<commit_before>var nlp = (function() {
    'use strict';

    var unitsForRegex = [
        "miles?",
        "foot",
        "feet",
        "ft",
        "fahrenheit",
        "yards?",
        "gallons?",
        "ounce",
        "oz",
        "pounds?",
        "inches",
        "inch",
        "in"
    ];

    function singularizeUnits(units) {
        return units.replace("miles", "mile")
            .replace("feet", "foot")
            .replace("fahrenheits", "fahrenheit")
            .replace("yards", "yard")
            .replace("gallons", "gallon")
            .replace("ounces", "ounce")
            .replace("pounds", "pound")
            .replace("inches", "inch");
    }

    function interpretNum(what) {
        what = what.replace(",", "");
        return parseFloat(what);
    }

    function multisearch(where) {
        var units = unitsForRegex.join("|"),
            numberRe = "([\\d,]*\\.?\\d+)",
            re = new RegExp(numberRe + "[\\s-]*(" + units + ")", "gi"),
            result,
            results = [];
        while (true) {
            result = re.exec(where);
            if (result === null) {
                break;
            }
            results.push({
                index: result.index,
                match: result[0],
                units: singularizeUnits(result[2].toLowerCase()),
                numeral: interpretNum(result[1])
            });
        }
        return results;
    }

    function reduceImperialUnitNames(name) {
        var abbrevs = {
            "oz": "ounce",
            "in": "inch",
            "ft": "foot"
        };
        if (abbrevs.hasOwnProperty(name)) {
            return abbrevs[name];
        }
        return name;
    }

    function roundDecimal(decimalStr, pos) {
        var dec = decimalStr.substring(0, pos).replace(/0+$/g, ''),
            trailing = decimalStr.substring(pos, pos + 1),
            rounded,
            carry = 0;
        if (trailing && parseInt(trailing, 10) >= 5) {
            rounded = parseFloat("0." + dec) + Math.pow(10, -pos);
            if (rounded >= 1.0) {
                carry = 1;
            }
            return {
                decimal: rounded.toString().substring(2, 2 + pos),
                carry: carry
            };
        }
        return {
            decimal: dec,
            carry: 0
        };
    }

    function roundForReadability(num) {
        var strRepr = num.toString(),
            dot = strRepr.indexOf("."),
            parts,
            whole,
            numSigDigits = 0,
            roundResult,
            strResult;
        if (dot === -1) {
            return num;
        }
        parts = strRepr.split(".");
        whole = parseInt(parts[0], 10);
        if (whole < 100) {
            numSigDigits = 1;
        }
        if (whole < 10) {
            numSigDigits = 2;
        }
        roundResult = roundDecimal(parts[1], numSigDigits);
        strResult = (whole + roundResult.carry).toString();
        if (roundResult.decimal !== "") {
            strResult = strResult + "." + roundResult.decimal;
        }
        return strResult;
    }

    function makeReadable(value, unit) {
        var unitMap = {
            "mile": "kilometers",
            "foot": "meters",
            "fahrenheit": "Celsius",
            "yard": "meters",
            "gallon": "liters",
            "ounce": "grams",
            "pound": "kilograms",
            "inch": "centimeters"
        },
            siUnit = unitMap[unit];
        // TODO: implement unit pluralization
        return roundForReadability(value) + " " + siUnit;
    }

    function convertImperialToSI(units, value) {
        var converters = {
            "mile": function(value) {
                return value * 1.6;
            },
            "foot": function(value) {
                return value * 0.3;
            },
            "fahrenheit": function(value) {
                return Math.round((value - 32) / 1.8);
            },
            "yard": function(value) {
                return value * 0.9;
            },
            "gallon": function(value) {
                return value * 3.78541;
            },
            "ounce": function(value) {
                return value * 28.3495;
            },
            "pound": function(value) {
                return value * 0.453592;
            },
            "inch": function(value) {
                return value * 2.54;
            }
        },
            reducedUnit = reduceImperialUnitNames(units),
            converter = converters[reducedUnit];
        if (converter) {
            return makeReadable(converter(value), reducedUnit);
        }
        return value + " " + units;
    }

    function isScriptNode(node) {
        if (node.nodeType !== Node.ELEMENT_NODE) {
            return false;
        }
        if (node.nodeName === "SCRIPT") {
            return true;
        }
        return false;
    }

    function getAllTextNodes(elem) {
        var filter = NodeFilter.SHOW_TEXT,
            walker = document.createTreeWalker(elem, filter, null, false),
            arr = [],
            node;
        while (walker.nextNode()) {
            node = walker.currentNode;
            if (node.parentNode && isScriptNode(node.parentNode)) {
                continue;
            }
            if (!node.isElementContentWhitespace) {
                arr.push(node);
            }
        }
        return arr;
    }

    function makeTextOrSpanNode(data) {
        if (!data.span) {
            return document.createTextNode(data.text);
        }
        var span = document.createElement('span');
        span.setAttribute("style", "background-color: yellow;");
        span.appendChild(document.createTextNode(data.text));
        return span;
    }

    function splitBySearchResults(text, matches) {
        var i = 0,
            match,
            plainText,
            si,
            textIndex = 0,
            results = [];
        while (i < matches.length) {
            match = matches[i];
            plainText = text.substring(textIndex, match.index);
            results.push({
                text: plainText,
                span: false
            });

            si = convertImperialToSI(match.units, match.numeral);
            textIndex = match.index + match.match.length;
            results.push({
                text: si,
                span: true
            });

            i += 1;
        }
        if (textIndex !== text.length) {
            results.push({
                text: text.substring(textIndex),
                span: false
            });
        }
        return results;
    }

    function multisearchTextNodes(nodes) {
        var resultArray = [];
        nodes.forEach(function(node) {
            var text = node.nodeValue,
                searchResults = multisearch(text);
            if (searchResults.length !== 0) {
                resultArray.push({
                    origNode: node,
                    replacement: splitBySearchResults(text, searchResults)
                });
            }
        });
        return resultArray;
    }

    function replaceTextNodes(newData) {
        newData.forEach(function(result) {
            var parentNode = result.origNode.parentNode;
            result.replacement.forEach(function(repl) {
                var newNode = makeTextOrSpanNode(repl);
                parentNode.insertBefore(newNode, result.origNode);
            });
            parentNode.removeChild(result.origNode);
        });
    }

    chrome.runtime.onMessage.addListener(function(rq, sender, sendResponse) {
        if (rq.method && (rq.method === "convertToSI")) {
            var textNodes = getAllTextNodes(document.body);
            replaceTextNodes(multisearchTextNodes(textNodes));
            sendResponse({"text": "ok"});
        }
    });

    return {
        reduceImperialUnitNames: reduceImperialUnitNames,
        unitsForRegex: unitsForRegex,
        convertImperialToSI: convertImperialToSI,
        singularizeUnits: singularizeUnits,
        roundDecimal: roundDecimal,
        multisearch: multisearch,
        getAllTextNodes: getAllTextNodes,
        splitBySearchResults: splitBySearchResults,
        roundForReadability: roundForReadability
    };
}());
<commit_msg>Add back highlight parameter implementation<commit_after>var nlp = (function() {
    'use strict';

    var unitsForRegex = [
        "miles?",
        "foot",
        "feet",
        "ft",
        "fahrenheit",
        "yards?",
        "gallons?",
        "ounce",
        "oz",
        "pounds?",
        "inches",
        "inch",
        "in"
    ];

    function singularizeUnits(units) {
        return units.replace("miles", "mile")
            .replace("feet", "foot")
            .replace("fahrenheits", "fahrenheit")
            .replace("yards", "yard")
            .replace("gallons", "gallon")
            .replace("ounces", "ounce")
            .replace("pounds", "pound")
            .replace("inches", "inch");
    }

    function interpretNum(what) {
        what = what.replace(",", "");
        return parseFloat(what);
    }

    function multisearch(where) {
        var units = unitsForRegex.join("|"),
            numberRe = "([\\d,]*\\.?\\d+)",
            re = new RegExp(numberRe + "[\\s-]*(" + units + ")", "gi"),
            result,
            results = [];
        while (true) {
            result = re.exec(where);
            if (result === null) {
                break;
            }
            results.push({
                index: result.index,
                match: result[0],
                units: singularizeUnits(result[2].toLowerCase()),
                numeral: interpretNum(result[1])
            });
        }
        return results;
    }

    function reduceImperialUnitNames(name) {
        var abbrevs = {
            "oz": "ounce",
            "in": "inch",
            "ft": "foot"
        };
        if (abbrevs.hasOwnProperty(name)) {
            return abbrevs[name];
        }
        return name;
    }

    function roundDecimal(decimalStr, pos) {
        var dec = decimalStr.substring(0, pos).replace(/0+$/g, ''),
            trailing = decimalStr.substring(pos, pos + 1),
            rounded,
            carry = 0;
        if (trailing && parseInt(trailing, 10) >= 5) {
            rounded = parseFloat("0." + dec) + Math.pow(10, -pos);
            if (rounded >= 1.0) {
                carry = 1;
            }
            return {
                decimal: rounded.toString().substring(2, 2 + pos),
                carry: carry
            };
        }
        return {
            decimal: dec,
            carry: 0
        };
    }

    function roundForReadability(num) {
        var strRepr = num.toString(),
            dot = strRepr.indexOf("."),
            parts,
            whole,
            numSigDigits = 0,
            roundResult,
            strResult;
        if (dot === -1) {
            return num;
        }
        parts = strRepr.split(".");
        whole = parseInt(parts[0], 10);
        if (whole < 100) {
            numSigDigits = 1;
        }
        if (whole < 10) {
            numSigDigits = 2;
        }
        roundResult = roundDecimal(parts[1], numSigDigits);
        strResult = (whole + roundResult.carry).toString();
        if (roundResult.decimal !== "") {
            strResult = strResult + "." + roundResult.decimal;
        }
        return strResult;
    }

    function makeReadable(value, unit) {
        var unitMap = {
            "mile": "kilometers",
            "foot": "meters",
            "fahrenheit": "Celsius",
            "yard": "meters",
            "gallon": "liters",
            "ounce": "grams",
            "pound": "kilograms",
            "inch": "centimeters"
        },
            siUnit = unitMap[unit];
        // TODO: implement unit pluralization
        return roundForReadability(value) + " " + siUnit;
    }

    function convertImperialToSI(units, value) {
        var converters = {
            "mile": function(value) {
                return value * 1.6;
            },
            "foot": function(value) {
                return value * 0.3;
            },
            "fahrenheit": function(value) {
                return Math.round((value - 32) / 1.8);
            },
            "yard": function(value) {
                return value * 0.9;
            },
            "gallon": function(value) {
                return value * 3.78541;
            },
            "ounce": function(value) {
                return value * 28.3495;
            },
            "pound": function(value) {
                return value * 0.453592;
            },
            "inch": function(value) {
                return value * 2.54;
            }
        },
            reducedUnit = reduceImperialUnitNames(units),
            converter = converters[reducedUnit];
        if (converter) {
            return makeReadable(converter(value), reducedUnit);
        }
        return value + " " + units;
    }

    function isScriptNode(node) {
        if (node.nodeType !== Node.ELEMENT_NODE) {
            return false;
        }
        if (node.nodeName === "SCRIPT") {
            return true;
        }
        return false;
    }

    function getAllTextNodes(elem) {
        var filter = NodeFilter.SHOW_TEXT,
            walker = document.createTreeWalker(elem, filter, null, false),
            arr = [],
            node;
        while (walker.nextNode()) {
            node = walker.currentNode;
            if (node.parentNode && isScriptNode(node.parentNode)) {
                continue;
            }
            if (!node.isElementContentWhitespace) {
                arr.push(node);
            }
        }
        return arr;
    }

    function makeTextOrSpanNode(data, highlight) {
        if (!data.span || !highlight) {
            return document.createTextNode(data.text);
        }
        var span = document.createElement('span');
        span.setAttribute("style", "background-color: yellow;");
        span.appendChild(document.createTextNode(data.text));
        return span;
    }

    function splitBySearchResults(text, matches) {
        var i = 0,
            match,
            plainText,
            si,
            textIndex = 0,
            results = [];
        while (i < matches.length) {
            match = matches[i];
            plainText = text.substring(textIndex, match.index);
            results.push({
                text: plainText,
                span: false
            });

            si = convertImperialToSI(match.units, match.numeral);
            textIndex = match.index + match.match.length;
            results.push({
                text: si,
                span: true
            });

            i += 1;
        }
        if (textIndex !== text.length) {
            results.push({
                text: text.substring(textIndex),
                span: false
            });
        }
        return results;
    }

    function multisearchTextNodes(nodes) {
        var resultArray = [];
        nodes.forEach(function(node) {
            var text = node.nodeValue,
                searchResults = multisearch(text);
            if (searchResults.length !== 0) {
                resultArray.push({
                    origNode: node,
                    replacement: splitBySearchResults(text, searchResults)
                });
            }
        });
        return resultArray;
    }

    function replaceTextNodes(newData, highlight) {
        newData.forEach(function(result) {
            var parentNode = result.origNode.parentNode;
            result.replacement.forEach(function(repl) {
                var newNode = makeTextOrSpanNode(repl, highlight);
                parentNode.insertBefore(newNode, result.origNode);
            });
            parentNode.removeChild(result.origNode);
        });
    }

    chrome.runtime.onMessage.addListener(function(rq, sender, sendResponse) {
        if (rq.method && (rq.method === "convertToSI")) {
            var textNodes = getAllTextNodes(document.body);
            replaceTextNodes(multisearchTextNodes(textNodes), rq.highlight);
            sendResponse({"text": "ok"});
        }
    });

    return {
        reduceImperialUnitNames: reduceImperialUnitNames,
        unitsForRegex: unitsForRegex,
        convertImperialToSI: convertImperialToSI,
        singularizeUnits: singularizeUnits,
        roundDecimal: roundDecimal,
        multisearch: multisearch,
        getAllTextNodes: getAllTextNodes,
        splitBySearchResults: splitBySearchResults,
        roundForReadability: roundForReadability
    };
}());
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2010 European Molecular Biology Laboratory
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
(function($, undefined) {
    if($ == undefined)
        throw "jQuery not loaded";

   $(function() {
        // this will be executed when DOM is ready
        if ($.query == undefined)
            throw "jQuery.query not loaded";

        if ($.browser.msie) {
            $("#head")[0].allowTransparency = true;
            $("#ae_contents")[0].style.zIndex = 1;
        }
    });

})(window.jQuery);
<commit_msg>jquery.query is not required here<commit_after>/*
 * Copyright 2009-2010 European Molecular Biology Laboratory
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
(function($, undefined) {
    if($ == undefined)
        throw "jQuery not loaded";

   $(function() {
        // this will be executed when DOM is ready
        if ($.browser.msie) {
            $("#head")[0].allowTransparency = true;
            $("#ae_contents")[0].style.zIndex = 1;
        }
    });

})(window.jQuery);
<|endoftext|>


<commit_before>function geneCount() {
	if ($('textarea#text-area').val())
    	$('span#gene-count').text($('textarea#text-area').val().trim().split(/\r?\n/g).length);
    else
    	$('span#gene-count').text(0);
}

function navigateTo(index) {
	if (_changingCategory)
		return;
	else
		_changingCategory = true;
	$('#content div.selected').fadeToggle('slow', function() {
		$('.selected').removeClass('selected');
		$('#navbar td').eq(index).addClass('selected');
		$('#content > div').eq(index).addClass('selected');
		$('#content div.selected').fadeToggle('slow');
		_changingCategory = false;
	});
}

function validateInput() {
	if ($('input#file-chooser').val())
		return true;
	else if ($('textarea#text-area').val())
		return true;
	else {
		alert("Nothing to analyze. Please select a file to upload or paste in a list of genes.");
		return false;
	}
}

function insertExample() {
	$.get('example_list.txt', function(data) {
		$('textarea#text-area').val(data);
		geneCount();
		$('#description input').val("Sample gene list");
	});
}

function createStats() {
	if (!$('#stats').hasClass('done')) {
		$.getJSON('dataset_statistics.json', function(json) {
			$('#stats').addClass('done');
			$('#stats').dataTable({
				"aaData": json,
				"aoColumns": [
					{
						"sTitle": "Gene-set Library",
						"fnRender": function(oObj, sVal) {
							return '' + sVal + '';
						}
					},
					{
						"sTitle": "Terms",
						"sClass": "right",
						"asSorting": ["desc", "asc"]
					},
					{
						"sTitle": "Gene Coverage",
						"sClass": "right",
						"asSorting": ["desc", "asc"]
					},
					{
						"sTitle": "Mean Genes per Term",
						"sClass": "right",
						"asSorting": ["desc", "asc"],
						"fnRender": function(obj) {
							return obj.aData[obj.iDataColumn].toFixed(4);
						}
					},
					{
						"bVisible": false
					}
				],
				"aaSorting": [[1, "desc"]],
				"bPaginate": false,
				"sDom": '<t>'
			});
		});
	}
}

$(document).ready(function () {
	$.ajaxSetup({ cache: false });	// Prevent IE from caching GET requests
	_changingCategory = false;	// Prevent changing category too fast
	// Load counter
	$.get('count', function(data) {
		$('div#count span').text(data);
		$('div#count').fadeIn('slow');
	})
	.error(function() { $('div#count').remove() });

	// Touch gestures
	$.fn.swipe.defaults.fallbackToMouseEvents = false;
	$('#content div').eq(0).swipe({
		swipeRight: function() {
			if (validateInput())
				document.forms['enrich'].submit();
		},
		fingers: 1
	});
	$('body').swipe({
		swipe: function(event, direction, distance, duration, fingerCount) {
			// if (fingerCount == 2) {
				if (direction == 'left')
					var dest = ($('div.selected').index() - 1) % 4
				else if (direction == 'right')
					var dest = ($('div.selected').index() + 1) % 4
				if (dest == 1)
					createStats();

				navigateTo(dest);
			// }
		},
		fingers: 2
	});
});<commit_msg>Separate function test<commit_after>function geneCount() {
	if ($('textarea#text-area').val())
    	$('span#gene-count').text($('textarea#text-area').val().trim().split(/\r?\n/g).length);
    else
    	$('span#gene-count').text(0);
}

function navigateTo(index) {
	if (_changingCategory)
		return;
	else
		_changingCategory = true;
	$('#content div.selected').fadeToggle('slow', function() {
		$('.selected').removeClass('selected');
		$('#navbar td').eq(index).addClass('selected');
		$('#content > div').eq(index).addClass('selected');
		$('#content div.selected').fadeToggle('slow');
		_changingCategory = false;
	});
}

function validateInput() {
	if ($('input#file-chooser').val())
		return true;
	else if ($('textarea#text-area').val())
		return true;
	else {
		alert("Nothing to analyze. Please select a file to upload or paste in a list of genes.");
		return false;
	}
}

function insertExample() {
	$.get('example_list.txt', function(data) {
		$('textarea#text-area').val(data);
		geneCount();
		$('#description input').val("Sample gene list");
	});
}

function createStats() {
	if (!$('#stats').hasClass('done')) {
		$.getJSON('dataset_statistics.json', function(json) {
			$('#stats').addClass('done');
			$('#stats').dataTable({
				"aaData": json,
				"aoColumns": [
					{
						"sTitle": "Gene-set Library",
						"fnRender": function(oObj, sVal) {
							return '' + sVal + '';
						}
					},
					{
						"sTitle": "Terms",
						"sClass": "right",
						"asSorting": ["desc", "asc"]
					},
					{
						"sTitle": "Gene Coverage",
						"sClass": "right",
						"asSorting": ["desc", "asc"]
					},
					{
						"sTitle": "Mean Genes per Term",
						"sClass": "right",
						"asSorting": ["desc", "asc"],
						"fnRender": function(obj) {
							return obj.aData[obj.iDataColumn].toFixed(4);
						}
					},
					{
						"bVisible": false
					}
				],
				"aaSorting": [[1, "desc"]],
				"bPaginate": false,
				"sDom": '<t>'
			});
		});
	}
}

$(document).ready(function () {
	$.ajaxSetup({ cache: false });	// Prevent IE from caching GET requests
	_changingCategory = false;	// Prevent changing category too fast
	// Load counter
	$.get('count', function(data) {
		$('div#count span').text(data);
		$('div#count').fadeIn('slow');
	})
	.error(function() { $('div#count').remove() });

	// Touch gestures
	$.fn.swipe.defaults.fallbackToMouseEvents = false;
	$('#content div').eq(0).swipe({
		swipeRight: function() {
			if (validateInput())
				document.forms['enrich'].submit();
		},
		fingers: 1
	});
	$('body').swipe({
		swipeLeft: function() {
			var dest = ($('div.selected').index() - 1) % 4;
			if (dest == 1)
				createStats();
			navigateTo(dest);
		},
		swipeRight: function() {
			var dest = ($('div.selected').index() + 1) % 4;
			if (dest == 1)
				createStats();
			navigateTo(dest);
		},
		fingers: 2
	});
});<|endoftext|>


<commit_before>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    consolidate = require('gulp-consolidate'),
    autoprefixer = require('gulp-autoprefixer'),
    shell = require('gulp-shell'),
    jshint= require('gulp-jshint'),
    livereload = require('gulp-livereload'),

    // iconfont = require('gulp-iconfont'),

    // svgstore = require('gulp-svgstore'),
    // svgmin = require('gulp-svgmin'),
    // path = require('path'),

    dummy = 'last';

// fix Promise() error from whiche package again?
// from the earlier days! require('es6-promise').polyfill();
var static_path = 'apps/{{ project_name }}/static/{{ project_name }}/';

// gulp.task('sass', ['iconfont', 'svgstore'], function () {
gulp.task('sass', function () {
    return gulp.src(static_path + 'sass/screen.sass')
        .pipe(sass({
                sourceComments: 'map',
                sourceMap: 'sass',
                outputStyle: 'nested'
            }).on('error', sass.logError))
        .pipe(autoprefixer("last 2 versions"))
        .pipe(gulp.dest(static_path + 'css/'))
});

// last used: losinger
gulp.task('svgstore', function () {
    return gulp
        .src(static_path + 'svgstore/*.svg')
        .pipe(cheerio({
            run: function ($) {
                //console.log($.xml());
                $('[fill]').removeAttr('fill');
                $('[style]').removeAttr('style');
            },
            parserOptions: { xmlMode: true }
        }))
        .pipe(svgmin(function (file) {
            var prefix = path.basename(file.relative, path.extname(file.relative));
            return {
                plugins: [{
                    cleanupIDs: {
                        prefix: prefix + '-',
                        minify: true
                    }
                }]
            }
        }))
        .pipe(svgstore({'inlineSvg': true}))
        .pipe(gulp.dest(static_path + '../../templates/{{ project_name }}/svgstore/'));
});

// last used: bos
gulp.task('iconfont', function () {
    var runTimestamp = Math.round(Date.now()/1000);
    return gulp.src([static_path + 'iconfont/svg/*.svg'])
        .pipe(iconfont({
                fontName: 'icons', // required
                normalize: true, // recommended option
                appendUnicode: false,
                fontHeight: 1000,
                formats: ['ttf', 'eot', 'woff'], // default, 'woff2' and 'svg' are available
                timestamp: runTimestamp // recommended to get consistent builds when watching files
            }
        )
    ).on('glyphs', function(glyphs, options) {
        // CSS templating, e.g.
        console.log(glyphs, options);
        gulp.src(static_path + 'iconfont/scss/_iconfont.scss')
            .pipe(consolidate('lodash', {
                glyphs: glyphs,
                fontName: 'icons',
                fontPath: '../iconfont/font/',
                className: 'icon'
            })
        )
        .pipe(gulp.dest(static_path + 'sass/'));
    })
    .pipe(gulp.dest(static_path + 'iconfont/font/'));
});

gulp.task('jshint', function () {
    return gulp.src(['gulpfile.js', static_path + 'js/**.js'])
        .pipe(jshint())
        .pipe(livereload());
});

gulp.task('flake8', shell.task(
        ['flake8 --ignore=errors']
    )
);

gulp.task('pip-compile', shell.task(
        [
            'pip-compile requirements/dev.in',
            'pip install -r requirements/dev.txt',
            'pip-compile requirements/deploy.in',
            'safety check',
            // let it get a bit older, until it really works
            // 'pip-sync requirements/dev.txt',
        ]
    )
);

gulp.task('pip-compile-upgrade', shell.task(
        [
            'pip-compile requirements/dev.in --upgrade',
            'pip install -r requirements/dev.txt',
            'pip-compile requirements/deploy.in --upgrade',
            'safety check',
            // let it get a bit older, until it really works
            // 'pip-sync requirements/dev.txt',
        ]
    )
);

gulp.task('node2static', function () {
    return gulp.src(
            [
              'node_modules/jquery/**/*',
              'node_modules/jquery-ui/**/*',
              'node_modules/slick-carousel/**/*',
              'node_modules/normalize-css/**/*',
              'node_modules/magnific-popup/**/*',
            ],
            {'base': 'node_modules', }
        )
        .pipe(gulp.dest(static_path + '/libs/'));
});

gulp.task('default', gulp.parallel('sass', 'node2static', 'pip-compile', 'jshint', 'flake8'));

gulp.task('watch', function () {
    livereload.listen();
    gulp.watch([
        'apps/**/*.html',
        'apps/**/*.py',
        static_path + 'css/*',
        static_path + 'js/*',
    ]).on('change', livereload.changed);
    gulp.watch(static_path + 'sass/*.sass', gulp.series('sass'));
    // gulp.watch(static_path + 'iconfont/svg/*.svg', ['iconfont']);
    // gulp.watch(static_path + 'svgstore/*.svg', ['svgstore']);
    gulp.watch('requirements/*.in', gulp.series('pip-compile'));
    gulp.watch(['gulpfile.js', static_path + 'js/**.js'], gulp.series('jshint'));
    gulp.watch('apps/**/*.py', gulp.series('flake8'));
});
<commit_msg>less repos space<commit_after>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    consolidate = require('gulp-consolidate'),
    autoprefixer = require('gulp-autoprefixer'),
    shell = require('gulp-shell'),
    jshint = require('gulp-jshint'),
    livereload = require('gulp-livereload'),

    // iconfont = require('gulp-iconfont'),

    // svgstore = require('gulp-svgstore'),
    // svgmin = require('gulp-svgmin'),
    // path = require('path'),

    dummy = 'last';

// fix Promise() error from whiche package again?
// from the earlier days! require('es6-promise').polyfill();
var static_path = 'apps/{{ project_name }}/static/{{ project_name }}/';

// gulp.task('sass', ['iconfont', 'svgstore'], function () {
gulp.task('sass', function () {
    return gulp.src(static_path + 'sass/screen.sass')
        .pipe(sass({
            sourceComments: 'map',
            sourceMap: 'sass',
            outputStyle: 'nested'
        }).on('error', sass.logError))
        .pipe(autoprefixer("last 2 versions"))
        .pipe(gulp.dest(static_path + 'css/'))
});

// last used: losinger
gulp.task('svgstore', function () {
    return gulp
        .src(static_path + 'svgstore/*.svg')
        .pipe(cheerio({
            run: function ($) {
                //console.log($.xml());
                $('[fill]').removeAttr('fill');
                $('[style]').removeAttr('style');
            },
            parserOptions: {xmlMode: true}
        }))
        .pipe(svgmin(function (file) {
            var prefix = path.basename(file.relative, path.extname(file.relative));
            return {
                plugins: [{
                    cleanupIDs: {
                        prefix: prefix + '-',
                        minify: true
                    }
                }]
            }
        }))
        .pipe(svgstore({'inlineSvg': true}))
        .pipe(gulp.dest(static_path + '../../templates/{{ project_name }}/svgstore/'));
});

// last used: bos
gulp.task('iconfont', function () {
    var runTimestamp = Math.round(Date.now() / 1000);
    return gulp.src([static_path + 'iconfont/svg/*.svg'])
        .pipe(iconfont({
                fontName: 'icons', // required
                normalize: true, // recommended option
                appendUnicode: false,
                fontHeight: 1000,
                formats: ['ttf', 'eot', 'woff'], // default, 'woff2' and 'svg' are available
                timestamp: runTimestamp // recommended to get consistent builds when watching files
            }
            )
        ).on('glyphs', function (glyphs, options) {
            // CSS templating, e.g.
            console.log(glyphs, options);
            gulp.src(static_path + 'iconfont/scss/_iconfont.scss')
                .pipe(consolidate('lodash', {
                        glyphs: glyphs,
                        fontName: 'icons',
                        fontPath: '../iconfont/font/',
                        className: 'icon'
                    })
                )
                .pipe(gulp.dest(static_path + 'sass/'));
        })
        .pipe(gulp.dest(static_path + 'iconfont/font/'));
});

gulp.task('jshint', function () {
    return gulp.src(['gulpfile.js', static_path + 'js/**.js'])
        .pipe(jshint())
        .pipe(livereload());
});

gulp.task('flake8', shell.task(
    ['flake8 --ignore=errors']
    )
);

gulp.task('pip-compile', shell.task(
    [
        'pip-compile requirements/dev.in',
        'pip install -r requirements/dev.txt',
        'pip-compile requirements/deploy.in',
        'safety check',
        // let it get a bit older, until it really works
        // 'pip-sync requirements/dev.txt',
    ]
    )
);

gulp.task('pip-compile-upgrade', shell.task(
    [
        'pip-compile requirements/dev.in --upgrade',
        'pip install -r requirements/dev.txt',
        'pip-compile requirements/deploy.in --upgrade',
        'safety check',
        // let it get a bit older, until it really works
        // 'pip-sync requirements/dev.txt',
    ]
    )
);

gulp.task('node2static', function () {
    // jquery/ui: (and other?!)
    // save some repository space, by adding specific sub folders only
    // base is always node_modules, so a folder jquery/dist will be made
    return gulp.src(
        [
            'node_modules/jquery/dist/*',
            'node_modules/jquery-ui/ui/widget.js',
            'node_modules/slick-carousel/**/*',
            'node_modules/normalize-css/**/*',  // size ok
            'node_modules/magnific-popup/**/*',
        ],
        {'base': 'node_modules',}
    )
        .pipe(gulp.dest(static_path + '/libs/'));
});

gulp.task('default', gulp.parallel('sass', 'node2static', 'pip-compile', 'jshint', 'flake8'));

gulp.task('watch', function () {
    livereload.listen();
    gulp.watch([
        'apps/**/*.html',
        'apps/**/*.py',
        static_path + 'css/*',
        static_path + 'js/*',
    ]).on('change', livereload.changed);
    gulp.watch(static_path + 'sass/*.sass', gulp.series('sass'));
    // gulp.watch(static_path + 'iconfont/svg/*.svg', ['iconfont']);
    // gulp.watch(static_path + 'svgstore/*.svg', ['svgstore']);
    gulp.watch('requirements/*.in', gulp.series('pip-compile'));
    gulp.watch(['gulpfile.js', static_path + 'js/**.js'], gulp.series('jshint'));
    gulp.watch('apps/**/*.py', gulp.series('flake8'));
});
<|endoftext|>


<commit_before>/***
 * this is the content script, which will be injected in all pages and checks if the page
 * defines a <meta name="dashboard" /> directive. If so it will setup refresh timers and
 * scroll to defined positions
 */
(function(chrome, document, window) {

    /***
     * Check if the page is a dashboard enabled page
     * Check if we can inject content scripts dynamically in iframes
     * - if so, we can add a post receive message between these frames
     */

    var isIframe = window.parent !== window && window.parent !== null,
        isDashboard = !isIframe && document.querySelectorAll("meta[name='dashboard']").length > 0,
        frames = [],
        iFrameClient = {
            reload: function() {
                window.location.reload();
            },
            addCss: function(data) {
                var css;

                if (data && data.style) {
                    css = document.createElement("style");
                    css.type = "text/css";
                    css.innerText = data.style;
                } else if (data && data.styleUrl) {
                    css = document.createElement("link");
                    css.rel = "stylesheet";
                    css.type = "text/css";
                    css.href = data.styleUrl;
                }

                if (!css) {
                    console.error("addCss method received invalid data.", data);
                    return;
                }

                var head = document.getElementsByTagName("head")[0];
                head.appendChild(css);
            }
        },
        dashboardClient = {
            ready: function(data, event) {

                // find frame
                for (var i = 0; i < frames.length; i++) {
                    var frame = frames[i];

                    if (frame.contentWindow === event.source) {
                        // found the frame

                        // send by the iframe, after the content script has been injected
                        processCssForFrame(frame);
                    }
                }

            }
        },
        client = isIframe ? iFrameClient : dashboardClient;

    if (isDashboard) {
        frames = Array.prototype.slice.call(document.querySelectorAll("iframe"));

        frames.forEach(function(frame) {
            frame.invoke = function(method, data) {
                // TODO: we could also read the origin from the iframe
                frame.contentWindow.postMessage({
                    method: method,
                    data: data
                }, "*");
            };

            var refreshRate = parseInt(frame.getAttribute("data-refresh"));
            if (!isNaN(refreshRate)) {
                // a number was given in seconds
                setInterval(function() {
                    frame.invoke("reload");

                }, refreshRate * 1000);
            }
        });
    } else {
        // Notify the dashboard that the content script has been loaded
        // so the dashboard can inject us the css
        window.parent.postMessage({
            method: "ready"
        }, "*");
    }

    window.addEventListener("message", function(event) {

        // TODO: check origin
        var data = event.data,
            method = client[data.method];

        if (method) {
            // method is available in client
            method(data.data, event)
        } else {
            console.log("No handler for method '"+ data.method + "' found!", event);
        }

    }, false);

    function processCssForFrame(frame) {
        var cssUri = frame.getAttribute("data-css"),
            css;

        if (cssUri === null) {
            return;
        }

        if (/^#/.test(cssUri)) {
            // css is references by id
            var scriptBlock = document.querySelector(cssUri);
            if (!scriptBlock) {
                console.error("References css block '" + cssUri + "' not found.");
                return;
            }

            css = {
                style: scriptBlock.innerText
            };

        } else {
            css = {
                styleUrl: cssUri
            };
        }

        frame.invoke("addCss", css);
    }

})(chrome, document, window);<commit_msg>save scroll position<commit_after>/***
 * this is the content script, which will be injected in all pages and checks if the page
 * defines a <meta name="dashboard" /> directive. If so it will setup refresh timers and
 * scroll to defined positions
 */
(function (chrome, document, window) {

    /***
     * Check if the page is a dashboard enabled page
     * Check if we can inject content scripts dynamically in iframes
     * - if so, we can add a post receive message between these frames
     */

    var isIframe = window.parent !== window && window.parent !== null,
        isDashboard = !isIframe && document.querySelectorAll("meta[name='dashboard']").length > 0,
        frames = [],
        framesLoading = {},
        iFrameClient = {
            reload: function () {
                window.location.reload();
            },
            addCss: function (data) {
                var css;

                if (data && data.style) {
                    css = document.createElement("style");
                    css.type = "text/css";
                    css.innerText = data.style;
                } else if (data && data.styleUrl) {
                    css = document.createElement("link");
                    css.rel = "stylesheet";
                    css.type = "text/css";
                    css.href = data.styleUrl;
                }

                if (!css) {
                    console.error("addCss method received invalid data.", data);
                    return;
                }

                var head = document.getElementsByTagName("head")[0];
                head.appendChild(css);
            },
            scrollTo: function (position) {
                window.scrollTo(position.pageXOffset, position.pageYOffset);
            }
        },
        dashboardClient = {

            _getIFrameForWindow: function (window) {
                // find frame
                for (var i = 0; i < frames.length; i++) {
                    var frame = frames[i];

                    if (frame.contentWindow === window) {
                        // found the frame
                        // send by the iframe, after the content script has been injected
                        return {
                            frame: frame,
                            index: i
                        };
                    }
                }

                return null;
            },

            _getUniqueKey: function () {
                return "dashboard" + location.pathname;
            },

            _save: function (key, value) {
                var uniqueKey = this._getUniqueKey();

                var data = JSON.parse(localStorage.getItem(uniqueKey) || "{}");

                data[key] = value;
                localStorage.setItem(uniqueKey, JSON.stringify(data));
            },

            _get: function (key, defaultValue) {
                var uniqueKey = this._getUniqueKey();
                var data = JSON.parse(localStorage.getItem(uniqueKey) || "{}");

                return data[key] || defaultValue;
            },

            ready: function (data, event) {
                var frame = this._getIFrameForWindow(event.source);
                frame && processCssForFrame(frame.frame);

                framesLoading[frame.index] = false;

                var scrollPosition = this._get("frame_" + frame.index);
                if (scrollPosition) {
                    frame.frame.invoke("scrollTo", scrollPosition);
                }

            },

            scrolled: function (data, event) {

                if (!window.localStorage) {
                    return;
                }

                var frame = this._getIFrameForWindow(event.source);
                if (frame && framesLoading[frame.index] !== true) {
                    // save scroll position in localStorage
                    this._save("frame_" + frame.index, data);
                }
            }
        },
        client = isIframe ? iFrameClient : dashboardClient;

    if (isDashboard) {
        frames = Array.prototype.slice.call(document.querySelectorAll("iframe"));

        frames.forEach(function (frame, index) {
            framesLoading[index] = true;

            frame.invoke = function (method, data) {
                // TODO: we could also read the origin from the iframe
                frame.contentWindow.postMessage({
                    method: method,
                    data: data
                }, "*");
            };

            var refreshRate = parseInt(frame.getAttribute("data-refresh"));
            if (!isNaN(refreshRate)) {
                // a number was given in seconds
                setInterval(function () {
                    frame.invoke("reload");
                }, refreshRate * 1000);
            }
        });
    } else {
        // Notify the dashboard that the content script has been loaded
        // so the dashboard can inject us the css
        window.parent.postMessage({
            method: "ready"
        }, "*");

        window.addEventListener("scroll", function () {
            window.parent.postMessage({
                method: "scrolled",
                data: {
                    pageXOffset: window.pageXOffset,
                    pageYOffset: window.pageYOffset
                }
            }, "*");
        }, false);

    }

    window.addEventListener("message", function (event) {

        // TODO: check origin
        var data = event.data,
            method = client[data.method];

        if (/^_/.test(data.method || "")) {
            // private method
            return;
        }

        if (method) {
            // method is available in client
            method.call(client, data.data, event)
        } else {
            console.log("No handler for method '" + data.method + "' found!", event);
        }

    }, false);

    function processCssForFrame(frame) {
        var cssUri = frame.getAttribute("data-css"),
            css;

        if (cssUri === null) {
            return;
        }

        if (/^#/.test(cssUri)) {
            // css is references by id
            var scriptBlock = document.querySelector(cssUri);
            if (!scriptBlock) {
                console.error("References css block '" + cssUri + "' not found.");
                return;
            }

            css = {
                style: scriptBlock.innerText
            };

        } else {
            css = {
                styleUrl: cssUri
            };
        }

        frame.invoke("addCss", css);
    }

})(chrome, document, window);<|endoftext|>


<commit_before>
/*
  Utility to make a sub-tree of the DOM inert. Inert means the elements cannot be interacted
  with and they cannot be focused via script, pointer or keyboard.

  inert attribute was [removed](https://html5.org/r/8536) [tweet by steve](https://twitter.com/stevefaulkner/status/443075900201259008)
  but definition of [inert subtrees](http://www.w3.org/html/wg/drafts/html/master/editing.html#inert-subtrees) remains.

  [implementation idea by Vasilis](http://codepen.io/vasilisvg/pen/scowI)
  [inert attribute polyfill by GoogleChrome](https://github.com/GoogleChrome/inert-polyfill)

  [Gecko Bug: Inert Attribute](https://bugzilla.mozilla.org/show_bug.cgi?id=921504)
  [Chromium Bug: Inert Attribute](https://code.google.com/p/chromium/issues/detail?id=269846)
  [Chromium Bug: Inert Subtree](https://code.google.com/p/chromium/issues/detail?id=241699)
  [WebKit Bug: Inert Subtree](https://bugs.webkit.org/show_bug.cgi?id=110952)
*/

import nodeArray from '../util/node-array';
import queryFocusable from '../query/focusable';
import elementDisabled from '../element/disabled';

function makeElementInert(element) {
  return elementDisabled(element, true);
}

function undoElementInert(element) {
  return elementDisabled(element, false);
}

const observerConfig = {
  attributes: true,
  childList: true,
  subtree: true,
  attributeFilter: ['tabindex'],
};

class InertSubtree {
  constructor({context, filter} = {}) {
    this._context = nodeArray(context || document.documentElement);
    this._filter = nodeArray(filter);

    this.disengage = this.disengage.bind(this);
    this.handleMutations = this.handleMutations.bind(this);
    this.handleMutation = this.handleMutation.bind(this);
    this.renderInert = this.renderInert.bind(this);
    this.filterContext = this.filterContext.bind(this);
    this.filterElements = this.filterElements.bind(this);

    const focusable = this.listQueryFocusable(this._context);
    this.renderInert(focusable);
    this.startObserver();
  }

  disengage() {
    if (!this._context) {
      return;
    }

    this._context.forEach(function(element) {
      undoElementInert(element);
      [].forEach.call(element.querySelectorAll('[data-ally-disabled], :disabled'), undoElementInert);
    });

    this._filter = null;
    this._context = null;
    this._observer && this._observer.disconnect();
  }

  listQueryFocusable(list) {
    return list
      // find all focusable elements within the given contexts
      .map(element => queryFocusable({context: element, includeContext: true, strategy: 'all'}))
      // flatten nested arrays
      .reduce((previous, current) => previous.concat(current), []);
  }

  renderInert(elements) {
    elements.filter(this.filterElements).forEach(makeElementInert);
  }

  filterContext(element) {
    // ignore elements that are not within the context sub-trees
    return this._context.some(function(_context) {
      // Node.compareDocumentPosition is available since IE9
      return element === _context || _context.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_CONTAINED_BY;
    });
  }

  filterElements(element) {
    if (element === document.body && !element.hasAttribute('tabindex')) {
      // ignore the body (default focus element) unless it was made focusable
      return false;
    }

    // ignore elements within the exempted sub-trees
    return !this._filter.some(function(_except) {
      // Node.compareDocumentPosition is available since IE9
      return element === _except || _except.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_CONTAINED_BY;
    });
  }

  startObserver() {
    if (!window.MutationObserver) {
      // not supporting IE10 via Mutation Events, because they're too expensive
      // https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
      return;
    }
    // http://caniuse.com/#search=mutation
    // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
    this._observer = new MutationObserver(this.handleMutations);
    this._observer.observe(
      // we don't need to observe the entire document unless there are multiple contexts in play
      this._context.length === 1 ? this._context[0] : document.documentElement,
      observerConfig
    );
  }

  handleMutations(mutations) {
    mutations.forEach(this.handleMutation);
  }

  handleMutation(mutation) {
    if (mutation.type === 'childList') {
      const addedElements = nodeArray(mutation.addedNodes).filter(element => element.nodeType === Node.ELEMENT_NODE);
      if (!addedElements.length) {
        return;
      }

      const addedFocusableElements = this.listQueryFocusable(addedElements);
      this.renderInert(addedFocusableElements);
    } else if (mutation.type === 'attribute' && !this.filterElements(mutation.target) && this.filterContext(mutation.target)) {
      makeElementInert(mutation.target);
    }
  }
}

export default function({context, filter} = {}) {
  var service = new InertSubtree({context, filter});
  return { disengage: service.disengage };
}
<commit_msg>refactor(maintain/disabled): DRYing sub-tree filtering<commit_after>
/*
  Utility to make a sub-tree of the DOM inert. Inert means the elements cannot be interacted
  with and they cannot be focused via script, pointer or keyboard.

  inert attribute was [removed](https://html5.org/r/8536) [tweet by steve](https://twitter.com/stevefaulkner/status/443075900201259008)
  but definition of [inert subtrees](http://www.w3.org/html/wg/drafts/html/master/editing.html#inert-subtrees) remains.

  [implementation idea by Vasilis](http://codepen.io/vasilisvg/pen/scowI)
  [inert attribute polyfill by GoogleChrome](https://github.com/GoogleChrome/inert-polyfill)

  [Gecko Bug: Inert Attribute](https://bugzilla.mozilla.org/show_bug.cgi?id=921504)
  [Chromium Bug: Inert Attribute](https://code.google.com/p/chromium/issues/detail?id=269846)
  [Chromium Bug: Inert Subtree](https://code.google.com/p/chromium/issues/detail?id=241699)
  [WebKit Bug: Inert Subtree](https://bugs.webkit.org/show_bug.cgi?id=110952)
*/

import nodeArray from '../util/node-array';
import queryFocusable from '../query/focusable';
import elementDisabled from '../element/disabled';

function makeElementInert(element) {
  return elementDisabled(element, true);
}

function undoElementInert(element) {
  return elementDisabled(element, false);
}

function containedByElement(element) {
  // callback returns true when element is contained by parent or is the parent
  // suited for use with Array.some()
  return function(parent) {
    // Node.compareDocumentPosition is available since IE9
    // see https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
    return element === parent || parent.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_CONTAINED_BY;
  };
}

const observerConfig = {
  attributes: true,
  childList: true,
  subtree: true,
  attributeFilter: ['tabindex'],
};

class InertSubtree {
  constructor({context, filter} = {}) {
    this._context = nodeArray(context || document.documentElement);
    this._filter = nodeArray(filter);

    this.disengage = this.disengage.bind(this);
    this.handleMutations = this.handleMutations.bind(this);
    this.handleMutation = this.handleMutation.bind(this);
    this.renderInert = this.renderInert.bind(this);
    this.filterContext = this.filterContext.bind(this);
    this.filterElements = this.filterElements.bind(this);

    const focusable = this.listQueryFocusable(this._context);
    this.renderInert(focusable);
    this.startObserver();
  }

  disengage() {
    if (!this._context) {
      return;
    }

    this._context.forEach(function(element) {
      undoElementInert(element);
      [].forEach.call(element.querySelectorAll('[data-ally-disabled], :disabled'), undoElementInert);
    });

    this._filter = null;
    this._context = null;
    this._observer && this._observer.disconnect();
  }

  listQueryFocusable(list) {
    return list
      // find all focusable elements within the given contexts
      .map(element => queryFocusable({context: element, includeContext: true, strategy: 'all'}))
      // flatten nested arrays
      .reduce((previous, current) => previous.concat(current), []);
  }

  renderInert(elements) {
    elements.filter(this.filterElements).forEach(makeElementInert);
  }

  filterContext(element) {
    // ignore elements that are not within the context sub-trees
    const contained = containedByElement(element);
    return this._context.some(contained);
  }

  filterElements(element) {
    if (element === document.body && !element.hasAttribute('tabindex')) {
      // ignore the body (default focus element) unless it was made focusable
      return false;
    }

    // ignore elements within the exempted sub-trees
    const containsElement = containedByElement(element);
    return !this._filter.some(containsElement);
  }

  startObserver() {
    if (!window.MutationObserver) {
      // not supporting IE10 via Mutation Events, because they're too expensive
      // https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
      return;
    }
    // http://caniuse.com/#search=mutation
    // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
    this._observer = new MutationObserver(this.handleMutations);
    this._observer.observe(
      // we don't need to observe the entire document unless there are multiple contexts in play
      this._context.length === 1 ? this._context[0] : document.documentElement,
      observerConfig
    );
  }

  handleMutations(mutations) {
    mutations.forEach(this.handleMutation);
  }

  handleMutation(mutation) {
    if (mutation.type === 'childList') {
      const addedElements = nodeArray(mutation.addedNodes).filter(element => element.nodeType === Node.ELEMENT_NODE);
      if (!addedElements.length) {
        return;
      }

      const addedFocusableElements = this.listQueryFocusable(addedElements);
      this.renderInert(addedFocusableElements);
    } else if (mutation.type === 'attribute' && !this.filterElements(mutation.target) && this.filterContext(mutation.target)) {
      makeElementInert(mutation.target);
    }
  }
}

export default function({context, filter} = {}) {
  var service = new InertSubtree({context, filter});
  return { disengage: service.disengage };
}
<|endoftext|>


<commit_before>var gulp = require("gulp"),
	plugins = require("gulp-load-plugins")();

// Options
var options = {
	autoprefixer: {
		map: true,
		from: "placeholder",
		to: "style.min.css"
	},
	rename: {
		suffix: ".min"
	},
	clean: {
		read: false
	}
};

var paths = {
	scripts: [
	 	"src/*.js"
	],
	styles: [
		"src/*.css"
	]
};

gulp.task("scripts", function () {
	"use strict";
	return gulp.src(paths.scripts)
		.pipe(plugins.jshint(".jshintrc"))
		.pipe(plugins.jshint.reporter("jshint-stylish"))
		.pipe(gulp.dest("./build"))
		.pipe(plugins.filesize())
		.pipe(plugins.uglify())
		.pipe(plugins.rename(options.rename))
		.pipe(gulp.dest("./build"))
		.pipe(plugins.filesize());
});

gulp.task("styles", function () {
	"use strict";
	return gulp.src(paths.styles)
		.pipe(plugins.autoprefixer(["last 1 version", "> 1%", "ie 8", "ie 7"], options.autoprefixer))
		.pipe(gulp.dest("./build"))
		.pipe(plugins.filesize())
		.pipe(plugins.minifyCss())
		.pipe(plugins.rename(options.rename))
		.pipe(gulp.dest("./build"))
		.pipe(plugins.filesize());
});

gulp.task("clean", function () {
	"use strict";
	return gulp.src("./build", options.clean)
		.pipe(plugins.clean());
});

gulp.task("default", ["clean"], function () {
	"use strict";
	gulp.start("watch");
});

gulp.task("watch", ["styles", "scripts"], function () {
	"use strict";

	// Watch .css files
	gulp.watch(paths.styles, ["styles"]);

	// Watch .js files
	gulp.watch(paths.scripts, ["scripts"]);
});<commit_msg>Removes duplicate filesize call<commit_after>var gulp = require("gulp"),
	plugins = require("gulp-load-plugins")();

// Options
var options = {
	autoprefixer: {
		map: true,
		from: "placeholder",
		to: "style.min.css"
	},
	rename: {
		suffix: ".min"
	},
	clean: {
		read: false
	}
};

var paths = {
	scripts: [
	 	"src/*.js"
	],
	styles: [
		"src/*.css"
	]
};

gulp.task("scripts", function () {
	"use strict";
	return gulp.src(paths.scripts)
		.pipe(plugins.jshint(".jshintrc"))
		.pipe(plugins.jshint.reporter("jshint-stylish"))
		.pipe(gulp.dest("./build"))
		.pipe(plugins.uglify())
		.pipe(plugins.rename(options.rename))
		.pipe(gulp.dest("./build"))
		.pipe(plugins.filesize());
});

gulp.task("styles", function () {
	"use strict";
	return gulp.src(paths.styles)
		.pipe(plugins.autoprefixer(["last 1 version", "> 1%", "ie 8", "ie 7"], options.autoprefixer))
		.pipe(gulp.dest("./build"))
		.pipe(plugins.minifyCss())
		.pipe(plugins.rename(options.rename))
		.pipe(gulp.dest("./build"))
		.pipe(plugins.filesize());
});

gulp.task("clean", function () {
	"use strict";
	return gulp.src("./build", options.clean)
		.pipe(plugins.clean());
});

gulp.task("default", ["clean"], function () {
	"use strict";
	gulp.start("watch");
});

gulp.task("watch", ["styles", "scripts"], function () {
	"use strict";

	// Watch .css files
	gulp.watch(paths.styles, ["styles"]);

	// Watch .js files
	gulp.watch(paths.scripts, ["scripts"]);
});<|endoftext|>


<commit_before>(function() {
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
  var actions = {
    gyazoCapture: function() {
      var startX, startY, data = {};
      var tempUserSelect = document.body.style.webkitUserSelect;
      var layer = document.createElement('div');
      layer.style.position = 'fixed';
      layer.style.left = document.body.clientLeft;
      layer.style.top = document.body.clientTop;
      layer.style.width = document.body.clientWidth + 'px';
      layer.style.height = document.body.clientHeight + 'px';
      layer.style.zIndex = 2147483647; //Maximun number of 32bit Int
      layer.style.cursor = 'crosshair';
      document.body.style.webkitUserSelect = 'none';
      var selectionElm = document.createElement('div');
      layer.appendChild(selectionElm);
      document.body.appendChild(layer);
      selectionElm.styleUpdate = function(styles) {
        Object.keys(styles).forEach(function(key) {
          selectionElm.style[key] = styles[key];
        });
      };
      selectionElm.styleUpdate({
        background: 'rgba(92, 92, 92, 0.3)',
        position: 'fixed'
      });
      var cancelGyazo = function(){
        document.body.removeChild(layer);
        document.body.style.webkitUserSelect = tempUserSelect;
        document.removeEventListener('keydown', keydownHandler);
        window.removeEventListener('contextmenu', cancelGyazo);
      }
      var keydownHandler = function(e){
        // If press Esc Key, cancel it
        if(e.keyCode === 27){
          cancelGyazo();
        }
      };
      var mousedownHandler = function(e) {
        startX = e.clientX;
        startY = e.clientY;
        selectionElm.styleUpdate({
          border: '1px solid rgba(255, 255, 255, 0.8)',
          left: startX + 'px',
          top: startY + 'px'
        });
        layer.removeEventListener('mousedown', mousedownHandler);
        layer.addEventListener('mousemove', mousemoveHandler);
        layer.addEventListener('mouseup', mouseupHandler);
      };
      var mousemoveHandler = function(e) {
        selectionElm.styleUpdate({
          width: (Math.abs(e.clientX - startX) - 1) + 'px',
          height: (Math.abs(e.clientY - startY) - 1) + 'px',
          left: Math.min(e.clientX, startX) + 'px',
          top: Math.min(e.clientY, startY) + 'px'
        });
      };
      var mouseupHandler = function(e) {
        document.body.style.webkitUserSelect = tempUserSelect;
        document.removeEventListener('keydown', keydownHandler);
        window.addEventListener('contextmenu', function(event){
          cancelGyazo();
          event.preventDefault();
        });
        data.w = Math.abs(e.clientX - startX);
        data.h = Math.abs(e.clientY - startY);
        if(data.h < 1 || data.w < 1){
          document.body.removeChild(layer);
          return false;
        }
        data.x = Math.min(e.clientX, startX);
        data.y = Math.min(e.clientY, startY);
        data.t = document.title;
        data.u = location.href;
        data.s = window.devicePixelRatio;
        document.body.removeChild(layer);
        //wait for rewrite by removeChild
        window.setTimeout(function() {
          chrome.runtime.sendMessage(chrome.runtime.id,{
            action: 'gyazoCaptureSize',
            data: data
          }, function(){});
        },100);
      };
      layer.addEventListener('mousedown', mousedownHandler);
      document.addEventListener('keydown', keydownHandler);
      window.addEventListener('contextmenu', cancelGyazo);
      layer.addEventListener('mousedown',mousedownHandler);
    },
    wholeCaptureInit: function() {
      var context = request.context;
      context.scrollY = window.scrollY;
      context.overflow = document.documentElement.style.overflow;
      context.overflowY = document.documentElement.style.overflowY;
      document.documentElement.style.overflow = 'hidden';
      document.documentElement.style.overflowY = 'hidden';
      //I want twitter bootstrap's navigation bar not to follow scrolling
      var fixedTopNavs = document.getElementsByClassName('navbar-fixed-top');
      Array.prototype.slice.apply(fixedTopNavs).forEach(function(element, index){
        element.style.position = 'absolute';
      });
      window.scroll(0, 0);
      var data = {
        width: document.body.clientWidth,
        height: document.body.clientHeight,
        windowInnerHeight: window.innerHeight,
        title: document.title,
        url: location.href,
        captureTop: 0,
        captureButtom: window.innerHeight
      };
      //waiting for repaint after scroll
      window.setTimeout(function(){
        chrome.runtime.sendMessage(chrome.runtime.id,{
          action: 'wholeCaptureManager',
          data: data,
          context: context
        });
      }, 50);
    },
    scrollNextPage: function(){
      var data = request.data;
      var captureTop = data.captureButtom;
      var captureButtom = captureTop + window.innerHeight;
      window.scroll(0, captureTop);
      data.captureTop = captureTop;
      data.captureButtom = captureButtom;
      window.setTimeout(function(){
        chrome.runtime.sendMessage(chrome.runtime.id,{
          action: 'wholeCaptureManager',
          canvasData: request.canvasData,
          data: data,
          context: request.context
        });
      }, 50);
    },
    wholeCaptureFinish: function(){
      document.documentElement.style.overflow = request.context.overflow;
      document.documentElement.style.overflowY = request.context.overflowY;
      var fixedTop = document.getElementsByClassName('navbar-fixed-top');
      Array.prototype.slice.apply(fixedTop).forEach(function(element, index){
        element.style.position = 'fixed';
      });
      window.scroll(0, request.context.scrollY);
    }
  };
  if(request.action in actions){
    actions[request.action]();
  }
});
})()
<commit_msg>get page height 3ways<commit_after>(function() {
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
  var actions = {
    gyazoCapture: function() {
      var startX, startY, data = {};
      var tempUserSelect = document.body.style.webkitUserSelect;
      var layer = document.createElement('div');
      layer.style.position = 'fixed';
      layer.style.left = document.body.clientLeft;
      layer.style.top = document.body.clientTop;
      layer.style.width = document.body.clientWidth + 'px';
      layer.style.height = document.body.clientHeight + 'px';
      layer.style.zIndex = 2147483647; //Maximun number of 32bit Int
      layer.style.cursor = 'crosshair';
      document.body.style.webkitUserSelect = 'none';
      var selectionElm = document.createElement('div');
      layer.appendChild(selectionElm);
      document.body.appendChild(layer);
      selectionElm.styleUpdate = function(styles) {
        Object.keys(styles).forEach(function(key) {
          selectionElm.style[key] = styles[key];
        });
      };
      selectionElm.styleUpdate({
        background: 'rgba(92, 92, 92, 0.3)',
        position: 'fixed'
      });
      var cancelGyazo = function(){
        document.body.removeChild(layer);
        document.body.style.webkitUserSelect = tempUserSelect;
        document.removeEventListener('keydown', keydownHandler);
        window.removeEventListener('contextmenu', cancelGyazo);
      }
      var keydownHandler = function(e){
        // If press Esc Key, cancel it
        if(e.keyCode === 27){
          cancelGyazo();
        }
      };
      var mousedownHandler = function(e) {
        startX = e.clientX;
        startY = e.clientY;
        selectionElm.styleUpdate({
          border: '1px solid rgba(255, 255, 255, 0.8)',
          left: startX + 'px',
          top: startY + 'px'
        });
        layer.removeEventListener('mousedown', mousedownHandler);
        layer.addEventListener('mousemove', mousemoveHandler);
        layer.addEventListener('mouseup', mouseupHandler);
      };
      var mousemoveHandler = function(e) {
        selectionElm.styleUpdate({
          width: (Math.abs(e.clientX - startX) - 1) + 'px',
          height: (Math.abs(e.clientY - startY) - 1) + 'px',
          left: Math.min(e.clientX, startX) + 'px',
          top: Math.min(e.clientY, startY) + 'px'
        });
      };
      var mouseupHandler = function(e) {
        document.body.style.webkitUserSelect = tempUserSelect;
        document.removeEventListener('keydown', keydownHandler);
        window.addEventListener('contextmenu', function(event){
          cancelGyazo();
          event.preventDefault();
        });
        data.w = Math.abs(e.clientX - startX);
        data.h = Math.abs(e.clientY - startY);
        if(data.h < 1 || data.w < 1){
          document.body.removeChild(layer);
          return false;
        }
        data.x = Math.min(e.clientX, startX);
        data.y = Math.min(e.clientY, startY);
        data.t = document.title;
        data.u = location.href;
        data.s = window.devicePixelRatio;
        document.body.removeChild(layer);
        //wait for rewrite by removeChild
        window.setTimeout(function() {
          chrome.runtime.sendMessage(chrome.runtime.id,{
            action: 'gyazoCaptureSize',
            data: data
          }, function(){});
        },100);
      };
      layer.addEventListener('mousedown', mousedownHandler);
      document.addEventListener('keydown', keydownHandler);
      window.addEventListener('contextmenu', cancelGyazo);
      layer.addEventListener('mousedown',mousedownHandler);
    },
    wholeCaptureInit: function() {
      var context = request.context;
      context.scrollY = window.scrollY;
      context.overflow = document.documentElement.style.overflow;
      context.overflowY = document.documentElement.style.overflowY;
      document.documentElement.style.overflow = 'hidden';
      document.documentElement.style.overflowY = 'hidden';
      //I want twitter bootstrap's navigation bar not to follow scrolling
      var fixedTopNavs = document.getElementsByClassName('navbar-fixed-top');
      Array.prototype.slice.apply(fixedTopNavs).forEach(function(element, index){
        element.style.position = 'absolute';
      });
      window.scroll(0, 0);
      var data = {
        width: document.body.clientWidth,
        height: Math.max(document.body.clientHeight, document.body.offsetHeight, document.body.scrollHeight),
        windowInnerHeight: window.innerHeight,
        title: document.title,
        url: location.href,
        captureTop: 0,
        captureButtom: window.innerHeight
      };
      //waiting for repaint after scroll
      window.setTimeout(function(){
        chrome.runtime.sendMessage(chrome.runtime.id,{
          action: 'wholeCaptureManager',
          data: data,
          context: context
        });
      }, 50);
    },
    scrollNextPage: function(){
      var data = request.data;
      var captureTop = data.captureButtom;
      var captureButtom = captureTop + window.innerHeight;
      window.scroll(0, captureTop);
      data.captureTop = captureTop;
      data.captureButtom = captureButtom;
      window.setTimeout(function(){
        chrome.runtime.sendMessage(chrome.runtime.id,{
          action: 'wholeCaptureManager',
          canvasData: request.canvasData,
          data: data,
          context: request.context
        });
      }, 50);
    },
    wholeCaptureFinish: function(){
      document.documentElement.style.overflow = request.context.overflow;
      document.documentElement.style.overflowY = request.context.overflowY;
      var fixedTop = document.getElementsByClassName('navbar-fixed-top');
      Array.prototype.slice.apply(fixedTop).forEach(function(element, index){
        element.style.position = 'fixed';
      });
      window.scroll(0, request.context.scrollY);
    }
  };
  if(request.action in actions){
    actions[request.action]();
  }
});
})()
<|endoftext|>


<commit_before>var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var mainBowerFiles = require('main-bower-files');
var del = require('del');
var runSequence = require('run-sequence');

function js(shouldMinify) {
  return gulp.src(mainBowerFiles().concat([ // not taking wildcards
    './webserver/public/js/controllers/**',
    './webserver/public/js/charting/**',
    './webserver/public/js/directives/**',
    './webserver/public/js/**'
  ]))
      .pipe(plugins.filter('*.js'))
      .pipe(plugins.concat('scripts.js'))
      .pipe(plugins.if(shouldMinify, plugins.ngAnnotate()))
      .pipe(plugins.if(shouldMinify, plugins.uglify()))
      .pipe(gulp.dest('./webserver/public/build'));
}

function css(shouldMinify) {
  return gulp.src(mainBowerFiles().concat(['./webserver/public/less/*.less']))
      .pipe(plugins.filter(['*.css', '*.less']))
      .pipe(plugins.less())
      .pipe(plugins.concat('style.css'))
      .pipe(plugins.if(shouldMinify, plugins.minifyCss({keepBreaks: true})))
      .pipe(gulp.dest('./webserver/public/build'));
}

gulp.task('clean', function () {
  return del([
    './webserver/public/build/*',
    './webserver/public/fonts/*'
  ]);
});

gulp.task('copy-fonts', function () {
  return gulp.src('./webserver/public/bower_components/bootstrap/fonts/*')
      .pipe(plugins.copy('./webserver/public/fonts/', {prefix: 5}))
});

gulp.task('lint', function () {
  return gulp.src('./webserver/public/js/**')
      .pipe(plugins.jshint())
      .pipe(plugins.jshint.reporter('default'))
});

gulp.task('js-dev', function () {
  return js(false);
});

gulp.task('js-prod', function () {
  return js(true);
});

gulp.task('css-prod', function () {
  return css(true);
});

gulp.task('build', function () {
  return runSequence('clean', ['copy-fonts', 'js-prod', 'css-prod']);
});

gulp.task('watch', function () {
  gulp.watch('./webserver/public/bower_components/**/*', ['css', 'js-dev']);
  gulp.watch('./webserver/public/js/**', ['js-dev']);
  gulp.watch('./webserver/public/less/*', ['css']);
});

gulp.task('default', ['build']);<commit_msg>fix: fix reference to css gulp task<commit_after>var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var mainBowerFiles = require('main-bower-files');
var del = require('del');
var runSequence = require('run-sequence');

function js(shouldMinify) {
  return gulp.src(mainBowerFiles().concat([ // not taking wildcards
    './webserver/public/js/controllers/**',
    './webserver/public/js/charting/**',
    './webserver/public/js/directives/**',
    './webserver/public/js/**'
  ]))
      .pipe(plugins.filter('*.js'))
      .pipe(plugins.concat('scripts.js'))
      .pipe(plugins.if(shouldMinify, plugins.ngAnnotate()))
      .pipe(plugins.if(shouldMinify, plugins.uglify()))
      .pipe(gulp.dest('./webserver/public/build'));
}

function css(shouldMinify) {
  return gulp.src(mainBowerFiles().concat(['./webserver/public/less/*.less']))
      .pipe(plugins.filter(['*.css', '*.less']))
      .pipe(plugins.less())
      .pipe(plugins.concat('style.css'))
      .pipe(plugins.if(shouldMinify, plugins.minifyCss({keepBreaks: true})))
      .pipe(gulp.dest('./webserver/public/build'));
}

gulp.task('clean', function () {
  return del([
    './webserver/public/build/*',
    './webserver/public/fonts/*'
  ]);
});

gulp.task('copy-fonts', function () {
  return gulp.src('./webserver/public/bower_components/bootstrap/fonts/*')
      .pipe(plugins.copy('./webserver/public/fonts/', {prefix: 5}))
});

gulp.task('lint', function () {
  return gulp.src('./webserver/public/js/**')
      .pipe(plugins.jshint())
      .pipe(plugins.jshint.reporter('default'))
});

gulp.task('js-dev', function () {
  return js(false);
});

gulp.task('js-prod', function () {
  return js(true);
});

gulp.task('css-prod', function () {
  return css(true);
});

gulp.task('build', function () {
  return runSequence('clean', ['copy-fonts', 'js-prod', 'css-prod']);
});

gulp.task('watch', function () {
  gulp.watch('./webserver/public/bower_components/**/*', ['css-prod', 'js-dev']);
  gulp.watch('./webserver/public/js/**', ['js-dev']);
  gulp.watch('./webserver/public/less/*', ['css-prod']);
});

gulp.task('default', ['build']);<|endoftext|>


<commit_before>var traits = [

	// thanks to Stephen Dobson
	"frustrated poet",
	"tries to hide circular scar around neck",
	"one blue eye, one brown",
	"poor personal hygiene",
	"constantly scratching",
	"missing top two front teeth",
	'tattoo on inner forearm in an unusual foreign language. Thinks it says "warrior spirit" but actually means "import duty paid"',
	"thinks they can sing. They're wrong.",
	"silver necklace with four different faiths' holy symbols",
	"dagger with a (costume jewel) jewelled pommel tucked into their belt",
	"yellow sash stretching from left shoulder to right waist",
	"missing right eye, wears a patch",
	"left little finger missing last joint, scarring evidently old",
	"greying at the temples. tries to hide with hat.",
	"dirty fingernails",
	"halitosis",
	"heavy drinker (red nose and cheeks)",
	"dried rations make them nauseous",

	// thanks to John Wilson
	"wide mouth",
	"beady eyes",
	"long face",
	"big hands",
	"long legs",
	"bristly hair",
	"limps (but no less agile for it)",
	"lisps",
	"always smiles",
	"greasy",
	"hirsute",

	// thanks to me
	"missing left eye, leaves scar uncovered",
	"has one gold tooth and no others",
	"missing both little fingers",
	'has a pet rat named "Mr Squeek" who lives in their pocket',
	"small hands",
	"dislikes loud noises",
	"scared of dogs",
	"afraid of heights",
	"claustrophobic",
	"tends to whisper",
	"arachnophobic",
	"distrusts men with beards",
	"village wrestling champion",
	"always wanted to be a magic user",
	"un-sure if their chosen deity exists",
	"considers themselves a master of strategy games",
	"inveterate gambler",
	"skilled at sleight of hand tricks",
	"scars run from corners of mouth to below ears",
	"tattoos on fingers of both hands spell words",
	"shameless womanizer",
	"has an invisible friend",
	"keen botanist",
	"ex bookkeeper",
	"ex beekeeper",
	"ex cowheard",
	"ex goatherd",
	"ex dung carter",
	"ex tanner",
	"ex woodcutter",
	"ex stone mason",
	"ex rat catcher, hates rats",
	"ex gamekeeper",
	"ex fisherman but now scared of the sea",
	"starving artist",
	"failed musician",
	"terrible artist",
	"skilled artist",
	"shoemaker's apprentice",
	"baker",
	"believes Frogs are Gods in mortal form",
	"believes Finch is greatest of all birds",
	"ex bricklayer",
	"ex brick maker",
	"ex grave digger",
	"turned to crime to surive as a child",
	"sheltered upbringing",
	"lute-maker",
	"snake oil salesman",
	"wants to be an actor",
	"kicked out of town guard for corruption",
	"fallen, level drained former Paladin. Protects this secret.",
	"hedge herbalist",
	"former mercenary",
	"former body guard",
	"beggar",
	"cut-purse",
	"scion of destitute nobel family",
	"transient"
];

function get_trait(character_class) {
	var choice = randomRange(0, traits.length-1);
	return(traits[choice]);
}
<commit_msg>More traits<commit_after>var traits = [

	// thanks to Stephen Dobson
	"frustrated poet",
	"tries to hide circular scar around neck",
	"one blue eye, one brown",
	"poor personal hygiene",
	"constantly scratching",
	"missing top two front teeth",
	'tattoo on inner forearm in an unusual foreign language. Thinks it says "warrior spirit" but actually means "import duty paid"',
	"thinks they can sing. They're wrong.",
	"silver necklace with four different faiths' holy symbols",
	"dagger with a (costume jewel) jewelled pommel tucked into their belt",
	"yellow sash stretching from left shoulder to right waist",
	"missing right eye, wears a patch",
	"left little finger missing last joint, scarring evidently old",
	"greying at the temples. tries to hide with hat.",
	"dirty fingernails",
	"halitosis",
	"heavy drinker (red nose and cheeks)",
	"dried rations make them nauseous",

	// thanks to John Wilson
	"wide mouth",
	"beady eyes",
	"long face",
	"big hands",
	"long legs",
	"bristly hair",
	"limps (but no less agile for it)",
	"lisps",
	"always smiles",
	"greasy",
	"hirsute",

	// thanks to me
	"missing left eye, leaves scar uncovered",
	"has one gold tooth and no others",
	"missing both little fingers",
	'has a pet rat named "Mr Squeek" who lives in their pocket',
	"small hands",
	"dislikes loud noises",
	"scared of dogs",
	"afraid of heights",
	"claustrophobic",
	"tends to whisper",
	"arachnophobic",
	"distrusts men with beards",
	"village wrestling champion",
	"always wanted to be a magic user",
	"un-sure if their chosen deity exists",
	"considers themselves a master of strategy games",
	"inveterate gambler",
	"skilled at sleight of hand tricks",
	"scars run from corners of mouth to below ears",
	"tattoos on fingers of both hands spell words",
	"shameless womanizer",
	"has an invisible friend",
	"keen botanist",
	"ex bookkeeper",
	"ex beekeeper",
	"ex cowheard",
	"ex goatherd",
	"ex dung carter",
	"ex tanner",
	"ex woodcutter",
	"ex stone mason",
	"ex rat catcher, hates rats",
	"ex gamekeeper",
	"ex fisherman but now scared of the sea",
	"starving artist",
	"failed musician",
	"terrible artist",
	"skilled artist",
	"shoemaker's apprentice",
	"baker",
	"believes Frogs are Gods in mortal form",
	"believes Finch is greatest of all birds",
	"ex bricklayer",
	"ex brick maker",
	"ex grave digger",
	"turned to crime to surive as a child",
	"sheltered upbringing",
	"lute-maker",
	"snake oil salesman",
	"wants to be an actor",
	"kicked out of town guard for corruption",
	"fallen, level drained former Paladin. Protects this secret.",
	"hedge herbalist",
	"former mercenary",
	"former body guard",
	"beggar",
	"cut-purse",
	"scion of destitute nobel family",
	"transient",
	"writes terrible plays. Wants you to act in them.",
	"worries the Sun may not rise",
	"believes the Moon laughs at them",
	"cannot distinguish left and right",
	"village sporting hero. Misses glory days.",
	"poor judge of character",
	"terrible choice in romantic partners",
	"prone to panic attacks",
	"passion for embroidery"
];

function get_trait(character_class) {
	var choice = randomRange(0, traits.length-1);
	return(traits[choice]);
}
<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';

var gulp = require('gulp');
var argv = require('yargs').argv;
var babelify = require('babelify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var del = require('del');
var reload = browserSync.reload;
var source = require('vinyl-source-stream');
var stringify = require('stringify');

// Autoload any gulp plugins
var plugins = require('gulp-load-plugins')();

var dist = './public/';
var src = './src/';

var config = {
    production: !! plugins.util.env.production,
    src: {
        scss: src + 'sass/',
        js: src + 'js/'
    },
    dist: {
        css: dist + 'assets/css/',
        js: dist + 'assets/js/'
    },
    sourcemaps: ! plugins.util.env.production,
    autoprefix:   true,
    babelOptions: {
          stage: 2,
          compact: false
    },
    autoprefixerOptions: {
        browsers: ['last 2 versions'],
        cascade: false
    }
};

// Sass // --------------------------------------------------

gulp.task('styles', function () {
    return gulp.src([config.src.scss + '*.scss', '!' + config.src.scss + 'guide.scss'])
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.init()))
        .pipe(plugins.cssGlobbing({
            extensions: ['.scss']
        }))
        .pipe(plugins.sass({
            outputStyle: 'expanded',
            errLogToConsole: true,
            sourceComments: false
        }))
        .pipe(plugins.plumber({ errorHandler: function (err) {console.log(err);}}))
        .pipe(plugins.autoprefixer(config.autoprefixerOptions))
        .pipe(plugins.if(config.production, plugins.minifyCss({processImport: false})))
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.write('./')))
        .pipe(gulp.dest(config.dist.css))
        .pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})))
        .pipe(plugins.notify({message: 'Styles Complete'}));
});

gulp.task('guide', function () {
    return gulp.src(config.src.scss + 'guide.scss')
        .pipe(plugins.cssGlobbing({
            extensions: ['.scss']
        }))
        .pipe(plugins.sass({
            errLogToConsole: true,
            sourceComments: false
        }))
        .pipe(plugins.autoprefixer(config.autoprefixerOptions))
        .pipe(gulp.dest(config.dist.css))
        .pipe(plugins.notify({message: 'Style Guide Complete'}));
});

// Scripts // --------------------------------------------------

gulp.task('lint', function () {
    gulp.src([config.src.js + '**/*.js', '!' +  config.src.js + 'vendor/*.js'])
        .pipe(plugins.jshint())
        .pipe(plugins.jshint.reporter('default'));
});

gulp.task('browserify', function () {
    return browserify({ entries: [config.src.js + 'app.js']})
        .transform(babelify, config.babelOptions)
        .transform(stringify(['.html']))
        .bundle()
        .on('error', function(e){
            console.log(e.message);
            this.emit('end');
        })
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.init()))
        .pipe(plugins.if(config.production, plugins.uglify()))
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.write('./')))
        .pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})))
        .pipe(gulp.dest(config.dist.js))
        .pipe(plugins.notify({message: 'Browserify Complete'}));
});

gulp.task('js', function() {
    return gulp.src(config.src.js + 'vendor/*.js')
        .pipe(plugins.concat('vendor.js'))
        .pipe(plugins.plumber({ errorHandler: function (err) { console.log(err); } }))
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.init()))
        .pipe(plugins.if(config.production, plugins.uglify()))
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.write('./')))
        .pipe(gulp.dest(config.dist.js))
        .pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})))
        .pipe(plugins.notify({message: 'JS Complete'}));
});

// HTML // --------------------------------------------------

gulp.task('html', function () {
    gulp.src(dist + '/**/*.html')
        .pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})));
});

// PHP // --------------------------------------------------

gulp.task('php', function () {
    gulp.src(['**/*.php', '!./vendor/**/*'])
       .pipe(plugins.if(argv.livereload, plugins.livereload()));
});

gulp.task('php.format', function () {
    return gulp.src(['**/*.php', '!./vendor/**/*'])
        .pipe(plugins.plumber({ errorHandler: function (err) { console.log(err); } }))
        // Validate files using PHP Code Sniffer
        .pipe(plugins.phpcs({
            bin: 'phpcs',
            standard: 'PSR2',
            warningSeverity: 0
        }))
        // Log all problems that were found
        .pipe(plugins.phpcs.reporter('log'));
});

var format = function (config) {
    return gulp.src(config)
        .pipe(plugins.plumber({ errorHandler: function (err) { console.log(err); } }))
        // Validate files using PHP Code Sniffer
        .pipe(plugins.phpcs({
            bin: 'phpcs',
            standard: 'PSR2',
            warningSeverity: 0
        }))
        // Log all problems that were found
        .pipe(plugins.phpcs.reporter('log'));
};

// Server // --------------------------------------------------

gulp.task('browser-sync', function () {
    browserSync({
        notify: false,
        ghostMode: {
            clicks: true,
            forms: true,
            scroll: true
        },
        server: {
            baseDir: dist
        }
    });
});

// Task // --------------------------------------------------

gulp.task('watch', function () {
    plugins.watch(config.src.js + '**/*', function () {
        gulp.start(['lint', 'js', 'browserify']);
    });

    plugins.watch(config.src.scss + '**/*.scss', function () {
        gulp.start('styles', 'guide');
    });

    plugins.watch(dist + '/**/*.html', function () {
        gulp.start('html');
    });

    plugins.watch(['**/*.php', '!./vendor/**/*'], function (event) {
        gulp.start(['php']);
        // PSR-2 Autoformat using https://github.com/squizlabs/PHP_CodeSniffer
        // format(event.path);
    });
});

gulp.task('dev', function () {
    gulp.start('watch');

    if (argv.livereload) {
        plugins.livereload.listen();
    } else {
        gulp.start('browser-sync');
    }
});

gulp.task('test', function () {
    gulp.start('lint');
});

gulp.task('default', function () {
    gulp.start('styles', 'browserify', 'js');
});
<commit_msg>Moved the plumber pipe above the sass call to prevent errors. It didn't work.<commit_after>/*jslint node: true */
'use strict';

var gulp = require('gulp');
var argv = require('yargs').argv;
var babelify = require('babelify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var del = require('del');
var reload = browserSync.reload;
var source = require('vinyl-source-stream');
var stringify = require('stringify');

// Autoload any gulp plugins
var plugins = require('gulp-load-plugins')();

var dist = './public/';
var src = './src/';

var config = {
    production: !! plugins.util.env.production,
    src: {
        scss: src + 'sass/',
        js: src + 'js/'
    },
    dist: {
        css: dist + 'assets/css/',
        js: dist + 'assets/js/'
    },
    sourcemaps: ! plugins.util.env.production,
    autoprefix:   true,
    babelOptions: {
          stage: 2,
          compact: false
    },
    autoprefixerOptions: {
        browsers: ['last 2 versions'],
        cascade: false
    }
};

// Sass // --------------------------------------------------

gulp.task('styles', function () {
    return gulp.src([config.src.scss + '*.scss', '!' + config.src.scss + 'guide.scss'])
        .pipe(plugins.plumber({ errorHandler: function (err) {console.log(err);}}))
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.init()))
        .pipe(plugins.cssGlobbing({
            extensions: ['.scss']
        }))
        .pipe(plugins.sass({
            outputStyle: 'expanded',
            errLogToConsole: true,
            sourceComments: false
        }))
        .pipe(plugins.autoprefixer(config.autoprefixerOptions))
        .pipe(plugins.if(config.production, plugins.minifyCss({processImport: false})))
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.write('./')))
        .pipe(gulp.dest(config.dist.css))
        .pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})))
        .pipe(plugins.notify({message: 'Styles Complete'}));
});

gulp.task('guide', function () {
    return gulp.src(config.src.scss + 'guide.scss')
        .pipe(plugins.cssGlobbing({
            extensions: ['.scss']
        }))
        .pipe(plugins.sass({
            errLogToConsole: true,
            sourceComments: false
        }))
        .pipe(plugins.autoprefixer(config.autoprefixerOptions))
        .pipe(gulp.dest(config.dist.css))
        .pipe(plugins.notify({message: 'Style Guide Complete'}));
});

// Scripts // --------------------------------------------------

gulp.task('lint', function () {
    gulp.src([config.src.js + '**/*.js', '!' +  config.src.js + 'vendor/*.js'])
        .pipe(plugins.jshint())
        .pipe(plugins.jshint.reporter('default'));
});

gulp.task('browserify', function () {
    return browserify({ entries: [config.src.js + 'app.js']})
        .transform(babelify, config.babelOptions)
        .transform(stringify(['.html']))
        .bundle()
        .on('error', function(e){
            console.log(e.message);
            this.emit('end');
        })
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.init()))
        .pipe(plugins.if(config.production, plugins.uglify()))
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.write('./')))
        .pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})))
        .pipe(gulp.dest(config.dist.js))
        .pipe(plugins.notify({message: 'Browserify Complete'}));
});

gulp.task('js', function() {
    return gulp.src(config.src.js + 'vendor/*.js')
        .pipe(plugins.concat('vendor.js'))
        .pipe(plugins.plumber({ errorHandler: function (err) { console.log(err); } }))
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.init()))
        .pipe(plugins.if(config.production, plugins.uglify()))
        .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.write('./')))
        .pipe(gulp.dest(config.dist.js))
        .pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})))
        .pipe(plugins.notify({message: 'JS Complete'}));
});

// HTML // --------------------------------------------------

gulp.task('html', function () {
    gulp.src(dist + '/**/*.html')
        .pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})));
});

// PHP // --------------------------------------------------

gulp.task('php', function () {
    gulp.src(['**/*.php', '!./vendor/**/*'])
       .pipe(plugins.if(argv.livereload, plugins.livereload()));
});

gulp.task('php.format', function () {
    return gulp.src(['**/*.php', '!./vendor/**/*'])
        .pipe(plugins.plumber({ errorHandler: function (err) { console.log(err); } }))
        // Validate files using PHP Code Sniffer
        .pipe(plugins.phpcs({
            bin: 'phpcs',
            standard: 'PSR2',
            warningSeverity: 0
        }))
        // Log all problems that were found
        .pipe(plugins.phpcs.reporter('log'));
});

var format = function (config) {
    return gulp.src(config)
        .pipe(plugins.plumber({ errorHandler: function (err) { console.log(err); } }))
        // Validate files using PHP Code Sniffer
        .pipe(plugins.phpcs({
            bin: 'phpcs',
            standard: 'PSR2',
            warningSeverity: 0
        }))
        // Log all problems that were found
        .pipe(plugins.phpcs.reporter('log'));
};

// Server // --------------------------------------------------

gulp.task('browser-sync', function () {
    browserSync({
        notify: false,
        ghostMode: {
            clicks: true,
            forms: true,
            scroll: true
        },
        server: {
            baseDir: dist
        }
    });
});

// Task // --------------------------------------------------

gulp.task('watch', function () {
    plugins.watch(config.src.js + '**/*', function () {
        gulp.start(['lint', 'js', 'browserify']);
    });

    plugins.watch(config.src.scss + '**/*.scss', function () {
        gulp.start('styles', 'guide');
    });

    plugins.watch(dist + '/**/*.html', function () {
        gulp.start('html');
    });

    plugins.watch(['**/*.php', '!./vendor/**/*'], function (event) {
        gulp.start(['php']);
        // PSR-2 Autoformat using https://github.com/squizlabs/PHP_CodeSniffer
        // format(event.path);
    });
});

gulp.task('dev', function () {
    gulp.start('watch');

    if (argv.livereload) {
        plugins.livereload.listen();
    } else {
        gulp.start('browser-sync');
    }
});

gulp.task('test', function () {
    gulp.start('lint');
});

gulp.task('default', function () {
    gulp.start('styles', 'browserify', 'js');
});
<|endoftext|>