<commit_before>((exports) => {
	typeof module !== `undefined` && module.exports ? module.exports = exports() :
	typeof define === `function` && define.amd ? define(() => exports()) :
	this[`Bite`] = exports();
})(() => {
	const helpers    = {};
	const concat     = `o+='`;
	const end_concat = `';`;

	const utilities = {
		s : `$=>$||$===0?$+'':''`, // String
		e : `$=>('&<>="\`\\''.split('').map(x=>$=$.replace(new RegExp(x,'g'),'&#'+x.charCodeAt(0)+';')),$)`, // Escape HTML
		r : `($)=>{$=+$||0;for(var x=0,a=[];x<$;++x)a.push(x);return a}`, // Repeat generator
		c : `()=>{$.$$=$$;$$=$}`, // Child scope
		p : `()=>{$=$$;$$=$.$$;$.$$=void 0}`, // Parent scope
	};

	[
		[``,       [`e`, `s`], params => `o+=e(s(${params}));`],
		[`!`,      [`s`],      params => `o+=s(${params});`],
		[`if`,     [],         params => `if(${params}){`, `}`],
		[`elseif`, [],         params => `}else if(${params}){`],
		[`else`,   [],         params => `}else{`],
		[`repeat`, [`r`],      params => `r(${params}).forEach((i)=>{`, `});`],
		[`each`,   [`c`, `p`], params => `c();${params}.forEach(($,i)=>{`, `});p();`],
		[`with`,   [`c`, `p`], params => `c();$=${params};`, `p();`],
	].forEach(definition => helper.apply(null, definition));

	function helper(helper, deps, begin, end) {
		const clean_helper = helper.replace(/([.*+?^=!:${}()|[\]\/\\])/g, `\\$&`);
		const prefix       = helper && helper !== `!` ? `#` : ``;
		const space        = helper && helper !== `!` ? `\\s+` : `\\s*`;

		helpers[helper] = {
			deps : deps,
			begin : {
				pattern : helper ? new RegExp(`{{${prefix}${clean_helper}(?:${space}([^{}]+))?\\s*}}`, `gi`) : /{{\s*([^#\/!][^{}]*)\s*}}/g,
				replace : (match, params) => end_concat + begin(params ? params.replace(/\\'/g, `'`) : null) + concat,
			},
			end : end ? {
				pattern : new RegExp(`{{/${clean_helper}}}`, `gi`),
				replace : () => end_concat + end + concat,
			} : null,
		};
	}

	function bite(body, preserve_whitespace) {
		body = (body || body === 0 ? body + `` : ``).replace(/'/g, `\\'`);
		body = preserve_whitespace ? body.replace(/\r?\n/g, `\\n`) : body.replace(/\s+/g, ` `);

		const deps_map = {};
		let deps       = ``;

		for(let helper in helpers) {
			const begin  = helpers[helper].begin;
			const end    = helpers[helper].end;
			const begins = (body.match(begin.pattern) || ``).length;
			const ends   = (end && body.match(end.pattern) || ``).length;

			if(!begins) {
				continue;
			}
			else if(end && begins > ends) {
				throw new Error(`Unclosed {{#${helper}}}`);
			}
			else if(end && begins < ends) {
				throw new Error(`Unexpected {{/${helper}}}`);
			}

			helpers[helper].deps.forEach((dep) => deps_map[dep] = true);
			body = body.replace(begin.pattern, begin.replace);
			end && (body = body.replace(end.pattern, end.replace));
		}

		for(let dep in utilities) {
			if(deps_map[dep]) {
				deps += utilities[dep] ? `,${dep}=${utilities[dep]}` : `,${dep}`;
			}
		}

		body = (`let $$,o=''${deps};${concat}${body}${end_concat}return o`).replace(/o\+='';/g, ``).replace(/;}/g, `}`);

		const template = new Function(`$`, body);
		template.toString = () => `$=>{${body}}`;

		return template;
	}

	return bite;
});
<commit_msg>Better error handling<commit_after>((exports) => {
	typeof module !== `undefined` && module.exports ? module.exports = exports() :
	typeof define === `function` && define.amd ? define(() => exports()) :
	this[`Bite`] = exports();
})(() => {
	const helpers    = {};
	const concat     = `o+='`;
	const end_concat = `';`;

	const utilities = {
		s : `$=>$||$===0?$+'':''`, // String
		e : `$=>('&<>="\`\\''.split('').map(x=>$=$.replace(new RegExp(x,'g'),'&#'+x.charCodeAt(0)+';')),$)`, // Escape HTML
		r : `($)=>{$=+$||0;for(var x=0,a=[];x<$;++x)a.push(x);return a}`, // Repeat generator
		c : `()=>{$.$$=$$;$$=$}`, // Child scope
		p : `()=>{$=$$;$$=$.$$;$.$$=void 0}`, // Parent scope
	};

	[
		[``,       [`e`, `s`], params => `o+=e(s(${params}));`],
		[`!`,      [`s`],      params => `o+=s(${params});`],
		[`if`,     [],         params => `if(${params}){`, `}`],
		[`elseif`, [],         params => `}else if(${params}){`],
		[`else`,   [],         params => `}else{`],
		[`repeat`, [`r`],      params => `r(${params}).forEach((i)=>{`, `});`],
		[`each`,   [`c`, `p`], params => `c();${params}.forEach(($,i)=>{`, `});p();`],
		[`with`,   [`c`, `p`], params => `c();$=${params};`, `p();`],
	].forEach(definition => helper.apply(null, definition));

	function helper(helper, deps, begin, end) {
		const clean_helper = helper.replace(/([.*+?^=!:${}()|[\]\/\\])/g, `\\$&`);
		const prefix       = helper && helper !== `!` ? `#` : ``;
		const space        = helper && helper !== `!` ? `\\s+` : `\\s*`;

		helpers[helper] = {
			deps : deps,
			begin : {
				pattern : helper ? new RegExp(`{{${prefix}${clean_helper}(?:${space}([^{}]+))?\\s*}}`, `gi`) : /{{\s*([^#\/!][^{}]*)\s*}}/g,
				replace : (match, params) => end_concat + begin(params ? params.replace(/\\'/g, `'`) : null) + concat,
			},
			end : end ? {
				pattern : new RegExp(`{{/${clean_helper}}}`, `gi`),
				replace : () => end_concat + end + concat,
			} : null,
		};
	}

	function bite(body, preserve_whitespace) {
		body = (body || body === 0 ? body + `` : ``).replace(/'/g, `\\'`);
		body = preserve_whitespace ? body.replace(/\r?\n/g, `\\n`) : body.replace(/\s+/g, ` `);

		const deps_map = {};
		let deps       = ``;

		for(let helper in helpers) {
			const begin  = helpers[helper].begin;
			const end    = helpers[helper].end;
			const begins = (body.match(begin.pattern) || ``).length;
			const ends   = (end && body.match(end.pattern) || ``).length;

			if(end) {
				if(begins > ends) {
					throw new Error(`Unclosed {{#${helper}}}`);
				}
				else if(begins < ends) {
					throw new Error(`Unexpected {{/${helper}}}`);
				}
			}

			if(!begins) {
				continue;
			}

			helpers[helper].deps.forEach((dep) => deps_map[dep] = true);
			body = body.replace(begin.pattern, begin.replace);
			end && (body = body.replace(end.pattern, end.replace));
		}

		for(let dep in utilities) {
			if(deps_map[dep]) {
				deps += utilities[dep] ? `,${dep}=${utilities[dep]}` : `,${dep}`;
			}
		}

		body = (`let $$,o=''${deps};${concat}${body}${end_concat}return o`).replace(/o\+='';/g, ``).replace(/;}/g, `}`);

		const template = new Function(`$`, body);
		template.toString = () => `$=>{${body}}`;

		return template;
	}

	return bite;
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var S = require('string');
var Promise = require('bluebird');
var chalk = require('chalk');
var apps = require('../../db/apps');
var parse = require('../../parse');
var log = require('../../logger');
var maxUIResults = require('config').results.maxUI;

module.exports = {
    init: init,
    find: find
}

function init(env) {
    return apps
        .init("ui")
        .then(function (ret) {
            env.apps = ret
            return env
        })
}

function find(env, query, options) {
    // If query is not specified, return everything in scope
    if (!query) {
        return Promise.resolve(options.scope);
    }
    var uiQuery = parse(query);
    // array to collect results
    var results = [];
    var count = 0;
    var found = 0;
    // Iterate over ids in the scope
    for (var i = 0; i < options.scope.length; i++) {
        var id = options.scope[i];
        var app = env.apps.get(id, {dom: true})

        if (app.dom === undefined || app.dom === null) {
            return;
        }

        var matcher = _lookup_matcher(uiQuery)

        // apply the matcher to 'app' to see if it maches
        var matched = matcher(uiQuery, app)

        // if so
        if (matched) {
            // add to the results array
            results.push(id)
            found++;
        }

        log.info('%d: %s %s', count, chalk.grey(id),
            matched ? chalk.green('yes') : chalk.red('no'))
        count++;

        if (found == maxUIResults) {
            // the maximum number of UI results have been reached.
            break;
        }
    }

    return new Promise(function (resolve, reject) {
        resolve(results)
    })
}

//
// Matchers
//

// analyze the pattern of the given query and lookup a matcher to process the query
function _lookup_matcher(q) {
    if (q.children === undefined && q.count === 1) {
        return _find_by_a_single_tag
    } else if (q.children === undefined && q.count > 1) {
        return _find_by_siblings
    } else if (q.children.length === 1) {
        return _find_by_a_single_tag_with_n_children_of_one_tag
    } else if (q.children.length > 1) {
        return _find_by_a_single_tag_with_n_children_of_multiple_tags
    } else {
        log.error('Unrecognized UI query.');
        return function () {
            return false
        }
    }

}

function _find_by_a_single_tag(q, app) {
    var $ = app.dom
    var selector = _get_element_name(q)

    // find a custom tag like: <com.whatsapp.*/>
    if (selector.indexOf('*') != -1) {
        var results = _.filter($('*'), function (val) {
            if ('attributes' in q && q.attributes.length > 0) {
                if (S(val.name).startsWith(q.name.split('*')[0])) {
                    var newSelector = _escapeSpecialCharacters(val.name) +
                        _getAttributeSelectors(q.attributes);
                    return $(newSelector).length >= q.count;
                }
            }
            else {
                return S(val.name).startsWith(q.name.split('*')[0]);
            }
        });
        return results.length >= q.count
    }
    if ('attributes' in q) {
        selector += _getAttributeSelectors(q.attributes)
    }
    if ('min' in q) {
        $(selector).length > q.min;
    } else if ('max' in q) {
        $(selector).length < q.count;
    } else if ('exactly' in q) {
        $(selector).length == q.exactly;
    }
    return $(selector).length >= q.count
}

function _find_by_a_single_tag_with_n_children_of_one_tag(q, app) {
    var $ = app.dom || app
    var selector = _get_element_name(q)
    var childName = _get_child_name(q.children[0])
    var childCount = q.children[0].count
    var result
    if (typeof $ === 'function') {
        // Find each selector that is nth in relation to its sibling selector with the same element name.
        result = (childName === '*') ? $(selector + ' > ' + childName) :
            $(selector + ' > ' + childName + ':nth-of-type(' + childCount + ')')
    }
    else {
        result = $.children(childName);
    }
    if ('children' in q.children[0] && result.length >= childCount) {
        return _find_by_a_single_tag_with_n_children_of_one_tag(q.children[0], result)
    }
    return result.length >= childCount
}

function _find_by_a_single_tag_with_n_children_of_multiple_tags(q, app) {
    // Find the children of the single tag and count their children
    // as siblings of each other.
    // Example: $('LinearLayout').children('ImageView ~ RatingBar')
    var $ = app.dom;
    var selector = _get_element_name(q);
    var childrenNames = new Array();
    _.forEach(q.children, function (child) {
        var fullChildName = _get_child_name(child) + " ";
        childrenNames.push(_.repeat(fullChildName + " ~ ", child.count));
    });
    // Join the array and remove the last four characters for " ~ "
    var querySiblings = childrenNames.join('').slice(0, -4);
    return $(selector).children(querySiblings).length >= 1
}

function _find_by_siblings(q, app) {
    var $ = app.dom
    var selector = _get_element_name(q)
    var result = $(selector + ':nth-of-type(' + q.count + ')')
    return result.length > 0
}

function _get_element_name(element) {
    var selector = element.name
    if (selector == '_') {
        selector = '*'
    }
    selector = _escapeSpecialCharacters(selector)
    if ('attributes' in element) {
        var actualAttributes = _filterExtraAttributes(element.attributes)
        selector += _getAttributeSelectors(actualAttributes)
    }
    return selector
}

function _get_child_name(child) {
    var childName = child.name
    if (childName == '_') {
        childName = '*'
    }
    if ('attributes' in child) {
        var actualAttributes = _filterExtraAttributes(child.attributes)
        childName += _getAttributeSelectors(actualAttributes)
    }
    if (childName != '*') {
        childName = _escapeSpecialCharacters(childName)
    }
    return childName;

}

function _getAttributeSelectors(attributes) {
    var attributesSelector = ''
    _.forEach(attributes, function (attrib) {
        var idx = attrib['value'].indexOf('*');
        // Attribute value equals to a value
        if (idx == -1) {
            var attribText = '[' + _escapeSpecialCharacters(attrib.name) +
                '="' + _escapeSpecialCharacters(attrib.value) + '"]';
            attributesSelector += attribText
        }
        // Attribute value starts with a value
        else if (idx == attrib['value'].length - 1) {
            var attribText = '[' + _escapeSpecialCharacters(attrib.name)
                + '^="' + _escapeSpecialCharacters(attrib.value.split('*')[0]) + '"]';
            attributesSelector += attribText
        }
        // Attribute value ends with a value
        else if (idx == 0) {
            var attribText = '[' + _escapeSpecialCharacters(attrib.name) +
                '$="' + _escapeSpecialCharacters(attrib.value.split('*')[1]) + '"]';
            attributesSelector += attribText
        }
    })
    return attributesSelector;
}

function _filterExtraAttributes(attributes) {
    return _.filter(attributes, function (attrib) {
        return attrib.name != '__name'
    })
}

/**
 * Escape names that use any of JQuery meta-characters as a literal part of a name.
 * @param str a String that may use any of the meta-characters
 * @returns {String} The escaped string with two backslashes replacing the
 * JQuery's special meta-characters
 * @private
 */
function _escapeSpecialCharacters(str) {
    return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
}
<commit_msg>fix escaping special characters<commit_after>var _ = require('lodash');
var S = require('string');
var Promise = require('bluebird');
var chalk = require('chalk');
var apps = require('../../db/apps');
var parse = require('../../parse');
var log = require('../../logger');
var domMatcher = require('../dom/index.js');
var maxUIResults = require('config').results.maxUI;

module.exports = {
    init: init,
    find: find
}

function init(env) {
    return apps
        .init("ui")
        .then(function (ret) {
            env.apps = ret
            return env
        })
}

function find(env, query, options) {
    // If query is not specified, return everything in scope
    if (!query) {
        return Promise.resolve(options.scope);
    }
    var uiQuery = parse(query);
    // array to collect results
    var results = [];
    var count = 0;
    var found = 0;
    // Iterate over ids in the scope
    for (var i = 0; i < options.scope.length; i++) {
        var id = options.scope[i];
        var app = env.apps.get(id, {dom: true})

        if (app.dom === undefined || app.dom === null) {
            return;
        }
        var matched;
        if (options.mode === 'strict') {
            var matcher = _lookup_matcher(uiQuery);
            matched = matcher(uiQuery, app);
        }
        else {
            matched = domMatcher(uiQuery, app, app.dom);
        }
        if (matched) {
            results.push(id)
            found++;
        }

        log.info('%d: %s %s', count, chalk.grey(id),
            matched ? chalk.green('yes') : chalk.red('no'))
        count++;

        if (found == maxUIResults) {
            // the maximum number of UI results have been reached.
            break;
        }
    }

    return new Promise(function (resolve, reject) {
        resolve(results)
    })
}

//
// Matchers
//

// analyze the pattern of the given query and lookup a matcher to process the query
function _lookup_matcher(q) {
    if (q.children === undefined && q.count === 1) {
        return _find_by_a_single_tag
    } else if (q.children === undefined && q.count > 1) {
        return _find_by_siblings
    } else if (q.children.length === 1) {
        return _find_by_a_single_tag_with_n_children_of_one_tag
    } else if (q.children.length > 1) {
        return _find_by_a_single_tag_with_n_children_of_multiple_tags
    } else {
        log.error('Unrecognized UI query.');
        return function () {
            return false
        }
    }

}

function _find_by_a_single_tag(q, app) {
    var $ = app.dom
    var selector = _get_element_name(q)

    // find a custom tag like: <com.whatsapp.*/>
    if (selector.indexOf('*') != -1) {
        var results = _.filter($('*'), function (val) {
            if ('attributes' in q && q.attributes.length > 0) {
                if (S(val.name).startsWith(q.name.split('*')[0])) {
                    var newSelector = _escapeSpecialCharacters(val.name) +
                        _escapeSpecialCharacters(_getAttributeSelectors(q.attributes));
                    return $(newSelector).length >= q.count;
                }
            }
            else {
                return S(val.name).startsWith(q.name.split('*')[0]);
            }
        });
        return results.length >= q.count
    }
    if ('min' in q) {
        $(selector).length > q.min;
    } else if ('max' in q) {
        $(selector).length < q.count;
    } else if ('exactly' in q) {
        $(selector).length == q.exactly;
    }
    return $(selector).length >= q.count
}

function _find_by_a_single_tag_with_n_children_of_one_tag(q, app) {
    var $ = app.dom || app
    var selector = _get_element_name(q)
    var childName = _get_child_name(q.children[0])
    var childCount = q.children[0].count
    var result
    if (typeof $ === 'function') {
        // Find each selector that is nth in relation to its sibling selector with the same element name.
        result = (childName === '*') ? $(selector + ' > ' + childName) :
            $(selector + ' > ' + childName + ':nth-of-type(' + childCount + ')')
    }
    else {
        result = $.children(childName);
    }
    if ('children' in q.children[0] && result.length >= childCount) {
        return _find_by_a_single_tag_with_n_children_of_one_tag(q.children[0], result)
    }
    return result.length >= childCount
}

function _find_by_a_single_tag_with_n_children_of_multiple_tags(q, app) {
    // Find the children of the single tag and count their children
    // as siblings of each other.
    // Example: $('LinearLayout').children('ImageView ~ RatingBar')
    var $ = app.dom;
    var selector = _get_element_name(q);
    var childrenNames = new Array();
    _.forEach(q.children, function (child) {
        var fullChildName = _get_child_name(child) + " ";
        childrenNames.push(_.repeat(fullChildName + " ~ ", child.count));
    });
    // Join the array and remove the last four characters for " ~ "
    var querySiblings = childrenNames.join('').slice(0, -4);
    return $(selector).children(querySiblings).length >= 1
}

function _find_by_siblings(q, app) {
    var $ = app.dom
    var selector = _get_element_name(q)
    var result = $(selector + ':nth-of-type(' + q.count + ')')
    return result.length > 0
}

function _get_element_name(element) {
    var selector = element.name
    if (selector == '_') {
        selector = '*'
    }
    if ('attributes' in element) {
        var actualAttributes = _filterExtraAttributes(element.attributes)
        selector += _getAttributeSelectors(actualAttributes)
    }
    selector = _escapeSpecialCharacters(selector)
    return selector
}

function _get_child_name(child) {
    var childName = child.name
    if (childName == '_') {
        childName = '*'
    }
    if ('attributes' in child) {
        var actualAttributes = _filterExtraAttributes(child.attributes)
        childName += _getAttributeSelectors(actualAttributes)
    }
    if (childName != '*') {
        childName = _escapeSpecialCharacters(childName)
    }
    return childName;
}

function _getAttributeSelectors(attributes) {
    var attributesSelector = ''
    _.forEach(attributes, function (attrib) {
        var idx = attrib['value'].indexOf('*');
        // Attribute value equals to a value
        if (idx == -1) {
            var attribText = '[' + (attrib.name) +
                '="' + (attrib.value) + '"]';
            attributesSelector += attribText
        }
        // Attribute value starts with a value
        else if (idx == attrib['value'].length - 1) {
            var attribText = '[' + (attrib.name)
                + '^="' + (attrib.value.split('*')[0]) + '"]';
            attributesSelector += attribText
        }
        // Attribute value ends with a value
        else if (idx == 0) {
            var attribText = '[' + (attrib.name) +
                '$="' + (attrib.value.split('*')[1]) + '"]';
            attributesSelector += attribText
        }
    })
    return attributesSelector;
}

function _filterExtraAttributes(attributes) {
    return _.filter(attributes, function (attrib) {
        return attrib.name != '__name'
    })
}

/**
 * Escape names that use any of JQuery meta-characters as a literal part of a name.
 * @param str a String that may use any of the meta-characters
 * @returns {String} The escaped string with two backslashes replacing the
 * JQuery's special meta-characters
 * @private
 */
function _escapeSpecialCharacters(str) {
    var r = str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\$1');
    return r.replace(/(:|\.)/g, "\\$1");
}
<|endoftext|>


<commit_before>//HANGMAN

var words = ['around', 'astonishing', 'bikini', 'bookworm', 'cat', 'elephant', 'fitness',
			'galaxy', 'jigsaw', 'kiwi', 'microwave', 'music', 'nightclub',
			'pixel', 'pneumonia', 'robot', 'rainbow', 'swing', 'scientist', 'subway',
			'tequila', 'tree', 'unknown',
			'vodka', 'waltz', 'whiskey', 'youthful', 'zizag', 'zombie']

//Choose random words
function chooseWord(){
	var num = Math.floor(Math.random() * words.length);
	return words[num];
}

//Blanks for answer
function blanksFromAnswer( answerWord ) {
	var result = "";	//This is the variable we want to use
	for ( i in answerWord ) {
		result = "_" + result;
	}
	return result;
}

//Replacing letter, n = pos to replace, c = char to insert
function alterAt (n, c, originalString) {
	var last = originalString.length;
	return originalString.substr(0, n) + c + originalString.substr(n+1, last);
}

//shown = what is currently displayed to user, letter = letter guessed
function guessLetter( letter, shown, answer) {
	var checkIndex = 0;

	checkIndex = answer.indexOf(letter);
	while( checkIndex >= 0) {
		shown = alterAt(checkIndex, letter, shown);
		checkIndex = answer.indexOf(letter, checkIndex + 1);
	}
	return shown;
}<commit_msg>hangman edit<commit_after>//HANGMAN

var words = ['aida', 'adversary', 'algorithmn', 'anatomy','around', 'artificial', 'astonishing',
	'beagle', 'bikini', 'bookworm', 'brick',
    'canal', 'cardio', 'cast', 'cat', 'controller', 'communication', 'computation', 'customs',
    'doll', 'damange', 'dancing',
    'eager', 'easygoing', 'elephant', 'encapsulation', 'essential',
    'equine', 'exchange', 'exist', 'express',
    'faculty', 'film', 'fireplace', 'fitness', 'focus',
    'galaxy', 'gate', 'generally', 'genetics', 'genuine', 'graphics',
    'handwriting', 'harvest', 'horses',
    'ideal', 'illustrate', 'imagination', 'impact', 'import', 'induction', 'infrastructure',
    'interface', 'inheritance',
    'java', 'jelly', 'jewelry', 'jigsaw', 'journey',
    'kickoff', 'kiwi', 'knowledge',
    'language', 'latina', 'latino', 'laughter', 'logic',
    'machine', 'merengue','microwave', 'module', 'music',
    'nearby', 'networks', 'nightclub',
    'object', 'offer', 'optimization', 'oriented',
    'package', 'painter', 'paper', 'parallel', 'pixel', 'pneumonia', 'programming', 'prototype',
    'python',
    'quaity', 'question', 'quotation',
    'ratio', 'rational', 'raw', 'robot', 'rainbow',
    'sarcastic', 'scale', 'search', 'swing', 'scientist', 'schedule', 'scope', 'scoreboard',
    'silicon', 'software', 'subway',
    'target', 'teammate', 'technical', 'tequila', 'thrift', 'tree',
    'undergraduate', 'unique', 'unknown', 'user',
    'vacation', 'valley', 'valuable', 'variety', 'vegetable', 'verdict', 'version',
    'veterinarian', 'view', 'vodka',
    'waltz', 'wander', 'whiskey',
    'youthful',
    'zizag', 'zombie']

//Choose random words
function chooseWord(){
	var num = Math.floor(Math.random() * words.length);
	return words[num];
}

//Blanks for answer
function blanksFromAnswer( answerWord ) {
	var result = "";	//This is the variable we want to use
	for ( i in answerWord ) {
		result = "_" + result;
	}
	return result;
}

//Replacing letter, n = pos to replace, c = char to insert
function alterAt (n, c, originalString) {
	var last = originalString.length;
	return originalString.substr(0, n) + c + originalString.substr(n+1, last);
}

//shown = what is currently displayed to user, letter = letter guessed
function guessLetter( letter, shown, answer) {
	var checkIndex = 0;

	checkIndex = answer.indexOf(letter);
	while( checkIndex >= 0) {
		shown = alterAt(checkIndex, letter, shown);
		checkIndex = answer.indexOf(letter, checkIndex + 1);
	}
	return shown;
}<|endoftext|>


<commit_before>/* eslint-env mocha */
const assert = require('assert')
const TreeRegexp = require('../src/tree_regexp')

describe('TreeRegexp', () => {
  it('exposes group source', () => {
    const tr = new TreeRegexp(/(a(?:b)?)(c)/)
    assert.deepEqual(
      tr.groupBuilder.children.map(gb => gb.source)[('a(?:b)?', 'c')]
    )
  })

  it('builds tree', () => {
    const tr = new TreeRegexp(/(a(?:b)?)(c)/)
    const group = tr.match('ac')
    assert.equal(group.value, 'ac')
    assert.equal(group.children[0].value, 'a')
    assert.deepEqual(group.children[0].children, [])
    assert.equal(group.children[1].value, 'c')
  })

  it('ignores non-capturing groups', () => {
    const tr = new TreeRegexp(/(a(?:b)?)(c)/)
    const group = tr.match('ac')
    assert.equal(group.value, 'ac')
    assert.equal(group.children[0].value, 'a')
    assert.deepEqual(group.children[0].children, [])
    assert.equal(group.children[1].value, 'c')
  })

  it('matches optional group', () => {
    const tr = new TreeRegexp(/^Something( with an optional argument)?/)
    const group = tr.match('Something')
    assert.equal(group.children[0].value, null)
  })

  it('matches nested groups', () => {
    const tr = new TreeRegexp(
      /^A (\d+) thick line from ((\d+),\s*(\d+),\s*(\d+)) to ((\d+),\s*(\d+),\s*(\d+))/
    )
    const group = tr.match('A 5 thick line from 10,20,30 to 40,50,60')

    assert.equal(group.children[0].value, '5')
    assert.equal(group.children[1].value, '10,20,30')
    assert.equal(group.children[1].children[0].value, '10')
    assert.equal(group.children[1].children[1].value, '20')
    assert.equal(group.children[1].children[2].value, '30')
    assert.equal(group.children[2].value, '40,50,60')
    assert.equal(group.children[2].children[0].value, '40')
    assert.equal(group.children[2].children[1].value, '50')
    assert.equal(group.children[2].children[2].value, '60')
  })

  it('detects multiple non capturing groups', () => {
    const tr = new TreeRegexp(/(?:a)(:b)(\?c)(d)/)
    const group = tr.match('a:b?cd')
    assert.equal(group.children.length, 3)
  })

  it('captures non capturing groups with capturing groups inside', () => {
    const tr = new TreeRegexp('the stdout(?: from "(.*?)")?')
    const group = tr.match('the stdout')
    assert.equal(group.value, 'the stdout')
    assert.equal(group.children[0].value, null)
    assert.equal(group.children.length, 1)
  })
})
<commit_msg>cucumber-expressions: Fix syntax error in test<commit_after>/* eslint-env mocha */
const assert = require('assert')
const TreeRegexp = require('../src/tree_regexp')

describe('TreeRegexp', () => {
  it('exposes group source', () => {
    const tr = new TreeRegexp(/(a(?:b)?)(c)/)
    assert.deepEqual(tr.groupBuilder.children.map(gb => gb.source), [
      'a(?:b)?',
      'c',
    ])
  })

  it('builds tree', () => {
    const tr = new TreeRegexp(/(a(?:b)?)(c)/)
    const group = tr.match('ac')
    assert.equal(group.value, 'ac')
    assert.equal(group.children[0].value, 'a')
    assert.deepEqual(group.children[0].children, [])
    assert.equal(group.children[1].value, 'c')
  })

  it('ignores non-capturing groups', () => {
    const tr = new TreeRegexp(/(a(?:b)?)(c)/)
    const group = tr.match('ac')
    assert.equal(group.value, 'ac')
    assert.equal(group.children[0].value, 'a')
    assert.deepEqual(group.children[0].children, [])
    assert.equal(group.children[1].value, 'c')
  })

  it('matches optional group', () => {
    const tr = new TreeRegexp(/^Something( with an optional argument)?/)
    const group = tr.match('Something')
    assert.equal(group.children[0].value, null)
  })

  it('matches nested groups', () => {
    const tr = new TreeRegexp(
      /^A (\d+) thick line from ((\d+),\s*(\d+),\s*(\d+)) to ((\d+),\s*(\d+),\s*(\d+))/
    )
    const group = tr.match('A 5 thick line from 10,20,30 to 40,50,60')

    assert.equal(group.children[0].value, '5')
    assert.equal(group.children[1].value, '10,20,30')
    assert.equal(group.children[1].children[0].value, '10')
    assert.equal(group.children[1].children[1].value, '20')
    assert.equal(group.children[1].children[2].value, '30')
    assert.equal(group.children[2].value, '40,50,60')
    assert.equal(group.children[2].children[0].value, '40')
    assert.equal(group.children[2].children[1].value, '50')
    assert.equal(group.children[2].children[2].value, '60')
  })

  it('detects multiple non capturing groups', () => {
    const tr = new TreeRegexp(/(?:a)(:b)(\?c)(d)/)
    const group = tr.match('a:b?cd')
    assert.equal(group.children.length, 3)
  })

  it('captures non capturing groups with capturing groups inside', () => {
    const tr = new TreeRegexp('the stdout(?: from "(.*?)")?')
    const group = tr.match('the stdout')
    assert.equal(group.value, 'the stdout')
    assert.equal(group.children[0].value, null)
    assert.equal(group.children.length, 1)
  })
})
<|endoftext|>


<commit_before>define([
    'angular',
],
       function (angular) {
           'use strict';

           var module = angular.module('grafana.controllers');

           module.controller('RaspimonPandasQueryCtrl', function($scope, $http) {
               $scope.init = function() {
                   if (!$scope.target) { return; }
                   var target = $scope.target;
                   target.mul = target.mul || 1.0;
                   target.add = target.add || 0.0;
                   $scope.datasource.getTopicsListFiltered().then(function(topics) {
                       $scope.topics = topics;
                   });
                   $scope.datasource.getAggregatorsList().then(function(aggregators) {
                       $scope.aggregators = aggregators;
                   });
                   $scope.consolidateby = target.consolidateby || "last";
                   $scope.function_names = [
                       "abs", "add", "clip", "clip_lower", "clip_upper",
                       "cumprod", "cumsum", "diff", "div", "dropna", "fillna",
                       "floordiv", "interpolate", "mod", "mul", "nlargest",
                       "nonzero", "nsmallest", "pow", "rank", "resample",
                       "rolling_count", "rolling_kurtosis", "rolling_max",
                       "rolling_mean", "rolling_median", "rolling_min",
                       "rolling_skew", "rolling_std", "rolling_sum",
                       "rolling_var", "rolling_window", "round", "shift", "sub",
                       "replace",
                   ];
                   target.functions = target.functions || [];

                   $scope.addFunction = function() {
                       target.functions.push( { "name" : undefined,
                                                "arguments" : undefined } )
                   };
                   $scope.removeFunction = function(i) {
                       target.functions.splice(i, 1);
                   };
                   $scope.moveFunction = function(i,j) {
                       if (j >= 0 && j <= target.functions.length) {
                           var tmp = target.functions[i];
                           target.functions[i] = target.functions[j];
                           target.functions[j] = tmp;
                       }
                   };
               };
               $scope.targetBlur = function() {
                   // TODO: perform target validation here
               };
           });
       });
<commit_msg>updated raspimon panads<commit_after>define([
    'angular',
],
       function (angular) {
           'use strict';

           var module = angular.module('grafana.controllers');

           module.controller('RaspimonPandasQueryCtrl', function($scope, $http) {
               $scope.init = function() {
                   if (!$scope.target) { return; }
                   var target = $scope.target;
                   target.mul = target.mul || 1.0;
                   target.add = target.add || 0.0;
                   $scope.datasource.getTopicsListFiltered().then(function(topics) {
                       $scope.topics = topics;
                   });
                   $scope.datasource.getAggregatorsList().then(function(aggregators) {
                       $scope.aggregators = aggregators;
                   });
                   $scope.consolidateby = target.consolidateby || "last";
                   $scope.function_names = [
                       "abs", "add", "clip", "clip_lower", "clip_upper",
                       "cumprod", "cumsum", "diff", "div", "dropna", "fillna",
                       "floordiv", "interpolate", "mod", "mul", "nlargest",
                       "nonzero", "nsmallest", "pow", "rank", "replace", "resample",
                       "rolling_count", "rolling_kurtosis", "rolling_max",
                       "rolling_mean", "rolling_median", "rolling_min",
                       "rolling_skew", "rolling_std", "rolling_sum",
                       "rolling_var", "rolling_window", "round", "shift", "sub",
                   ];
                   target.functions = target.functions || [];

                   $scope.addFunction = function() {
                       target.functions.push( { "name" : undefined,
                                                "arguments" : undefined } )
                   };
                   $scope.removeFunction = function(i) {
                       target.functions.splice(i, 1);
                   };
                   $scope.moveFunction = function(i,j) {
                       if (j >= 0 && j <= target.functions.length) {
                           var tmp = target.functions[i];
                           target.functions[i] = target.functions[j];
                           target.functions[j] = tmp;
                       }
                   };
               };
               $scope.targetBlur = function() {
                   // TODO: perform target validation here
               };
           });
       });
<|endoftext|>


<commit_before>Ti.include('/includes/lib/json.i18n.js');

var win = Ti.UI.currentWindow,
	Utils = require('/includes/utils'),
	Keychain = require('clearlyinnovative.keychain');

function getTextFieldRow(text, hint, isPassword) {
	var row = Ti.UI.createTableViewRow({
		selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.NONE,
		layout: 'horizontal'
	}),

	rowText = Ti.UI.createLabel({
		text: text,
		left: 10,
		width: Ti.UI.SIZE,
		top: 5,
		bottom: 5,
		height: 30,
		font: {
			fontWeight: 'bold',
			fontSize: 17
		}
	}),

	textfield = Ti.UI.createTextField({
		color: '#336699',
		right: 10,
		left: 5,
		top: 5,
		bottom: 5,
		height: 30,
		width: Ti.UI.FILL,
		textAlign: Ti.UI.TEXT_ALIGNMENT_RIGHT,
		autocorrect: false,
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_NONE,
		returnKeyType: Ti.UI.RETURNKEY_NEXT,
		hintText: hint,
		passwordMask: isPassword,
		autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
		clearButtonMode: Ti.UI.INPUT_BUTTONMODE_ONFOCUS
	});

	row.add(rowText);

	rowText.addEventListener('postlayout', function() {
		if(rowText.rect.width >= 140) {
			rowText.width = 140;
		}
	});

	row.add(textfield);
	return row;
}

var b_credits = Ti.UI.createButton({
	title: I('credits.title')
});

b_credits.addEventListener('click', function() {
	var credits_win = Ti.UI.createWindow({
		url: 'credits.js',
		title: I('credits.title'),
		backgroundRepeat: true,
		barColor: Utils.getNavColor(),
		backgroundImage: Utils.getBGImage()
	});

	if(Utils.isiPad()) {
		win.masterGroup.open(credits_win);
	} else {
		win.navGroup.open(credits_win);
	}
});

if(Utils.isiPhone()) {
	var b_close = Ti.UI.createButton({
		title: I('buttons.close'),
		style: Titanium.UI.iPhone.SystemButtonStyle.DONE
	});

	b_close.addEventListener('click', function() {
		win.container.close();
	});

	win.setRightNavButton(b_credits);
	win.setLeftNavButton(b_close);
} else {
	win.setRightNavButton(b_credits);
}

var lbl_header = Ti.UI.createLabel({
	text: I('settings.header'),
	color: '#F8F8F8',
	font: {
		fontSize: 17,
		fontWeight: 'bold'
	},
	shadowColor: 'black',
	shadowOffset: {
		x: 0,
		y: 1
	},
	top: 15,
	left: 15,
	height: Ti.UI.SIZE
}),

tableView = Ti.UI.createTableView({
	data: [getTextFieldRow(I('settings.username'), 'Notch', false), getTextFieldRow(I('settings.password'), '●●●●●●●●●●●', true)],
	style: Ti.UI.iPhone.TableViewStyle.GROUPED,
	backgroundColor: 'transparent',
	rowBackgroundColor: 'white',
	scrollable: false,
	rowHeight: 45,
	height: 120
}),

lbl_footer = Ti.UI.createLabel({
	text: I('settings.footer.migratedAccount') + '\n\n' + I('settings.footer.privacy'),
	color: '#F8F8F8',
	font: {
		fontSize: (Utils.isiPad()) ? 18 : 15
	},
	shadowColor: 'black',
	shadowOffset: {
		x: 0,
		y: 1
	},
	top: 15,
	left: 15,
	right: 15,
	height: Ti.UI.SIZE
});

win.add(lbl_header);
win.add(tableView);
win.add(lbl_footer);

win.addEventListener('focus', function() {
	Keychain.getForKey({
		key: 'username',
		serviceName: Ti.App.getId()
	}, function(data) {
		tableView.getData()[0].getRows()[0].getChildren()[1].setValue(data.value);
	});

	Keychain.getForKey({
		key: 'password',
		serviceName: Ti.App.getId()
	}, function(data) {
		tableView.getData()[0].getRows()[1].getChildren()[1].setValue(data.value);
	});
});

function saveCredentials() {
	Keychain.setForKey({
		key: 'username',
		value: tableView.getData()[0].getRows()[0].getChildren()[1].getValue(),
		serviceName: Ti.App.getId()
	}, function() {
	});

	Keychain.setForKey({
		key: 'password',
		value: tableView.getData()[0].getRows()[1].getChildren()[1].getValue(),
		serviceName: Ti.App.getId()
	}, function() {
	});
}

win.addEventListener('blur', saveCredentials);
tableView.getData()[0].getRows()[0].getChildren()[1].addEventListener('blur', saveCredentials);
tableView.getData()[0].getRows()[1].getChildren()[1].addEventListener('blur', saveCredentials);
<commit_msg>Fix for randomly non-loading username<commit_after>Ti.include('/includes/lib/json.i18n.js');

var win = Ti.UI.currentWindow,
	Utils = require('/includes/utils'),
	Keychain = require('clearlyinnovative.keychain');

function getTextFieldRow(text, hint, isPassword) {
	var row = Ti.UI.createTableViewRow({
		selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.NONE,
		layout: 'horizontal'
	}),

	rowText = Ti.UI.createLabel({
		text: text,
		left: 10,
		width: Ti.UI.SIZE,
		top: 5,
		bottom: 5,
		height: 30,
		font: {
			fontWeight: 'bold',
			fontSize: 17
		}
	}),

	textfield = Ti.UI.createTextField({
		color: '#336699',
		right: 10,
		left: 5,
		top: 5,
		bottom: 5,
		height: 30,
		width: Ti.UI.FILL,
		textAlign: Ti.UI.TEXT_ALIGNMENT_RIGHT,
		autocorrect: false,
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_NONE,
		returnKeyType: Ti.UI.RETURNKEY_NEXT,
		hintText: hint,
		passwordMask: isPassword,
		autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
		clearButtonMode: Ti.UI.INPUT_BUTTONMODE_ONFOCUS
	});

	row.add(rowText);

	rowText.addEventListener('postlayout', function() {
		if(rowText.rect.width >= 140) {
			rowText.width = 140;
		}
	});

	row.add(textfield);
	return row;
}

var b_credits = Ti.UI.createButton({
	title: I('credits.title')
});

b_credits.addEventListener('click', function() {
	var credits_win = Ti.UI.createWindow({
		url: 'credits.js',
		title: I('credits.title'),
		backgroundRepeat: true,
		barColor: Utils.getNavColor(),
		backgroundImage: Utils.getBGImage()
	});

	if(Utils.isiPad()) {
		win.masterGroup.open(credits_win);
	} else {
		win.navGroup.open(credits_win);
	}
});

if(Utils.isiPhone()) {
	var b_close = Ti.UI.createButton({
		title: I('buttons.close'),
		style: Titanium.UI.iPhone.SystemButtonStyle.DONE
	});

	b_close.addEventListener('click', function() {
		win.container.close();
	});

	win.setRightNavButton(b_credits);
	win.setLeftNavButton(b_close);
} else {
	win.setRightNavButton(b_credits);
}

var lbl_header = Ti.UI.createLabel({
	text: I('settings.header'),
	color: '#F8F8F8',
	font: {
		fontSize: 17,
		fontWeight: 'bold'
	},
	shadowColor: 'black',
	shadowOffset: {
		x: 0,
		y: 1
	},
	top: 15,
	left: 15,
	height: Ti.UI.SIZE
}),

tableView = Ti.UI.createTableView({
	data: [getTextFieldRow(I('settings.username'), 'Notch', false), getTextFieldRow(I('settings.password'), '●●●●●●●●●●●', true)],
	style: Ti.UI.iPhone.TableViewStyle.GROUPED,
	backgroundColor: 'transparent',
	rowBackgroundColor: 'white',
	scrollable: false,
	rowHeight: 45,
	height: 120
}),

lbl_footer = Ti.UI.createLabel({
	text: I('settings.footer.migratedAccount') + '\n\n' + I('settings.footer.privacy'),
	color: '#F8F8F8',
	font: {
		fontSize: (Utils.isiPad()) ? 18 : 15
	},
	shadowColor: 'black',
	shadowOffset: {
		x: 0,
		y: 1
	},
	top: 15,
	left: 15,
	right: 15,
	height: Ti.UI.SIZE
});

win.add(lbl_header);
win.add(tableView);
win.add(lbl_footer);

Keychain.getForKey({
	key: 'username',
	serviceName: Ti.App.getId()
}, function(data) {
	tableView.getData()[0].getRows()[0].getChildren()[1].setValue(data.value);
});

Keychain.getForKey({
	key: 'password',
	serviceName: Ti.App.getId()
}, function(data) {
	tableView.getData()[0].getRows()[1].getChildren()[1].setValue(data.value);
});

function saveCredentials() {
	Keychain.setForKey({
		key: 'username',
		value: tableView.getData()[0].getRows()[0].getChildren()[1].getValue(),
		serviceName: Ti.App.getId()
	}, function() {
	});

	Keychain.setForKey({
		key: 'password',
		value: tableView.getData()[0].getRows()[1].getChildren()[1].getValue(),
		serviceName: Ti.App.getId()
	}, function() {
	});
}

win.addEventListener('blur', saveCredentials);
tableView.getData()[0].getRows()[0].getChildren()[1].addEventListener('blur', saveCredentials);
tableView.getData()[0].getRows()[1].getChildren()[1].addEventListener('blur', saveCredentials);
<|endoftext|>


<commit_before>/*
 * handlebars pattern engine for patternlab-node - v0.15.1 - 2015
 *
 * Geoffrey Pursell, Brian Muenzenmeyer, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

/*
 * ENGINE SUPPORT LEVEL:
 *
 * Full. Partial calls and lineage hunting are supported. Handlebars does not
 * support the mustache-specific syntax extensions, style modifiers and pattern
 * parameters, because their use cases are addressed by the core Handlebars
 * feature set.
 *
 */

"use strict";

var Handlebars = require('handlebars');

var engine_handlebars = {
  engine: Handlebars,
  engineName: 'handlebars',
  engineFileExtension: '.hbs',

  // partial expansion is only necessary for Mustache templates that have
  // style modifiers or pattern parameters (I think)
  expandPartials: false,

  // regexes, stored here so they're only compiled once
  findPartialsRE: /{{#?>\s*([\w-\/.]+)(?:.|\s+)*?}}/g,
  findListItemsRE: /({{#( )?)(list(I|i)tems.)(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)( )?}}/g,

  // render it
  renderPattern: function renderPattern(pattern, data, partials) {
    if (partials) {
      Handlebars.registerPartial(partials);
    }
    var compiled = Handlebars.compile(pattern.extendedTemplate);
    return compiled(data);
  },

  registerPartial: function (oPattern) {
    Handlebars.registerPartial(oPattern.key, oPattern.template);
  },

  // find and return any {{> template-name }} within pattern
  findPartials: function findPartials(pattern) {
    var matches = pattern.template.match(this.findPartialsRE);
    return matches;
  },
  findPartialsWithStyleModifiers: function () {
    // TODO: make the call to this from oPattern objects conditional on their
    // being implemented here.
    return [];
  },

  // returns any patterns that match {{> value(foo:"bar") }} or {{>
  // value:mod(foo:"bar") }} within the pattern
  findPartialsWithPatternParameters: function () {
    // TODO: make the call to this from oPattern objects conditional on their
    // being implemented here.
    return [];
  },
  findListItems: function (pattern) {
    var matches = pattern.template.match(this.findListItemsRE);
    return matches;
  },

  // given a pattern, and a partial string, tease out the "pattern key" and
  // return it.
  findPartial: function (partialString) {
    var partial = partialString.replace(this.findPartialsRE, '$1');
    return partial;
  }
};

module.exports = engine_handlebars;
<commit_msg>Pass the unit tests -- had to convert pattern.key to pattern.patternPartial<commit_after>/*
 * handlebars pattern engine for patternlab-node - v0.15.1 - 2015
 *
 * Geoffrey Pursell, Brian Muenzenmeyer, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

/*
 * ENGINE SUPPORT LEVEL:
 *
 * Full. Partial calls and lineage hunting are supported. Handlebars does not
 * support the mustache-specific syntax extensions, style modifiers and pattern
 * parameters, because their use cases are addressed by the core Handlebars
 * feature set.
 *
 */

"use strict";

var Handlebars = require('handlebars');

var engine_handlebars = {
  engine: Handlebars,
  engineName: 'handlebars',
  engineFileExtension: '.hbs',

  // partial expansion is only necessary for Mustache templates that have
  // style modifiers or pattern parameters (I think)
  expandPartials: false,

  // regexes, stored here so they're only compiled once
  findPartialsRE: /{{#?>\s*([\w-\/.]+)(?:.|\s+)*?}}/g,
  findListItemsRE: /({{#( )?)(list(I|i)tems.)(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)( )?}}/g,

  // render it
  renderPattern: function renderPattern(pattern, data, partials) {
    if (partials) {
      Handlebars.registerPartial(partials);
    }
    var compiled = Handlebars.compile(pattern.extendedTemplate);
    return compiled(data);
  },

  registerPartial: function (pattern) {
    Handlebars.registerPartial(pattern.patternPartial, pattern.template);
  },

  // find and return any {{> template-name }} within pattern
  findPartials: function findPartials(pattern) {
    var matches = pattern.template.match(this.findPartialsRE);
    return matches;
  },
  findPartialsWithStyleModifiers: function () {
    // TODO: make the call to this from oPattern objects conditional on their
    // being implemented here.
    return [];
  },

  // returns any patterns that match {{> value(foo:"bar") }} or {{>
  // value:mod(foo:"bar") }} within the pattern
  findPartialsWithPatternParameters: function () {
    // TODO: make the call to this from oPattern objects conditional on their
    // being implemented here.
    return [];
  },
  findListItems: function (pattern) {
    var matches = pattern.template.match(this.findListItemsRE);
    return matches;
  },

  // given a pattern, and a partial string, tease out the "pattern key" and
  // return it.
  findPartial: function (partialString) {
    var partial = partialString.replace(this.findPartialsRE, '$1');
    return partial;
  }
};

module.exports = engine_handlebars;
<|endoftext|>


<commit_before>var app = angular.module("app", ["ngMaterial", "ng","ngAnimate","ngAria", "angucomplete-alt"]);
app.controller("MainController", ["$scope", "$http", '$window', function($scope, $http, $window) {

  $scope.privacyAction = function(privacy){
    if(privacy){
       $scope.privacy = "PUBLIC";
    }else{
       $scope.privacy = "PRIVATE";
       $scope.coursecode = "";
    }
  }
  $scope.privacy = "PUBLIC";
  $scope.privacyToggle = true;

  $scope.gettingUserNotes = function(fbId) {
    $http({
      method: "GET",
          url: 'http://localhost:3000/api/usernotes/' + fbId
      })
      .then(function(response) {
        var privatenotes = [];
        var publicnotes = [];
        response.data.notes.forEach( function (arrayItem)
        {
            if (arrayItem.privacyLevel == "PRIVATE"){
              privatenotes.push(arrayItem);
            } else{
              publicnotes.push(arrayItem);
            }
        });
        console.log(privatenotes.length)
        if (privatenotes.length > 0){
          $('#private_heading').show();
        }
        if (publicnotes.length > 0){
          $('#public_heading').show();
        }
        $scope.privatenotesList = privatenotes;
        $scope.publicnotesList = publicnotes;
      },
      function(response) {
          alert("great failure");
    });
  }

  $scope.proceed = function() {
    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    var text = quill.getText();
    var delta = JSON.stringify(quill.getContents()); // have to stringify if we want pass it as a parameter
    var coursecode = $scope.coursecode;
    coursecode = coursecode.replace(/\s+/g,'');
    if (coursecode == ""){
      coursecode = "PRIVATE";
    }
    var mydata = $.param({
                "title": $scope.title,
                "writing": text,
                "coursecode" : coursecode,
                "delta": delta,
                "privacyLevel": $scope.privacy
               });
    $http({
        url: 'http://localhost:3000/api/note',
        method: "POST",
        data: mydata
    })
    .then(function(response) {
        $window.location.href = 'http://localhost:3000/courses/' + coursecode + "/" + response.data;
    },
    function(response) {
        alert("great failure");
    });
  }

  $scope.selectedObject = function(x) {
    if(x.originalObject.type === "coursecode") {
      $window.location.href = 'http://localhost:3000/courses/' + x.originalObject.title;
    } else if(x.originalObject.type === "title") {
      $window.location.href = 'http://localhost:3000/courses/' + x.originalObject.coursecode.toUpperCase() + "/" + x.originalObject.id;
    }
  }

}]);
<commit_msg>Remember old coursecode<commit_after>var app = angular.module("app", ["ngMaterial", "ng","ngAnimate","ngAria", "angucomplete-alt"]);
app.controller("MainController", ["$scope", "$http", '$window', function($scope, $http, $window) {

  $scope.privacyAction = function(privacy){
    if(privacy){
       $scope.privacy = "PUBLIC";
       $scope.coursecode = $scope.courseHidden;
    }else{
       $scope.privacy = "PRIVATE";
       $scope.courseHidden = $scope.coursecode;
       $scope.coursecode = "";
    }
  }

  $scope.privacy = "PUBLIC";
  $scope.privacyToggle = true;
  $scope.courseHidden = "";

  $scope.gettingUserNotes = function(fbId) {
    $http({
      method: "GET",
          url: 'http://localhost:3000/api/usernotes/' + fbId
      })
      .then(function(response) {
        var privatenotes = [];
        var publicnotes = [];
        response.data.notes.forEach( function (arrayItem)
        {
            if (arrayItem.privacyLevel == "PRIVATE"){
              privatenotes.push(arrayItem);
            } else{
              publicnotes.push(arrayItem);
            }
        });
        console.log(privatenotes.length)
        if (privatenotes.length > 0){
          $('#private_heading').show();
        }
        if (publicnotes.length > 0){
          $('#public_heading').show();
        }
        $scope.privatenotesList = privatenotes;
        $scope.publicnotesList = publicnotes;
      },
      function(response) {
          alert("great failure");
    });
  }

  $scope.proceed = function() {
    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    var text = quill.getText();
    var delta = JSON.stringify(quill.getContents()); // have to stringify if we want pass it as a parameter
    var coursecode = $scope.coursecode;
    coursecode = coursecode.replace(/\s+/g,'');
    if (coursecode == ""){
      coursecode = "PRIVATE";
    }
    var mydata = $.param({
                "title": $scope.title,
                "writing": text,
                "coursecode" : coursecode,
                "delta": delta,
                "privacyLevel": $scope.privacy
               });
    $http({
        url: 'http://localhost:3000/api/note',
        method: "POST",
        data: mydata
    })
    .then(function(response) {
        $window.location.href = 'http://localhost:3000/courses/' + coursecode + "/" + response.data;
    },
    function(response) {
        alert("great failure");
    });
  }

  $scope.selectedObject = function(x) {
    if(x.originalObject.type === "coursecode") {
      $window.location.href = 'http://localhost:3000/courses/' + x.originalObject.title;
    } else if(x.originalObject.type === "title") {
      $window.location.href = 'http://localhost:3000/courses/' + x.originalObject.coursecode.toUpperCase() + "/" + x.originalObject.id;
    }
  }

}]);
<|endoftext|>


<commit_before>/**
 * @TODO Document.
 */

/* globals jQuery: false, document: false, io: false, location: false, console: false, window: false, history: false, url: false */

// TODO:
//  grab on submit and cancel, get values
//  client-side protocol
//  show errors

jQuery.extend({
    getQueryParameters : function(str) {
        return (str || document.location.search)
            .replace(/(^\?)/,'')
            .split("&")
            .map(function(n){
                return n = n.split("="), this[n[0]] = (n[1] === "true" || n[1] === "false") ? JSON.parse(n[1]) : n[1], this;
            }
            .bind({}))[0];
    }
});

(function ($) {

    const MSG_EXCEPTION = {ui: 'Bug', bootstrap: 'danger'}
    ,   MSG_ERROR = {ui: 'Error', bootstrap: 'danger'}
    ,   MSG_WARN = {ui: 'Warning', bootstrap: 'warning'}
    ,   MSG_INFO = {ui: 'Advice', bootstrap: 'info'}
    ;

    var $form = $("form#options")
    ,   $urlContainer = $("#urlContainer")
    ,   $url = $("#url")
    ,   profile
    ,   $profileContainer = $("#profileContainer")
    ,   $profile = $("#profile")
    ,   $profileOptions = $('#profile option')
    ,   $validation = $("#validation")
    ,   $noRecTrack = $("#noRecTrack")
    ,   $informativeOnly = $("#informativeOnly")
    ,   $echidnaReady = $("#echidnaReady")
    ,   $patentPolicy = $("#patentPolicy")
    ,   $results = $('#results')
    ,   $resultsBody = $results.find('.panel-body')
    ,   $resultsList = $results.find('.list-group')
    ,   $progressContainer = $("#progressBar")
    ,   $progress = $progressContainer.find(".progress-bar")
    ,   $progressStyler = $progress.parent()
    ,   baseURI = (location.pathname + '/').replace(/\/+$/, '/')
    ,   socket = io(location.protocol + "//" + location.host, {path: baseURI + 'socket.io'})
    ,   done = 0
    ,   result = {exceptions: [], errors: [], warnings: [], infos: []}
    ,   total = 0
    ,   running = false
    ;

    // handshake
    socket.on("handshake", function (data) {
        console.log(`Handshake; using version “${data.version}”.`);

        socket.on('disconnect', function () {
            socket.close();
            toggleForm(false);
            $('#offline').modal();
        });

    });

    const toggleForm = function (bool) {
        if (bool) {
            $('form').css('opacity', 1);
            $('form input, form select, form label').removeClass('disabled').removeAttr('disabled');
            $('button[type=submit]').text('Check');
        } else {
            $('form').css('opacity', 0.333);
            $('form input, form select, form label').addClass('disabled').attr('disabled', 'disabled');
            $('button[type=submit]').text('Wait…');
        }
    };

    // validate
    function validate (options) {
        $resultsBody.empty();
        $resultsList.empty();
        profile = options.profile;
        socket.emit("validate", {
            url:                decodeURIComponent(options.url)
        ,   profile:            profile
        ,   validation:         options.validation
        ,   noRecTrack:         (true === options.noRecTrack)
        ,   informativeOnly:    (true === options.informativeOnly)
        ,   echidnaReady:       (true === options.echidnaReady)
        ,   patentPolicy:       options.patentPolicy
        });
    }

    // extractMetadata
    function extractMetadata (url) {
        socket.emit("extractMetadata", {
            url: decodeURIComponent(url)
        });
    }

    function addMessage (type, data) {
        const url = $url.val();
        var inContext = ''
        ,   issue
        ,   exc = (data && data.exception) ? ' exception' : ''
        ;
        if (data && data.id) {
            const newProfile = profile.replace(/\-echidna$/i, '');
            inContext = `<a href="doc/rules?profile=${newProfile}#${data.id}">See rule in context</a> <br>`;
        }
        if (data && data.name)
            issue = `<a href="https://github.com/w3c/specberus/issues/new?` +
                `title=Bug%20in%20rule%20%E2%80%9C${data.name}%E2%80%9D:%20[WHAT]&` +
                `body=[EXPLANATION]%0A%0AFound%20[while%20checking%20\`${url}\`](${encodeURIComponent(window.location)}).&` +
                `labels=from-template` +
                `">Report a bug</a>`;
        else if (data && data.exception)
            issue = `<a href="https://github.com/w3c/specberus/issues/new?` +
                `title=Bug:%20[WHAT]&` +
                `body=[EXPLANATION]%0A%0AFound%20[while%20checking%20\`${url}\`](${encodeURIComponent(window.location)}).&` +
                `labels=from-template` +
                `">Report a bug</a>`;
        else
            issue = `<a href="https://github.com/w3c/specberus/issues/new?` +
                `title=Bug%20in%20rules:%20[WHAT]&` +
                `body=[EXPLANATION]%0A%0AFound%20[while%20checking%20\`${url}\`](${encodeURIComponent(window.location)}).&` +
                `labels=from-template` +
                `">Report a bug</a>`;
        var item = `

            ${type.ui}

 ${inContext} ${issue}

            ${data.message}

`;
        if (MSG_EXCEPTION === type) result.exceptions.push(item);
        else if (MSG_ERROR === type) result.errors.push(item);
        else if (MSG_WARN === type) result.warnings.push(item);
        else if (MSG_INFO === type) result.infos.push(item);
    }

    function toggleManual(toggle) {
        $form.toggleClass('manual', toggle);
        $urlContainer.toggleClass('col-sm-4', !toggle);
        $urlContainer.toggleClass('col-sm-5', toggle);
        $profileContainer.toggleClass('col-sm-4 col-md-4 col-lg-4', !toggle);
        $profileContainer.toggleClass('col-sm-5 col-md-5 col-lg-5', toggle);
    }

    socket.on("exception", function (data) {
        const message = data.message ? data.message : data;
        addMessage(MSG_EXCEPTION, {message: `<div class="message">${message}</div>`, exception: true});
        window.setTimeout(showResults, 1000);
    });

    socket.on("start", function (data) {
        console.log('Started.');
        done = 0;
        result = {exceptions: [], errors: [], warnings: [], infos: []};
        total = data.rules.length;
        $progressStyler.addClass("active progress-striped");
        $progressContainer.fadeIn();
        $results.hide();
    });
    socket.on('err', function (data) {
        addMessage(MSG_ERROR, data);
    });
    socket.on('warning', function (data) {
        addMessage(MSG_WARN, data);
    });
    socket.on('info', function (data) {
        addMessage(MSG_INFO, data);
    });
    socket.on("done", function () {
        done++;
        $progress.attr({
            "aria-valuenow":    done
        ,   "aria-valuemax":    total
        ,   "style":            "width: " + (total ? (done/total)*100 : 0) + "%"
        });
        $progress.text(done + '/' + total);
    });
    socket.on("finished", function () {
        console.log('Finished.');
        showResults();
    });
    socket.on("finishedExtraction", function (data) {
        if (!data || !data.metadata || !data.metadata.profile) {
            addMessage(MSG_EXCEPTION, {message: `<div class="message">Metadata extraction could not infer a profile for the document.</div>`});
            window.setTimeout(showResults, 1000);
        }
        else {
            toggleManual(true);
            profile = data.metadata.profile;
            $profile.val(profile);
            $noRecTrack.prop('checked', !data.metadata.rectrack);
            $informativeOnly.prop('checked', data.metadata.informative);
            $validation.find("label").removeClass('active');
            $validation.find('label#simple-validation').addClass('active');
            var options = {
                              "url"             : data.url
                            , "profile"         : profile
                            , "validation"      : 'simple-validation'
                            , "noRecTrack"      : !data.metadata.rectrack || false
                            , "informativeOnly" : data.metadata.informative || false
                            , "echidnaReady"    : false
                            , "patentPolicy"    : "pp2004"
                          };
            validate(options);
            var newurl = document.URL.split('?')[0] + "?" + $.param(options);
            history.pushState(options, url + " - " + profile, newurl);
        }
    });

    $form.submit(function (event) {
        if (running) {
            if (event)
                event.preventDefault();
            return;
        }
        running = true;
        toggleForm(false);
        $resultsBody.empty();
        $resultsList.empty();
        result = {exceptions: [], errors: [], warnings: [], infos: []};
        if ($profile.val() === "auto") {
            extractMetadata($url.val());
        } else {
            var url = $url.val()
            ,   validation = $validation.find('label.active').attr('id')
            ,   noRecTrack = $noRecTrack.is(":checked") || false
            ,   informativeOnly = $informativeOnly.is(":checked") || false
            ,   echidnaReady = $echidnaReady.is(":checked") || false
            ,   patentPolicy = $patentPolicy.find('label.active').attr('id')
            ;
            profile = $profile.val();
            if (!url) addMessage(MSG_ERROR, 'Missing “URL” parameer');
            if (!profile) addMessage(MSG_ERROR, 'Missing “profile” parameter');
            if (echidnaReady) profile += '-Echidna';
            var options = {
                              "url"             : url
                            , "profile"         : profile
                            , "validation"      : validation
                            , "noRecTrack"      : noRecTrack
                            , "informativeOnly" : informativeOnly
                            , "echidnaReady"    : echidnaReady
                            , "patentPolicy"    : patentPolicy
                          };
            validate(options);
            var newurl = document.URL.split('?')[0] + "?" + $.param(options);
            history.pushState(options, url + " - " + profile, newurl);
        }
        return false;
    });

    function disableProfilesIfNeeded(checkbox) {
        if (checkbox.prop('checked')) {
            $profileOptions.each(function (_, el) {
                if ($(el).val() !== 'WD' && $(el).val() !== 'WG-NOTE')
                  $(el).prop('disabled', true);
            });
            if ($profile.val() !== 'WD' && $profile.val() !== 'WG-NOTE')
              $profile.val('');
        }
        else $profileOptions.each(function (_, el) {
            if ($(el).val() !== '') $(el).prop('disabled', false);
        });
    }

    function setFormParams(options) {
        // Option "echidnaReady" processed first, as it may restrict the list of enabled profiles.
        $echidnaReady.prop('checked', options.echidnaReady);
        if (options.url) $url.val(decodeURIComponent(options.url));
        // "profile" might be eg "WD-Echidna". Normalise.
        if (options.profile) {
          const newProfile = options.profile.replace(/\-echidna$/i, '');
          $profile.find('option[value=' + newProfile + ']').prop('selected', true);
        }
        if (options.validation) {
          $validation.find('label#' + options.validation).addClass('active');
          $validation.find(':not(label#' + options.validation + ')').removeClass('active');
        }
        $noRecTrack.prop('checked', options.noRecTrack);
        $informativeOnly.prop('checked', options.informativeOnly);
        if (options.patentPolicy) {
          $patentPolicy.find('label').removeClass('active');
          $patentPolicy.find('label#' + options.patentPolicy).addClass('active');
        }
    }

    const countNicely = function(term, no) {
        if (0 === no)
            return 'No ' + term + 's';
        else if (1 === no)
            return 'One ' + term;
        else
            return no + ' ' + term + 's';
    };

    function showResults() {
        toggleForm(true);
        running = false;
        $results.fadeIn();
        $progressStyler.removeClass("active progress-striped");
        $progressContainer.hide();
        $progress.text('');
        $progress.attr('style', '0');
        var message;
        if (result.errors.length > 0 || result.exceptions.length > 0) {
            message = `<span class="icon red pull-left">✗</span>`;
            if (result.warnings.length > 0)
                message += `
${countNicely('error', result.exceptions.length + result.errors.length)}
                    (and ${countNicely('warning', result.warnings.length)})
`;
            else
                message += `<h4>${countNicely('error', result.exceptions.length + result.errors.length)}</h4>`;
        }
        else {
            if (result.warnings.length > 0)
                message = `✓

All tests passed, but you are strongly encouraged to address
                    ${countNicely('warning', result.warnings.length).toLowerCase()} before publishing.
`;
            else
                message = `✓

OK!
`;
        }
        message += `<p class="details">`;
        if (total > 0 && profile)
            message += `<a href="doc/rules?profile=${profile}">${total} rules</a> were checked. `;
        message += `Hover over the rows below for options.<p>`;
        $resultsBody.html(message);
        message = '';
        if (result.exceptions.length > 0 || result.errors.length > 0 || result.warnings.length > 0 || result.infos.length > 0) {
            var i;
            for (i in result.exceptions) {
                message += result.exceptions[i];
            }
            for (i in result.errors) {
                message += result.errors[i];
            }
            for (i in result.warnings) {
                message += result.warnings[i];
            }
            for (i in result.infos) {
                message += result.infos[i];
            }
        }
        $resultsList.html(message);
    }

    window.addEventListener('popstate', function(event) {
        var options = event.state;
        if (null === options) return;
        setFormParams(options);
        validate(options);
    });

    $patentPolicy.find("label").on("click", function() {
        var isPP2002 = ($(this).attr("id") === "pp2002");
        $noRecTrack.prop("disabled", isPP2002);
        $informativeOnly.prop("disabled", isPP2002);
    });

    $profile.change(function() {
        toggleManual('auto' !== $(this).val());
    });

    $echidnaReady.change(function () {
        disableProfilesIfNeeded($echidnaReady);
    });

    $(document).ready(function() {
        $.getJSON(`${baseURI}data/profiles.json`, function(data) {
            $profile.append($('<option value="auto" selected="selected">Auto-detect</option>'));
            $.each(data.tracks, function(foo, track) {
                var optgroup = $('<optgroup label="' + track.name + '"></optgroup>');
                $.each(track.profiles, function(bar, profile) {
                    var option = $('<option value="' + profile.id + '">' + profile.id + ' — ' + profile.name + '</option>');
                    optgroup.append(option);
                });
                $profile.append(optgroup);
            });
            $profileOptions = $('#profile option');
            var options = $.getQueryParameters();
            setFormParams(options);
            toggleManual('auto' !== $profile.val());
            if (options.url && options.profile)
                $('form').submit();
            $('[data-toggle="tooltip"]').tooltip();
            $url.select();
        });
    });

}(jQuery));
<commit_msg>Encode URL when submitting a GH issue<commit_after>/**
 * @TODO Document.
 */

/* globals jQuery: false, document: false, io: false, location: false, console: false, window: false, history: false, url: false */

// TODO:
//  grab on submit and cancel, get values
//  client-side protocol
//  show errors

jQuery.extend({
    getQueryParameters : function(str) {
        return (str || document.location.search)
            .replace(/(^\?)/,'')
            .split("&")
            .map(function(n){
                return n = n.split("="), this[n[0]] = (n[1] === "true" || n[1] === "false") ? JSON.parse(n[1]) : n[1], this;
            }
            .bind({}))[0];
    }
});

(function ($) {

    const MSG_EXCEPTION = {ui: 'Bug', bootstrap: 'danger'}
    ,   MSG_ERROR = {ui: 'Error', bootstrap: 'danger'}
    ,   MSG_WARN = {ui: 'Warning', bootstrap: 'warning'}
    ,   MSG_INFO = {ui: 'Advice', bootstrap: 'info'}
    ;

    var $form = $("form#options")
    ,   $urlContainer = $("#urlContainer")
    ,   $url = $("#url")
    ,   profile
    ,   $profileContainer = $("#profileContainer")
    ,   $profile = $("#profile")
    ,   $profileOptions = $('#profile option')
    ,   $validation = $("#validation")
    ,   $noRecTrack = $("#noRecTrack")
    ,   $informativeOnly = $("#informativeOnly")
    ,   $echidnaReady = $("#echidnaReady")
    ,   $patentPolicy = $("#patentPolicy")
    ,   $results = $('#results')
    ,   $resultsBody = $results.find('.panel-body')
    ,   $resultsList = $results.find('.list-group')
    ,   $progressContainer = $("#progressBar")
    ,   $progress = $progressContainer.find(".progress-bar")
    ,   $progressStyler = $progress.parent()
    ,   baseURI = (location.pathname + '/').replace(/\/+$/, '/')
    ,   socket = io(location.protocol + "//" + location.host, {path: baseURI + 'socket.io'})
    ,   done = 0
    ,   result = {exceptions: [], errors: [], warnings: [], infos: []}
    ,   total = 0
    ,   running = false
    ;

    // handshake
    socket.on("handshake", function (data) {
        console.log(`Handshake; using version “${data.version}”.`);

        socket.on('disconnect', function () {
            socket.close();
            toggleForm(false);
            $('#offline').modal();
        });

    });

    const toggleForm = function (bool) {
        if (bool) {
            $('form').css('opacity', 1);
            $('form input, form select, form label').removeClass('disabled').removeAttr('disabled');
            $('button[type=submit]').text('Check');
        } else {
            $('form').css('opacity', 0.333);
            $('form input, form select, form label').addClass('disabled').attr('disabled', 'disabled');
            $('button[type=submit]').text('Wait…');
        }
    };

    // validate
    function validate (options) {
        $resultsBody.empty();
        $resultsList.empty();
        profile = options.profile;
        socket.emit("validate", {
            url:                decodeURIComponent(options.url)
        ,   profile:            profile
        ,   validation:         options.validation
        ,   noRecTrack:         (true === options.noRecTrack)
        ,   informativeOnly:    (true === options.informativeOnly)
        ,   echidnaReady:       (true === options.echidnaReady)
        ,   patentPolicy:       options.patentPolicy
        });
    }

    // extractMetadata
    function extractMetadata (url) {
        socket.emit("extractMetadata", {
            url: decodeURIComponent(url)
        });
    }

    function addMessage (type, data) {
        const url = $url.val();
        var inContext = ''
        ,   issue
        ,   exc = (data && data.exception) ? ' exception' : ''
        ;
        if (data && data.id) {
            const newProfile = profile.replace(/\-echidna$/i, '');
            inContext = `<a href="doc/rules?profile=${newProfile}#${data.id}">See rule in context</a> <br>`;
        }
        if (data && data.name)
            issue = `<a href="https://github.com/w3c/specberus/issues/new?` +
                `title=Bug%20in%20rule%20%E2%80%9C${data.name}%E2%80%9D:%20[WHAT]&` +
                `body=[EXPLANATION]%0A%0AFound%20[while%20checking%20\`${encodeURIComponent(url)}\`]` +
                `(${encodeURIComponent(window.location)}).&` +
                `labels=from-template` +
                `">Report a bug</a>`;
        else if (data && data.exception)
            issue = `<a href="https://github.com/w3c/specberus/issues/new?` +
                `title=Bug:%20[WHAT]&` +
                `body=[EXPLANATION]%0A%0AFound%20[while%20checking%20\`${encodeURIComponent(url)}\`]` +
                `(${encodeURIComponent(window.location)}).&` +
                `labels=from-template` +
                `">Report a bug</a>`;
        else
            issue = `<a href="https://github.com/w3c/specberus/issues/new?` +
                `title=Bug%20in%20rules:%20[WHAT]&` +
                `body=[EXPLANATION]%0A%0AFound%20[while%20checking%20\`${encodeURIComponent(url)}\`]` +
                `(${encodeURIComponent(window.location)}).&` +
                `labels=from-template` +
                `">Report a bug</a>`;
        var item = `

            ${type.ui}

 ${inContext} ${issue}

            ${data.message}

`;
        if (MSG_EXCEPTION === type) result.exceptions.push(item);
        else if (MSG_ERROR === type) result.errors.push(item);
        else if (MSG_WARN === type) result.warnings.push(item);
        else if (MSG_INFO === type) result.infos.push(item);
    }

    function toggleManual(toggle) {
        $form.toggleClass('manual', toggle);
        $urlContainer.toggleClass('col-sm-4', !toggle);
        $urlContainer.toggleClass('col-sm-5', toggle);
        $profileContainer.toggleClass('col-sm-4 col-md-4 col-lg-4', !toggle);
        $profileContainer.toggleClass('col-sm-5 col-md-5 col-lg-5', toggle);
    }

    socket.on("exception", function (data) {
        const message = data.message ? data.message : data;
        addMessage(MSG_EXCEPTION, {message: `<div class="message">${message}</div>`, exception: true});
        window.setTimeout(showResults, 1000);
    });

    socket.on("start", function (data) {
        console.log('Started.');
        done = 0;
        result = {exceptions: [], errors: [], warnings: [], infos: []};
        total = data.rules.length;
        $progressStyler.addClass("active progress-striped");
        $progressContainer.fadeIn();
        $results.hide();
    });
    socket.on('err', function (data) {
        addMessage(MSG_ERROR, data);
    });
    socket.on('warning', function (data) {
        addMessage(MSG_WARN, data);
    });
    socket.on('info', function (data) {
        addMessage(MSG_INFO, data);
    });
    socket.on("done", function () {
        done++;
        $progress.attr({
            "aria-valuenow":    done
        ,   "aria-valuemax":    total
        ,   "style":            "width: " + (total ? (done/total)*100 : 0) + "%"
        });
        $progress.text(done + '/' + total);
    });
    socket.on("finished", function () {
        console.log('Finished.');
        showResults();
    });
    socket.on("finishedExtraction", function (data) {
        if (!data || !data.metadata || !data.metadata.profile) {
            addMessage(MSG_EXCEPTION, {message: `<div class="message">Metadata extraction could not infer a profile for the document.</div>`});
            window.setTimeout(showResults, 1000);
        }
        else {
            toggleManual(true);
            profile = data.metadata.profile;
            $profile.val(profile);
            $noRecTrack.prop('checked', !data.metadata.rectrack);
            $informativeOnly.prop('checked', data.metadata.informative);
            $validation.find("label").removeClass('active');
            $validation.find('label#simple-validation').addClass('active');
            var options = {
                              "url"             : data.url
                            , "profile"         : profile
                            , "validation"      : 'simple-validation'
                            , "noRecTrack"      : !data.metadata.rectrack || false
                            , "informativeOnly" : data.metadata.informative || false
                            , "echidnaReady"    : false
                            , "patentPolicy"    : "pp2004"
                          };
            validate(options);
            var newurl = document.URL.split('?')[0] + "?" + $.param(options);
            history.pushState(options, url + " - " + profile, newurl);
        }
    });

    $form.submit(function (event) {
        if (running) {
            if (event)
                event.preventDefault();
            return;
        }
        running = true;
        toggleForm(false);
        $resultsBody.empty();
        $resultsList.empty();
        result = {exceptions: [], errors: [], warnings: [], infos: []};
        if ($profile.val() === "auto") {
            extractMetadata($url.val());
        } else {
            var url = $url.val()
            ,   validation = $validation.find('label.active').attr('id')
            ,   noRecTrack = $noRecTrack.is(":checked") || false
            ,   informativeOnly = $informativeOnly.is(":checked") || false
            ,   echidnaReady = $echidnaReady.is(":checked") || false
            ,   patentPolicy = $patentPolicy.find('label.active').attr('id')
            ;
            profile = $profile.val();
            if (!url) addMessage(MSG_ERROR, 'Missing “URL” parameer');
            if (!profile) addMessage(MSG_ERROR, 'Missing “profile” parameter');
            if (echidnaReady) profile += '-Echidna';
            var options = {
                              "url"             : url
                            , "profile"         : profile
                            , "validation"      : validation
                            , "noRecTrack"      : noRecTrack
                            , "informativeOnly" : informativeOnly
                            , "echidnaReady"    : echidnaReady
                            , "patentPolicy"    : patentPolicy
                          };
            validate(options);
            var newurl = document.URL.split('?')[0] + "?" + $.param(options);
            history.pushState(options, url + " - " + profile, newurl);
        }
        return false;
    });

    function disableProfilesIfNeeded(checkbox) {
        if (checkbox.prop('checked')) {
            $profileOptions.each(function (_, el) {
                if ($(el).val() !== 'WD' && $(el).val() !== 'WG-NOTE')
                  $(el).prop('disabled', true);
            });
            if ($profile.val() !== 'WD' && $profile.val() !== 'WG-NOTE')
              $profile.val('');
        }
        else $profileOptions.each(function (_, el) {
            if ($(el).val() !== '') $(el).prop('disabled', false);
        });
    }

    function setFormParams(options) {
        // Option "echidnaReady" processed first, as it may restrict the list of enabled profiles.
        $echidnaReady.prop('checked', options.echidnaReady);
        if (options.url) $url.val(decodeURIComponent(options.url));
        // "profile" might be eg "WD-Echidna". Normalise.
        if (options.profile) {
          const newProfile = options.profile.replace(/\-echidna$/i, '');
          $profile.find('option[value=' + newProfile + ']').prop('selected', true);
        }
        if (options.validation) {
          $validation.find('label#' + options.validation).addClass('active');
          $validation.find(':not(label#' + options.validation + ')').removeClass('active');
        }
        $noRecTrack.prop('checked', options.noRecTrack);
        $informativeOnly.prop('checked', options.informativeOnly);
        if (options.patentPolicy) {
          $patentPolicy.find('label').removeClass('active');
          $patentPolicy.find('label#' + options.patentPolicy).addClass('active');
        }
    }

    const countNicely = function(term, no) {
        if (0 === no)
            return 'No ' + term + 's';
        else if (1 === no)
            return 'One ' + term;
        else
            return no + ' ' + term + 's';
    };

    function showResults() {
        toggleForm(true);
        running = false;
        $results.fadeIn();
        $progressStyler.removeClass("active progress-striped");
        $progressContainer.hide();
        $progress.text('');
        $progress.attr('style', '0');
        var message;
        if (result.errors.length > 0 || result.exceptions.length > 0) {
            message = `<span class="icon red pull-left">✗</span>`;
            if (result.warnings.length > 0)
                message += `
${countNicely('error', result.exceptions.length + result.errors.length)}
                    (and ${countNicely('warning', result.warnings.length)})
`;
            else
                message += `<h4>${countNicely('error', result.exceptions.length + result.errors.length)}</h4>`;
        }
        else {
            if (result.warnings.length > 0)
                message = `✓

All tests passed, but you are strongly encouraged to address
                    ${countNicely('warning', result.warnings.length).toLowerCase()} before publishing.
`;
            else
                message = `✓

OK!
`;
        }
        message += `<p class="details">`;
        if (total > 0 && profile)
            message += `<a href="doc/rules?profile=${profile}">${total} rules</a> were checked. `;
        message += `Hover over the rows below for options.<p>`;
        $resultsBody.html(message);
        message = '';
        if (result.exceptions.length > 0 || result.errors.length > 0 || result.warnings.length > 0 || result.infos.length > 0) {
            var i;
            for (i in result.exceptions) {
                message += result.exceptions[i];
            }
            for (i in result.errors) {
                message += result.errors[i];
            }
            for (i in result.warnings) {
                message += result.warnings[i];
            }
            for (i in result.infos) {
                message += result.infos[i];
            }
        }
        $resultsList.html(message);
    }

    window.addEventListener('popstate', function(event) {
        var options = event.state;
        if (null === options) return;
        setFormParams(options);
        validate(options);
    });

    $patentPolicy.find("label").on("click", function() {
        var isPP2002 = ($(this).attr("id") === "pp2002");
        $noRecTrack.prop("disabled", isPP2002);
        $informativeOnly.prop("disabled", isPP2002);
    });

    $profile.change(function() {
        toggleManual('auto' !== $(this).val());
    });

    $echidnaReady.change(function () {
        disableProfilesIfNeeded($echidnaReady);
    });

    $(document).ready(function() {
        $.getJSON(`${baseURI}data/profiles.json`, function(data) {
            $profile.append($('<option value="auto" selected="selected">Auto-detect</option>'));
            $.each(data.tracks, function(foo, track) {
                var optgroup = $('<optgroup label="' + track.name + '"></optgroup>');
                $.each(track.profiles, function(bar, profile) {
                    var option = $('<option value="' + profile.id + '">' + profile.id + ' — ' + profile.name + '</option>');
                    optgroup.append(option);
                });
                $profile.append(optgroup);
            });
            $profileOptions = $('#profile option');
            var options = $.getQueryParameters();
            setFormParams(options);
            toggleManual('auto' !== $profile.val());
            if (options.url && options.profile)
                $('form').submit();
            $('[data-toggle="tooltip"]').tooltip();
            $url.select();
        });
    });

}(jQuery));
<|endoftext|>


<commit_before>var path = require('path');

var config = {
  input_file:  process.env.DASH_SOURCE_INPUT_FILE || path.join(process.cwd(), 'input.ts'),
  segment_dir: process.env.DASH_SEGMENT_INPUT_DIR || path.sep + path.join('tmp', 'dash_segment_input_dir'),
  output_dir:  process.env.DASH_OUTPUT_DIR        || path.sep + path.join('tmp', 'dash_output_dir'),
  mp4box:      process.env.DASH_MP4BOX            || 'MP4Box',
  ffmpeg:      process.env.DASH_FFMPEG            || 'ffmpeg',
  transcoding: {
    ffmpeg_opts: ['-re', '-i', '-', '-analyzeduration', '2147483647', '-probesize', '2147483647', '-threads', '0', '-y'],
    hls_opts: ['-hls_time', '10'],
    video_opts: ['-vcodec', 'libx264', '-vprofile', 'baseline', '-level', '31', '-keyint_min', '25', '-g', '25', '-r', '25'],
    audio_opts: ['-vn', '-acodec', 'aac', '-strict', '-2', '-ar', '48000', '-ac', '2']
  }
}

config.representations = {
  video_hd:       config.transcoding.video_opts.concat(['-vb', '4000k', '-bufsize', '8000k', '-maxrate', '4000k', '-s', '1280x720', '-an']).concat(config.transcoding.hls_opts),
  //video_veryhigh: config.transcoding.video_opts.concat(['-vb', '3072k', '-s', '960x540', '-an']).concat(config.transcoding.hls_opts),
  video_high:     config.transcoding.video_opts.concat(['-vb', '2000k', '-bufsize', '4000k', '-maxrate', '2000k', '-s', '768x432', '-an']).concat(config.transcoding.hls_opts),
  //video_med:      config.transcoding.video_opts.concat(['-vb', '1024k', '-s', '640x360', '-an']).concat(config.transcoding.hls_opts),
  video_low:      config.transcoding.video_opts.concat(['-vb', '500k', '-bufsize', '1000k', '-maxrate', '500k', '-s', '480x270', '-an']).concat(config.transcoding.hls_opts),
  audio:     config.transcoding.audio_opts.concat(['-ab', '128k']).concat(config.transcoding.hls_opts)
}

config.packaging = {
  mp4box_opts: ['-dash-ctx', path.join(config.output_dir, 'dash-live.txt'), '-dash', '10000', '-rap', '-ast-offset', '31', '-no-frags-default',
                '-bs-switching', 'no', '-mpd-refresh', '10', '-min-buffer', '30000', '-url-template', '-time-shift', '1800',
                '-mpd-title', 'EBU test live stream for MPEG-DASH test engine, created by Hiro (http://madebyhiro.com/en/).', '-mpd-info-url', 'http://ebu.io/',
                '-segment-name', 'live_$RepresentationID$_', '-out', path.join(config.output_dir, 'live'), '-dynamic']
}

config.getRepresentationKeys = function() {
  return Object.keys(config.representations);
}

module.exports = config;
<commit_msg>Update presets<commit_after>var path = require('path');

var config = {
  input_file:  process.env.DASH_SOURCE_INPUT_FILE || path.join(process.cwd(), 'input.ts'),
  segment_dir: process.env.DASH_SEGMENT_INPUT_DIR || path.sep + path.join('tmp', 'dash_segment_input_dir'),
  output_dir:  process.env.DASH_OUTPUT_DIR        || path.sep + path.join('tmp', 'dash_output_dir'),
  mp4box:      process.env.DASH_MP4BOX            || 'MP4Box',
  ffmpeg:      process.env.DASH_FFMPEG            || 'ffmpeg',
  transcoding: {
    ffmpeg_opts: ['-re', '-i', '-', '-analyzeduration', '2147483647', '-probesize', '2147483647', '-threads', '0', '-y'],
    hls_opts: ['-hls_time', '10'],
    video_opts: ['-vcodec', 'libx264', '-vprofile', 'baseline', '-preset', 'veryfast', '-level', '31', '-keyint_min', '25', '-g', '25', '-r', '25'],
    audio_opts: ['-vn', '-acodec', 'aac', '-strict', '-2', '-ar', '48000', '-ac', '2']
  }
}

config.representations = {
  video_hd:       config.transcoding.video_opts.concat(['-vb', '4096k', '-bufsize', '8192k', '-maxrate', '4096k', '-s', '1280x720', '-an']).concat(config.transcoding.hls_opts),
  //video_veryhigh: config.transcoding.video_opts.concat(['-vb', '3072k', '-s', '960x540', '-an']).concat(config.transcoding.hls_opts),
  video_high:     config.transcoding.video_opts.concat(['-vb', '2048k', '-bufsize', '4096k', '-maxrate', '2048k', '-s', '768x432', '-an']).concat(config.transcoding.hls_opts),
  //video_med:      config.transcoding.video_opts.concat(['-vb', '1024k', '-s', '640x360', '-an']).concat(config.transcoding.hls_opts),
  video_low:      config.transcoding.video_opts.concat(['-vb', '512k', '-bufsize', '1024k', '-maxrate', '512k', '-s', '480x270', '-an']).concat(config.transcoding.hls_opts),
  audio:     config.transcoding.audio_opts.concat(['-ab', '128k']).concat(config.transcoding.hls_opts)
}

config.packaging = {
  mp4box_opts: ['-dash-ctx', path.join(config.output_dir, 'dash-live.txt'), '-dash', '10000', '-rap', '-ast-offset', '31', '-no-frags-default',
                '-bs-switching', 'no', '-mpd-refresh', '10', '-min-buffer', '30000', '-url-template', '-time-shift', '1800',
                '-mpd-title', 'EBU test live stream for MPEG-DASH test engine, created by Hiro (http://madebyhiro.com/en/).', '-mpd-info-url', 'http://ebu.io/',
                '-segment-name', 'live_$RepresentationID$_', '-out', path.join(config.output_dir, 'live'), '-dynamic']
}

config.getRepresentationKeys = function() {
  return Object.keys(config.representations);
}

module.exports = config;
<|endoftext|>