text:
(function (root, factory) {
    if (typeof exports === 'object') {
        // CommonJS
        factory(exports, require('underscore'), require('./parser'), require('./expander'), require('./syntax'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([
            'exports',
            'underscore',
            'parser',
            'expander',
            'syntax'
        ], factory);
    }
}(this, function (exports$2, _, parser, expander, syntax) {
    var get_expression = expander.get_expression;
    var syntaxFromToken = syntax.syntaxFromToken;
    var makePunc = syntax.makePunc;
    var joinSyntax = syntax.joinSyntax;
    var joinSyntaxArr = syntax.joinSyntaxArr;
    var assert = syntax.assert;
    var throwSyntaxError = syntax.throwSyntaxError;
    var push = Array.prototype.push;
    // ([...CSyntax]) -> [...Str]
    function freeVarsInPattern(pattern) {
        var fv = [];
        _.each(pattern, function (pat) {
            if (isPatternVar(pat)) {
                fv.push(pat.token.value);
            } else if (pat.token.type === parser.Token.Delimiter) {
                push.apply(fv, freeVarsInPattern(pat.token.inner));
            }
        });
        return fv;
    }
    function typeIsLiteral(type) {
        return type === parser.Token.NullLiteral || type === parser.Token.NumericLiteral || type === parser.Token.StringLiteral || type === parser.Token.RegexLiteral || type === parser.Token.BooleanLiteral;
    }
    function containsPatternVar(patterns) {
        return _.any(patterns, function (pat) {
            if (pat.token.type === parser.Token.Delimiter) {
                return containsPatternVar(pat.token.inner);
            }
            return isPatternVar(pat);
        });
    }
    function delimIsSeparator(delim) {
        return delim && delim.token && delim.token.type === parser.Token.Delimiter && delim.token.value === '()' && delim.token.inner.length === 1 && delim.token.inner[0].token.type !== parser.Token.Delimiter && !containsPatternVar(delim.token.inner);
    }
    function isPatternVar(stx) {
        return stx.token.value[0] === '$' && stx.token.value !== '$';
    }
    // ([...{level: Num, match: [...CSyntax]}], Str) -> [...CSyntax]
    function joinRepeatedMatch(tojoin, punc) {
        return _.reduce(_.rest(tojoin, 1), function (acc, join) {
            if (punc === ' ') {
                return acc.concat(join.match);
            }
            return acc.concat(makePunc(punc, _.first(join.match)), join.match);
        }, _.first(tojoin).match);
    }
    // take the line context (range, lineNumber)
    // (CSyntax, [...CSyntax]) -> [...CSyntax]
    function takeLineContext(from, to) {
        return _.map(to, function (stx) {
            return takeLine(from, stx);
        });
    }
    // (CSyntax, CSyntax) -> CSyntax
    function takeLine(from, to) {
        var next;
        if (to.token.type === parser.Token.Delimiter) {
            var sm_startLineNumber = typeof to.token.sm_startLineNumber !== 'undefined' ? to.token.sm_startLineNumber : to.token.startLineNumber;
            var sm_endLineNumber = typeof to.token.sm_endLineNumber !== 'undefined' ? to.token.sm_endLineNumber : to.token.endLineNumber;
            var sm_startLineStart = typeof to.token.sm_startLineStart !== 'undefined' ? to.token.sm_startLineStart : to.token.startLineStart;
            var sm_endLineStart = typeof to.token.sm_endLineStart !== 'undefined' ? to.token.sm_endLineStart : to.token.endLineStart;
            var sm_startRange = typeof to.token.sm_startRange !== 'undefined' ? to.token.sm_startRange : to.token.startRange;
            var sm_endRange = typeof to.token.sm_endRange !== 'undefined' ? to.token.sm_endRange : to.token.endRange;
            if (from.token.type === parser.Token.Delimiter) {
                next = syntaxFromToken({
                    type: parser.Token.Delimiter,
                    value: to.token.value,
                    inner: takeLineContext(from, to.token.inner),
                    startRange: from.token.startRange,
                    endRange: from.token.endRange,
                    startLineNumber: from.token.startLineNumber,
                    startLineStart: from.token.startLineStart,
                    endLineNumber: from.token.endLineNumber,
                    endLineStart: from.token.endLineStart,
                    sm_startLineNumber: sm_startLineNumber,
                    sm_endLineNumber: sm_endLineNumber,
                    sm_startLineStart: sm_startLineStart,
                    sm_endLineStart: sm_endLineStart,
                    sm_startRange: sm_startRange,
                    sm_endRange: sm_endRange
                }, to);
            } else {
                next = syntaxFromToken({
                    type: parser.Token.Delimiter,
                    value: to.token.value,
                    inner: takeLineContext(from, to.token.inner),
                    startRange: from.token.range,
                    endRange: from.token.range,
                    startLineNumber: from.token.lineNumber,
                    startLineStart: from.token.lineStart,
                    endLineNumber: from.token.lineNumber,
                    endLineStart: from.token.lineStart,
                    sm_startLineNumber: sm_startLineNumber,
                    sm_endLineNumber: sm_endLineNumber,
                    sm_startLineStart: sm_startLineStart,
                    sm_endLineStart: sm_endLineStart,
                    sm_startRange: sm_startRange,
                    sm_endRange: sm_endRange
                }, to);
            }
        } else {
            var sm_lineNumber = typeof to.token.sm_lineNumber !== 'undefined' ? to.token.sm_lineNumber : to.token.lineNumber;
            var sm_lineStart = typeof to.token.sm_lineStart !== 'undefined' ? to.token.sm_lineStart : to.token.lineStart;
            var sm_range = typeof to.token.sm_range !== 'undefined' ? to.token.sm_range : to.token.range;
            if (from.token.type === parser.Token.Delimiter) {
                next = syntaxFromToken({
                    value: to.token.value,
                    type: to.token.type,
                    lineNumber: from.token.startLineNumber,
                    lineStart: from.token.startLineStart,
                    range: from.token.startRange,
                    sm_lineNumber: sm_lineNumber,
                    sm_lineStart: sm_lineStart,
                    sm_range: sm_range
                }, to);
            } else {
                next = syntaxFromToken({
                    value: to.token.value,
                    type: to.token.type,
                    lineNumber: from.token.lineNumber,
                    lineStart: from.token.lineStart,
                    range: from.token.range,
                    sm_lineNumber: sm_lineNumber,
                    sm_lineStart: sm_lineStart,
                    sm_range: sm_range
                }, to);
            }
        }
        if (to.token.leadingComments) {
            next.token.leadingComments = to.token.leadingComments;
        }
        if (to.token.trailingComments) {
            next.token.trailingComments = to.token.trailingComments;
        }
        return next;
    }
    function reversePattern(patterns) {
        var len = patterns.length;
        var pat;
        return _.reduceRight(patterns, function (acc, pat$2) {
            if (pat$2.class === 'pattern_group') {
                pat$2.token.inner = reversePattern(pat$2.token.inner);
            }
            if (pat$2.repeat) {
                pat$2.leading = !pat$2.leading;
            }
            acc.push(pat$2);
            return acc;
        }, []);
    }
    function loadLiteralGroup(patterns) {
        _.forEach(patterns, function (patStx) {
            if (patStx.token.type === parser.Token.Delimiter) {
                patStx.token.inner = loadLiteralGroup(patStx.token.inner);
            } else {
                patStx.class = 'pattern_literal';
            }
        });
        return patterns;
    }
    function loadPattern(patterns, reverse) {
        var patts = _.chain(patterns).reduce(function (acc, patStx, idx) {
                var last = patterns[idx - 1];
                var lastLast = patterns[idx - 2];
                var next = patterns[idx + 1];
                var nextNext = patterns[idx + 2];
                // skip over the `:lit` part of `$x:lit`
                if (patStx.token.value === ':') {
                    if (last && isPatternVar(last) && !isPatternVar(next)) {
                        return acc;
                    }
                }
                if (last && last.token.value === ':') {
                    if (lastLast && isPatternVar(lastLast) && !isPatternVar(patStx)) {
                        return acc;
                    }
                }
                // skip over $
                if (patStx.token.value === '$' && next && next.token.type === parser.Token.Delimiter) {
                    return acc;
                }
                if (isPatternVar(patStx)) {
                    if (next && next.token.value === ':' && !isPatternVar(nextNext)) {
                        if (typeof nextNext === 'undefined') {
                            throwSyntaxError('patterns', 'expecting a pattern class following a `:`', next);
                        }
                        patStx.class = nextNext.token.value;
                    } else {
                        patStx.class = 'token';
                    }
                } else if (patStx.token.type === parser.Token.Delimiter) {
                    if (last && last.token.value === '$') {
                        patStx.class = 'pattern_group';
                    }
                    // Leave literal groups as is
                    if (patStx.class === 'pattern_group' && patStx.token.value === '[]') {
                        patStx.token.inner = loadLiteralGroup(patStx.token.inner);
                    } else {
                        patStx.token.inner = loadPattern(patStx.token.inner);
                    }
                } else {
                    patStx.class = 'pattern_literal';
                }
                acc.push(patStx);
                return acc;
            }    // then second pass to mark repeat and separator
, []).reduce(function (acc, patStx, idx, patterns$2) {
                var separator = patStx.separator || ' ';
                var repeat = patStx.repeat || false;
                var next = patterns$2[idx + 1];
                var nextNext = patterns$2[idx + 2];
                if (next && next.token.value === '...') {
                    repeat = true;
                    separator = ' ';
                } else if (delimIsSeparator(next) && nextNext && nextNext.token.value === '...') {
                    repeat = true;
                    assert(next.token.inner.length === 1, 'currently assuming all separators are a single token');
                    separator = next.token.inner[0].token.value;
                }
                // skip over ... and (,)
                if (patStx.token.value === '...' || delimIsSeparator(patStx) && next && next.token.value === '...') {
                    return acc;
                }
                patStx.repeat = repeat;
                patStx.separator = separator;
                acc.push(patStx);
                return acc;
            }, []).value();
        return reverse ? reversePattern(patts) : patts;
    }
    function cachedTermMatch(stx, term) {
        var res = [];
        var i = 0;
        while (stx[i] && stx[i].term === term) {
            res.unshift(stx[i]);
            i++;
        }
        return {
            result: term,
            destructed: res,
            rest: stx.slice(res.length)
        };
    }
    // (Str, [...CSyntax], MacroEnv) -> {result: null or [...CSyntax], rest: [...CSyntax]}
    function matchPatternClass(patternClass, stx, env) {
        var result, rest, match;
        // pattern has no parse class
        if (patternClass === 'token' && stx[0] && stx[0].token.type !== parser.Token.EOF) {
            result = [stx[0]];
            rest = stx.slice(1);
        } else if (patternClass === 'lit' && stx[0] && typeIsLiteral(stx[0].token.type)) {
            result = [stx[0]];
            rest = stx.slice(1);
        } else if (patternClass === 'ident' && stx[0] && stx[0].token.type === parser.Token.Identifier) {
            result = [stx[0]];
            rest = stx.slice(1);
        } else if (stx.length > 0 && patternClass === 'VariableStatement') {
            match = stx[0].term ? cachedTermMatch(stx, stx[0].term) : expander.enforest(stx, expander.makeExpanderContext({ env: env }));
            if (match.result && match.result.hasPrototype(expander.VariableStatement)) {
                result = match.destructed || match.result.destruct(false);
                rest = match.rest;
            } else {
                result = null;
                rest = stx;
            }
        } else if (stx.length > 0 && patternClass === 'expr') {
            match = stx[0].term ? cachedTermMatch(stx, stx[0].term) : expander.get_expression(stx, expander.makeExpanderContext({ env: env }));
            if (match.result === null || !match.result.hasPrototype(expander.Expr)) {
                result = null;
                rest = stx;
            } else {
                result = match.destructed || match.result.destruct(false);
                rest = match.rest;
            }
        } else {
            result = null;
            rest = stx;
        }
        return {
            result: result,
            rest: rest
        };
    }
    // attempt to match patterns against stx
    // ([...Pattern], [...Syntax], Env) -> { result: [...Syntax], rest: [...Syntax], patternEnv: PatternEnv }
    function matchPatterns(patterns, stx, env, topLevel) {
        // topLevel lets us know if the patterns are on the top level or nested inside
        // a delimiter:
        //     case $topLevel (,) ... => { }
        //     case ($nested (,) ...) => { }
        // This matters for how we deal with trailing unmatched syntax when the pattern
        // has an ellipses:
        //     m 1,2,3 foo
        // should match 1,2,3 and leave foo alone but:
        //     m (1,2,3 foo)
        // should fail to match entirely.
        topLevel = topLevel || false;
        // note that there are two environments floating around,
        // one is the mapping of identifiers to macro definitions (env)
        // and the other is the pattern environment (patternEnv) that maps
        // patterns in a macro case to syntax.
        var result = [];
        var patternEnv = {};
        var match;
        var pattern;
        var rest = stx;
        var success = true;
        var inLeading;
        patternLoop:
            for (var i = 0; i < patterns.length; i++) {
                if (success === false) {
                    break;
                }
                pattern = patterns[i];
                inLeading = false;
                do {
                    // handles cases where patterns trail a repeated pattern like `$x ... ;`
                    if (pattern.repeat && i + 1 < patterns.length) {
                        var restMatch = matchPatterns(patterns.slice(i + 1), rest, env, topLevel);
                        if (restMatch.success) {
                            // match the repeat pattern on the empty array to fill in its
                            // pattern variable in the environment
                            match = matchPattern(pattern, [], env, patternEnv, topLevel);
                            patternEnv = _.extend(restMatch.patternEnv, match.patternEnv);
                            rest = restMatch.rest;
                            break patternLoop;
                        }
                    }
                    if (pattern.repeat && pattern.leading && pattern.separator !== ' ') {
                        if (rest[0].token.value === pattern.separator) {
                            if (!inLeading) {
                                inLeading = true;
                            }
                            rest = rest.slice(1);
                        } else {
                            // If we are in a leading repeat, the separator is required.
                            if (inLeading) {
                                success = false;
                                break;
                            }
                        }
                    }
                    match = matchPattern(pattern, rest, env, patternEnv, topLevel);
                    if (!match.success && pattern.repeat) {
                        // a repeat can match zero tokens and still be a
                        // "success" so break out of the inner loop and
                        // try the next pattern
                        break;
                    }
                    if (!match.success) {
                        success = false;
                        break;
                    }
                    rest = match.rest;
                    patternEnv = match.patternEnv;
                    if (success && !(topLevel || pattern.repeat)) {
                        // the very last pattern matched, inside a
                        // delimiter, not a repeat, *and* there are more
                        // unmatched bits of syntax
                        if (i == patterns.length - 1 && rest.length !== 0) {
                            success = false;
                            break;
                        }
                    }
                    if (pattern.repeat && !pattern.leading && success) {
                        // if (i < patterns.length - 1 && rest.length > 0) {
                        //     var restMatch = matchPatterns(patterns.slice(i+1), rest, env, topLevel);
                        //     if (restMatch.success) {
                        //         patternEnv = _.extend(patternEnv, restMatch.patternEnv);
                        //         rest = restMatch.rest;
                        //         break patternLoop;
                        //     }
                        // }
                        if (pattern.separator === ' ') {
                            // no separator specified (using the empty string for this)
                            // so keep going
                            continue;
                        } else if (rest[0] && rest[0].token.value === pattern.separator) {
                            // more tokens and the next token matches the separator
                            rest = rest.slice(1);
                        } else if (pattern.separator !== ' ' && rest.length > 0 && i === patterns.length - 1 && topLevel === false) {
                            // separator is specified, there is a next token, the
                            // next token doesn't match the separator, there are
                            // no more patterns, and this is a top level pattern
                            // so the match has failed
                            success = false;
                            break;
                        } else {
                            break;
                        }
                    }
                } while (pattern.repeat && success && rest.length > 0);
            }
        var result;
        if (success) {
            result = rest.length ? stx.slice(0, -rest.length) : stx;
        } else {
            result = [];
        }
        return {
            success: success,
            result: result,
            rest: rest,
            patternEnv: patternEnv
        };
    }
    /* the pattern environment will look something like:
    {
        "$x": {
            level: 2,
            match: [{
                level: 1,
                match: [{
                    level: 0,
                    match: [tok1, tok2, ...]
                }, {
                    level: 0,
                    match: [tok1, tok2, ...]
                }]
            }, {
                level: 1,
                match: [{
                    level: 0,
                    match: [tok1, tok2, ...]
                }]
            }]
        },
        "$y" : ...
    }
    */
    function matchPattern(pattern, stx, env, patternEnv, topLevel) {
        var subMatch;
        var match, matchEnv;
        var rest;
        var success;
        if (typeof pattern.inner !== 'undefined') {
            if (pattern.class === 'pattern_group') {
                // pattern groups don't match the delimiters
                subMatch = matchPatterns(pattern.inner, stx, env, true);
                rest = subMatch.rest;
            } else if (stx[0] && stx[0].token.type === parser.Token.Delimiter && stx[0].token.value === pattern.value) {
                stx[0].expose();
                if (pattern.inner.length === 0 && stx[0].token.inner.length !== 0) {
                    return {
                        success: false,
                        rest: stx,
                        patternEnv: patternEnv
                    };
                }
                subMatch = matchPatterns(pattern.inner, stx[0].token.inner, env, false);
                rest = stx.slice(1);
            } else {
                return {
                    success: false,
                    rest: stx,
                    patternEnv: patternEnv
                };
            }
            success = subMatch.success;
            // merge the subpattern matches with the current pattern environment
            _.keys(subMatch.patternEnv).forEach(function (patternKey) {
                if (pattern.repeat) {
                    // if this is a repeat pattern we need to bump the level
                    var nextLevel = subMatch.patternEnv[patternKey].level + 1;
                    if (patternEnv[patternKey]) {
                        patternEnv[patternKey].level = nextLevel;
                        patternEnv[patternKey].match.push(subMatch.patternEnv[patternKey]);
                    } else {
                        // initialize if we haven't done so already
                        patternEnv[patternKey] = {
                            level: nextLevel,
                            match: [subMatch.patternEnv[patternKey]],
                            topLevel: topLevel
                        };
                    }
                } else {
                    // otherwise accept the environment as-is
                    patternEnv[patternKey] = subMatch.patternEnv[patternKey];
                }
            });
        } else {
            if (pattern.class === 'pattern_literal') {
                // wildcard
                if (stx[0] && pattern.value === '_') {
                    success = true;
                    rest = stx.slice(1);
                }    // match the literal but don't update the pattern environment
                else if (stx[0] && pattern.value === stx[0].token.value) {
                    success = true;
                    rest = stx.slice(1);
                } else {
                    success = false;
                    rest = stx;
                }
            } else {
                match = matchPatternClass(pattern.class, stx, env);
                success = match.result !== null;
                rest = match.rest;
                matchEnv = {
                    level: 0,
                    match: match.result,
                    topLevel: topLevel
                };
                // push the match onto this value's slot in the environment
                if (pattern.repeat) {
                    if (patternEnv[pattern.value] && success) {
                        patternEnv[pattern.value].match.push(matchEnv);
                    } else if (patternEnv[pattern.value] === undefined) {
                        // initialize if necessary
                        patternEnv[pattern.value] = {
                            level: 1,
                            match: [matchEnv],
                            topLevel: topLevel
                        };
                    }
                } else {
                    patternEnv[pattern.value] = matchEnv;
                }
            }
        }
        return {
            success: success,
            rest: rest,
            patternEnv: patternEnv
        };
    }
    function matchLookbehind(patterns, stx, terms, env) {
        var success, patternEnv, prevStx, prevTerms;
        // No lookbehind, noop.
        if (!patterns.length) {
            success = true;
            patternEnv = {};
            prevStx = stx;
            prevTerms = terms;
        } else {
            var match = matchPatterns(patterns, stx, env, true);
            var last = match.result[match.result.length - 1];
            success = match.success;
            patternEnv = match.patternEnv;
            if (success) {
                if (match.rest.length) {
                    if (last && last.term === match.rest[0].term) {
                        // The term tree was split, so its a failed match;
                        success = false;
                    } else {
                        prevStx = match.rest;
                        // Find where to slice the prevTerms to match up with
                        // the state of prevStx.
                        for (var i = 0, len = terms.length; i < len; i++) {
                            if (terms[i] === prevStx[0].term) {
                                prevTerms = terms.slice(i);
                                break;
                            }
                        }
                    }
                } else {
                    prevTerms = [];
                    prevStx = [];
                }
            }
        }
        // We need to reverse the matches for any top level repeaters because
        // they match in reverse, and thus put their results in backwards.
        _.forEach(patternEnv, function (val, key) {
            if (val.level && val.match && val.topLevel) {
                val.match.reverse();
            }
        });
        return {
            success: success,
            patternEnv: patternEnv,
            prevStx: prevStx,
            prevTerms: prevTerms
        };
    }
    function hasMatch(m) {
        if (m.level === 0) {
            return m.match.length > 0;
        }
        return m.match.every(function (m$2) {
            return hasMatch(m$2);
        });
    }
    // given the given the macroBody (list of Pattern syntax objects) and the
    // environment (a mapping of patterns to syntax) return the body with the
    // appropriate patterns replaces with their value in the environment
    function transcribe(macroBody, macroNameStx, env) {
        return _.chain(macroBody).reduce(function (acc, bodyStx, idx, original) {
            // first find the ellipses and mark the syntax objects
            // (note that this step does not eagerly go into delimiter bodies)
            var last = original[idx - 1];
            var next = original[idx + 1];
            var nextNext = original[idx + 2];
            // drop `...`
            if (bodyStx.token.value === '...') {
                return acc;
            }
            // drop `(<separator)` when followed by an ellipse
            if (delimIsSeparator(bodyStx) && next && next.token.value === '...') {
                return acc;
            }
            // skip the $ in $(...)
            if (bodyStx.token.value === '$' && next && next.token.type === parser.Token.Delimiter && next.token.value === '()') {
                return acc;
            }
            // mark $[...] as a literal
            if (bodyStx.token.value === '$' && next && next.token.type === parser.Token.Delimiter && next.token.value === '[]') {
                next.literal = true;
                return acc;
            }
            if (bodyStx.token.type === parser.Token.Delimiter && bodyStx.token.value === '()' && last && last.token.value === '$') {
                bodyStx.group = true;
            }
            // literal [] delimiters have their bodies just
            // directly passed along
            if (bodyStx.literal === true) {
                assert(bodyStx.token.type === parser.Token.Delimiter, 'expecting a literal to be surrounded by []');
                return acc.concat(bodyStx.token.inner);
            }
            if (next && next.token.value === '...') {
                bodyStx.repeat = true;
                bodyStx.separator = ' ';
            }    // default to space separated
            else if (delimIsSeparator(next) && nextNext && nextNext.token.value === '...') {
                bodyStx.repeat = true;
                bodyStx.separator = next.token.inner[0].token.value;
            }
            acc.push(bodyStx);
            return acc;
        }, []).reduce(function (acc, bodyStx, idx) {
            // then do the actual transcription
            if (bodyStx.repeat) {
                if (bodyStx.token.type === parser.Token.Delimiter) {
                    bodyStx.expose();
                    var fv = _.filter(freeVarsInPattern(bodyStx.token.inner), function (pat) {
                            // ignore "patterns"
                            // that aren't in the
                            // environment (treat
                            // them like literals)
                            return env.hasOwnProperty(pat);
                        });
                    var restrictedEnv = [];
                    var nonScalar = _.find(fv, function (pat) {
                            return env[pat].level > 0;
                        });
                    assert(typeof nonScalar !== 'undefined', 'must have a least one non-scalar in repeat');
                    var repeatLength = env[nonScalar].match.length;
                    var sameLength = _.all(fv, function (pat) {
                            return env[pat].level === 0 || env[pat].match.length === repeatLength;
                        });
                    assert(sameLength, 'all non-scalars must have the same length');
                    // create a list of envs restricted to the free vars
                    _.each(_.range(repeatLength), function (idx$2) {
                        var renv = {};
                        _.each(fv, function (pat) {
                            if (env[pat].level === 0) {
                                // copy scalars over
                                renv[pat] = env[pat];
                            } else {
                                // grab the match at this index
                                renv[pat] = env[pat].match[idx$2];
                            }
                        });
                        var allHaveMatch = Object.keys(renv).every(function (pat) {
                                return hasMatch(renv[pat]);
                            });
                        if (allHaveMatch) {
                            restrictedEnv.push(renv);
                        }
                    });
                    var transcribed = _.map(restrictedEnv, function (renv) {
                            if (bodyStx.group) {
                                return transcribe(bodyStx.token.inner, macroNameStx, renv);
                            } else {
                                var newBody$2 = syntaxFromToken(_.clone(bodyStx.token), bodyStx);
                                newBody$2.token.inner = transcribe(bodyStx.token.inner, macroNameStx, renv);
                                return newBody$2;
                            }
                        });
                    var joined;
                    if (bodyStx.group) {
                        joined = joinSyntaxArr(transcribed, bodyStx.separator);
                    } else {
                        joined = joinSyntax(transcribed, bodyStx.separator);
                    }
                    push.apply(acc, joined);
                    return acc;
                }
                if (!env[bodyStx.token.value]) {
                    throwSyntaxError('patterns', 'The pattern variable is not bound for the template', bodyStx);
                } else if (env[bodyStx.token.value].level !== 1) {
                    throwSyntaxError('patterns', 'Ellipses level does not match in the template', bodyStx);
                }
                push.apply(acc, joinRepeatedMatch(env[bodyStx.token.value].match, bodyStx.separator));
                return acc;
            } else {
                if (bodyStx.token.type === parser.Token.Delimiter) {
                    bodyStx.expose();
                    var newBody = syntaxFromToken(_.clone(bodyStx.token), macroBody);
                    newBody.token.inner = transcribe(bodyStx.token.inner, macroNameStx, env);
                    acc.push(newBody);
                    return acc;
                }
                if (isPatternVar(bodyStx) && Object.prototype.hasOwnProperty.bind(env)(bodyStx.token.value)) {
                    if (!env[bodyStx.token.value]) {
                        throwSyntaxError('patterns', 'The pattern variable is not bound for the template', bodyStx);
                    } else if (env[bodyStx.token.value].level !== 0) {
                        throwSyntaxError('patterns', 'Ellipses level does not match in the template', bodyStx);
                    }
                    push.apply(acc, takeLineContext(bodyStx, env[bodyStx.token.value].match));
                    return acc;
                }
                acc.push(syntaxFromToken(_.clone(bodyStx.token), bodyStx));
                return acc;
            }
        }, []).value();
    }
    function extendEnv(env) {
        var newEnv = _.clone(env);
        newEnv.parent = env;
        return newEnv;
    }
    exports$2.loadPattern = loadPattern;
    exports$2.matchPatterns = matchPatterns;
    exports$2.matchLookbehind = matchLookbehind;
    exports$2.transcribe = transcribe;
    exports$2.matchPatternClass = matchPatternClass;
    exports$2.takeLineContext = takeLineContext;
    exports$2.takeLine = takeLine;
    exports$2.typeIsLiteral = typeIsLiteral;
    exports$2.extendEnv = extendEnv;
}));
//# sourceMappingURL=patterns.js.map


text:
package de.codecentric.boot.admin.client.config;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties;
import org.springframework.boot.actuate.endpoint.web.PathMappedEndpoints;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnCloudPlatform;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.cloud.CloudPlatform;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Lazy;

import de.codecentric.boot.admin.client.registration.CloudFoundryApplicationFactory;
import de.codecentric.boot.admin.client.registration.metadata.CloudFoundryMetadataContributor;
import de.codecentric.boot.admin.client.registration.metadata.CompositeMetadataContributor;
import de.codecentric.boot.admin.client.registration.metadata.MetadataContributor;

@AutoConfiguration(before = SpringBootAdminClientAutoConfiguration.class)
@ConditionalOnWebApplication
@ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY)
@Conditional(SpringBootAdminClientEnabledCondition.class)
@EnableConfigurationProperties(CloudFoundryApplicationProperties.class)
public class SpringBootAdminClientCloudFoundryAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean
	public CloudFoundryMetadataContributor cloudFoundryMetadataContributor(
			CloudFoundryApplicationProperties cloudFoundryApplicationProperties) {
		return new CloudFoundryMetadataContributor(cloudFoundryApplicationProperties);
	}

	@Bean
	@Lazy(false)
	@ConditionalOnMissingBean
	public CloudFoundryApplicationFactory applicationFactory(InstanceProperties instance,
			ManagementServerProperties management, ServerProperties server, PathMappedEndpoints pathMappedEndpoints,
			WebEndpointProperties webEndpoint, ObjectProvider<List<MetadataContributor>> metadataContributors,
			CloudFoundryApplicationProperties cfApplicationProperties) {
		return new CloudFoundryApplicationFactory(instance, management, server, pathMappedEndpoints, webEndpoint,
				new CompositeMetadataContributor(metadataContributors.getIfAvailable(Collections::emptyList)),
				cfApplicationProperties);
	}

}

redpajama_set_name: RedPajamaGithub


text:
package voicesplitting.voice.hmm;

/**
 * An HmmVoiceSplittingModelParameters contains the parameters to use for
 * an {@link HmmVoiceSplittingModel}.
 *

 * All of the fields contained within are final.
 *
 * @author Andrew McLeod - 13 April, 2015
 * @version 1.0
 * @since 1.0
 */
public class HmmVoiceSplittingModelParameters implements Comparable<HmmVoiceSplittingModelParameters> {
	/**
	 * The minimum possible gap score we will give out.
	 */
	public final double MIN_GAP_SCORE;

	/**
	 * The default value for {@link #MIN_GAP_SCORE}.
	 */
	public static final double MIN_GAP_SCORE_DEFAULT = 8E-4;

	/**
	 * The standard deviation to use for the Gaussian distribution used to calculate the
	 * pitch score. A pitch gap of exactly this many
	 * semitones will result in a Gaussian score of 1/sqrt(e).
	 */
	public final double PITCH_STD;

	/**
	 * The default value for {@link #PITCH_STD}.
	 */
	public static final double PITCH_STD_DEFAULT = 4;

	/**
	 * The standard deviation to use for the Gaussian distribution used to calculate the
	 * gap score. A gap of exactly this many microseconds will result in a Gaussian score of 1/sqrt(e).
	 */
	public final double GAP_STD_MICROS;

	/**
	 * The default value for {@link #GAP_STD_MICROS}.
	 */
	public static final double GAP_STD_MICROS_DEFAULT = 127000;

	/**
	 * The number of chords back we want to look in order to determine the weighted pitch.
	 */
	public final int PITCH_HISTORY_LENGTH;

	/**
	 * The default value for {@link #PITCH_HISTORY_LENGTH}
	 */
	public static final int PITCH_HISTORY_LENGTH_DEFAULT = 6;

	/**
	 * The probability score to return for adding a note to an empty Voice.
	 */
	public final double NEW_VOICE_PROBABILITY;

	/**
	 * The default value for {@link #NEW_VOICE_PROBABILITY}.
	 */
	public static final double NEW_VOICE_PROBABILITY_DEFAULT = 1E-9;

	/**
	 * The beam size for our search. It seems that 1 is optimal anyways, so we can remove this probably.
	 */
	public final int BEAM_SIZE;

	/**
	 * The default value for {@link #BEAM_SIZE}.
	 */
	public static final int BEAM_SIZE_DEFAULT = 25;

	/**
	 * Create a new params object with the given values.
	 *
	 * @param BS {@link #BEAM_SIZE}
	 * @param NVP {@link #NEW_VOICE_PROBABILITY}
	 * @param PHL {@link #PITCH_HISTORY_LENGTH}
	 * @param GSM {@link #GAP_STD_MICROS}
	 * @param PS {@link #PITCH_STD}
	 * @param MGS {@link #MIN_GAP_SCORE}
	 */
	public HmmVoiceSplittingModelParameters(int BS, double NVP, int PHL, double GSM, double PS, double MGS) {
		BEAM_SIZE = BS;
		NEW_VOICE_PROBABILITY = NVP;
		PITCH_HISTORY_LENGTH = PHL;
		GAP_STD_MICROS = GSM;
		PITCH_STD = PS;
		MIN_GAP_SCORE = MGS;
	}

	/**
	 * Create new params with default values for live performance data.
	 *
	 * @param live Unused.
	 */
	public HmmVoiceSplittingModelParameters(boolean live) {
		this(25, 3E-8, 6, 806000, 6, 0.01);
	}

	/**
	 * Create new params with default values. The default values referred to here are those found to be optimized
	 * when tuning to test on the computer-generated WTC Fugues, as noted in the paper. Specifically:
	 *

	 * {@link #BEAM_SIZE} = {@value #BEAM_SIZE_DEFAULT}
	 * {@link #NEW_VOICE_PROBABILITY} = {@value #NEW_VOICE_PROBABILITY_DEFAULT}
	 * {@link #PITCH_HISTORY_LENGTH} = {@value #PITCH_HISTORY_LENGTH_DEFAULT}
	 * {@link #GAP_STD_MICROS} = {@value #GAP_STD_MICROS_DEFAULT}
	 * {@link #PITCH_STD} = {@value #PITCH_STD_DEFAULT}
	 * {@link #MIN_GAP_SCORE} = {@value #MIN_GAP_SCORE_DEFAULT}
	 */
	public HmmVoiceSplittingModelParameters() {
		this(BEAM_SIZE_DEFAULT, NEW_VOICE_PROBABILITY_DEFAULT, PITCH_HISTORY_LENGTH_DEFAULT, GAP_STD_MICROS_DEFAULT, PITCH_STD_DEFAULT, MIN_GAP_SCORE_DEFAULT);
	}

	/**
	 * Return whether the given Object is equal to this one, which is only the case
	 * when the given Object is an HmmVoiceSplittingModelParameters, and all of its
	 * fields are equal to this one's.
	 *
	 * @param other The object we are checking for equality.
	 * @return True if the given Object is equal to this one. False otherwise.
	 */
	@Override
	public boolean equals(Object other) {
		if (!(other instanceof HmmVoiceSplittingModelParameters)) {
			return false;
		}

		HmmVoiceSplittingModelParameters p = (HmmVoiceSplittingModelParameters) other;

		return BEAM_SIZE == p.BEAM_SIZE
				&& NEW_VOICE_PROBABILITY == p.NEW_VOICE_PROBABILITY
				&& PITCH_HISTORY_LENGTH == p.PITCH_HISTORY_LENGTH
				&& GAP_STD_MICROS == p.GAP_STD_MICROS
				&& PITCH_STD == p.PITCH_STD
				&& MIN_GAP_SCORE == p.MIN_GAP_SCORE;
	}

	/**
	 * Get the hash code of this HmmVoiceSplittingModelParameters object.
	 *
	 * @return The hash code of this HmmVoiceSplittingModelParameters object.
	 */
	@Override
	public int hashCode() {
		return BEAM_SIZE +
				Double.valueOf(NEW_VOICE_PROBABILITY).hashCode() +
				PITCH_HISTORY_LENGTH +
				Double.valueOf(GAP_STD_MICROS).hashCode() +
				Double.valueOf(PITCH_STD).hashCode() +
				Double.valueOf(MIN_GAP_SCORE).hashCode();
	}

	/**
	 * Get the String representation of this object, which is in the following format:
	 *

	 * ({@link #BEAM_SIZE},{@link #NEW_VOICE_PROBABILITY},{@link #PITCH_HISTORY_LENGTH},{@link #GAP_STD_MICROS},{@link #PITCH_STD},{@link #MIN_GAP_SCORE})
	 *
	 * @return The String representation of this HmmVoiceSplittingModelParameters object.
	 */
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("(");

		sb.append(BEAM_SIZE).append(',');
		sb.append(NEW_VOICE_PROBABILITY).append(',');
		sb.append(PITCH_HISTORY_LENGTH).append(',');
		sb.append(GAP_STD_MICROS).append(',');
		sb.append(PITCH_STD).append(',');
		sb.append(MIN_GAP_SCORE).append(')');

		return sb.toString();
	}

	/**
	 * Compare the given HmmVoiceSplittingModelParameters to this one and return their difference.
	 * They are ordered first by their {@link #BEAM_SIZE}, followed by their {@link #MIN_GAP_SCORE},
	 * {@link #PITCH_STD}, {@link #GAP_STD_MICROS}, {@link #NEW_VOICE_PROBABILITY}, and
	 * {@link #PITCH_HISTORY_LENGTH} respectively.
	 *
	 * @param o The HmmVoiceSplittingModelParameters we are comparing to.
	 * @return A positive number if this HmmVoiceSplittingModelParameters should come first, negative
	 * if the given one should come first, or 0 if they are equal.
	 */
	@Override
	public int compareTo(HmmVoiceSplittingModelParameters o) {
		if (o == null) {
			return -1;
		}

		int result = Integer.compare(BEAM_SIZE, o.BEAM_SIZE);
		if (result != 0) {
			return result;
		}

		result = Double.compare(MIN_GAP_SCORE, o.MIN_GAP_SCORE);
		if (result != 0) {
			return result;
		}

		result = Double.compare(PITCH_STD, o.PITCH_STD);
		if (result != 0) {
			return result;
		}

		result = Double.compare(GAP_STD_MICROS, o.GAP_STD_MICROS);
		if (result != 0) {
			return result;
		}

		result = Double.compare(NEW_VOICE_PROBABILITY, o.NEW_VOICE_PROBABILITY);
		if (result != 0) {
			return result;
		}

		return Integer.compare(PITCH_HISTORY_LENGTH, o.PITCH_HISTORY_LENGTH);
	}
}


text:
namespace Spitfire.Disruptor
{
    /// <summary>
    /// The abstraction over array-like structures for entries.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IEntryHolder<T>
    {
        T this[int index] { get; }
        int Count { get; }
    }
}


text:
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.

/*=============================================================================
	UnAsyncLoading.cpp: Unreal async messsage log.
=============================================================================*/

#include "CoreUObjectPrivate.h"
#include "Serialization/DeferredMessageLog.h"

FDeferredMessageLog::FDeferredMessageLog(const FName& InLogCategory)
: LogCategory(InLogCategory)
{
	TArray<TSharedRef<FTokenizedMessage>>** ExistingCategoryMessages = Messages.Find(LogCategory);
	if (!ExistingCategoryMessages)
	{
		TArray<TSharedRef<FTokenizedMessage>>* CategoryMessages = new TArray<TSharedRef<FTokenizedMessage>>();
		Messages.Add(LogCategory, CategoryMessages);
	}
}

void FDeferredMessageLog::AddMessage(TSharedRef<FTokenizedMessage>& Message)
{
	TArray<TSharedRef<FTokenizedMessage>>* CategoryMessages = Messages.FindRef(LogCategory);
	check(CategoryMessages);
	CategoryMessages->Add(Message);
}

TSharedRef<FTokenizedMessage> FDeferredMessageLog::Info(const FText& InMessage)
{
	TSharedRef<FTokenizedMessage> Message = FTokenizedMessage::Create(EMessageSeverity::Info, InMessage);
	AddMessage(Message);
	return Message;
}

TSharedRef<FTokenizedMessage> FDeferredMessageLog::Warning(const FText& InMessage)
{
	TSharedRef<FTokenizedMessage> Message = FTokenizedMessage::Create(EMessageSeverity::Warning, InMessage);
	AddMessage(Message);
	return Message;
}

TSharedRef<FTokenizedMessage> FDeferredMessageLog::Error(const FText& InMessage)
{
	TSharedRef<FTokenizedMessage> Message = FTokenizedMessage::Create(EMessageSeverity::Error, InMessage);
	AddMessage(Message);
	return Message;
}

void FDeferredMessageLog::Flush()
{
	for (auto& CategoryMessages : Messages)
	{
		if (CategoryMessages.Value->Num())
		{
			FMessageLog LoaderLog(CategoryMessages.Key);
			LoaderLog.AddMessages(*CategoryMessages.Value);
			CategoryMessages.Value->Empty(CategoryMessages.Value->Num());
		}
	}
}

TMap<FName, TArray<TSharedRef<FTokenizedMessage>>*> FDeferredMessageLog::Messages;


text:
package healthchecker

import (
	"os"

	. "github.com/cloudfoundry-incubator/route-registrar/config"
	"github.com/pivotal-golang/lager"
)

type HealthChecker interface {
	Check() bool
}

func InitHealthChecker(clientConfig Config, logger lager.Logger, scriptPath string) HealthChecker {
	if clientConfig.HealthChecker != nil {
		if clientConfig.HealthChecker.Name == "riak-cs-cluster" {
			//TODO: these should be passed in via registrar_settings.yml
			riak_pidfile := "/var/vcap/sys/run/riak/riak.pid"
			riak_admin_program := "/var/vcap/packages/riak/rel/bin/riak-admin"
			riak_cs_pidfile := "/var/vcap/sys/run/riak-cs/riak-cs.pid"

			riakChecker := NewRiakHealthChecker(riak_pidfile, riak_admin_program, clientConfig.ExternalIp, logger, scriptPath)
			riakCSChecker := NewRiakCSHealthChecker(riak_cs_pidfile, logger)
			checkers := []HealthChecker{riakChecker, riakCSChecker}

			checker := NewCompositeChecker(checkers)
			return checker
		}

		if clientConfig.HealthChecker.Name == "script" {
			return NewScriptHealthChecker(clientConfig.HealthChecker.HealthcheckScript, logger)
		}
	}
	return nil
}

func checkPIDExist(pidFileName string) bool {
	_, err := os.Stat(pidFileName)
	return nil == err
}


text:
#ifndef NAMEUNIQUIFIER_H
#define NAMEUNIQUIFIER_H

#include "pandabase.h"

#include <string>
#include "pset.h"

/**
 * A handy class for converting a list of arbitrary names (strings) so that
 * each name is guaranteed to be unique in the list.  Useful for writing egg
 * files with unique vertex pool names, or for file converters to file formats
 * that require unique node names, etc.
 */
class EXPCL_PANDA_PUTIL NameUniquifier {
public:
  NameUniquifier(const std::string &separator = std::string(),
                 const std::string &empty = std::string());
  ~NameUniquifier();

  INLINE std::string add_name(const std::string &name);
  INLINE std::string add_name(const std::string &name, const std::string &prefix);

private:
  std::string add_name_body(const std::string &name, const std::string &prefix);

  typedef pset<std::string, string_hash> Names;
  Names _names;
  std::string _separator;
  std::string _empty;
  int _counter;
};

#include "nameUniquifier.I"

#endif


text:
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Dialog;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class View extends Thread {
	/**
	 * Deklariert die grafische Benutzeroberfläche des Servers.
	 */
	Frame controllerFrame;
	/**
	 * Legt den Standard-Port fest, welcher für den Kommunikationsaufbau
	 * zwischen Server und Client dient, sofern der Benutzer in der grafischen
	 * Benutzeroverfläche des Servers keinen anderen Port wählt.
	 */
	final static String PORT = "56789";

	/**
	 * Deklariert die Datenbasis
	 */
	String defaultBaseFile;

	/**
	 * Der Konstruktor der Klasse View nimmt den übergebenen Standard-Dateinamen
	 * für die Datenbasis entgegen. Dieser wird verwendet, sofern der Benutzer
	 * keine andere Datenbasis wählt.
	 *
	 * @param defaultBaseFile
	 *            Standard-Dateiname der Datenbasis
	 */
	View(String defaultBaseFile) {
		this.defaultBaseFile = defaultBaseFile;
	}

	/**
	 * Initialisiert die grafische Benutzeroberfläche mit einem Hauptfenster.
	 * Sollte das Fenster über das 'X'-Symbol versucht werden zu beenden, wird
	 * dem Nutzer eine Sicherheitsabfrage gestellt, ob das Programm wirklich
	 * beendet werden soll. Auf der grafischen Oberfläche wird der Port
	 * abgefragt, in Form eines Textfeldes. Dieses Textfeld ist dabei mit dem
	 * Standardport vorbelegt. Weiterhin kann zwischen der Datenbasis 'CSV' oder
	 * 'Datenbank' ausgewählt werden. Wird 'CSV' ausgewählt, so öffnet sich der
	 * File-Dialog, bei dem eine wahlfreie Datei für die Speicherung der Daten
	 * ausgewählt werden kann. Wird keine angegeben, so wird die
	 * Standard-CSV-Datenbasis verwendet. Zudem befinden sich zwei Buttons
	 * 'Serverstart' und 'Serverstop' innerhalb der GUI. Dise haben ihrem Namen
	 * entsprechende Funktion. Nach dem Start des Servers wird dem Benutzer
	 * angezeigt, in welche Datenbasis geschrieben wird (Name der Datenbasis)
	 * und wie viele Clients derzeit connected sind.
	 */
	@Override
	public void run() {
		controllerFrame = new Frame("Server");
		controllerFrame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(final WindowEvent e) {
				final Dialog yesNoDialog = new Dialog(controllerFrame);
				yesNoDialog.setLayout(new GridLayout(3, 1));
				Label label = new Label(
						"Wollen Sie das Programm wirklich beenden?");
				yesNoDialog.add(label);
				Button yes = new Button("Ja");
				yes.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						System.exit(0);
					}
				});
				Button no = new Button("Nein");
				no.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						yesNoDialog.dispose();
					}
				});
				yesNoDialog.add(yes);
				yesNoDialog.add(no);
				yesNoDialog.setSize(300, 100);
				yesNoDialog.setVisible(true);
			}
		});
		controllerFrame.setLayout(new GridLayout(2, 1));
		Panel data = new Panel();
		data.setLayout(new GridLayout(2, 1));
		data.add(new Label("Port: "));
		final TextField port = new TextField(5);
		port.setText(PORT);
		data.add(port);
		CheckboxGroup dataBase = new CheckboxGroup();
		Checkbox csv = new Checkbox("CSV", dataBase, false);
		data.add(csv);
		Checkbox database = new Checkbox("Datenbank", dataBase, false);
		data.add(database);

		/**
		 * BaseFileHelper wird verwendet um aus der inneren Klasse und aus der
		 * Klasse in der diese inneren Klasse eingebettet ist, auf Attribute
		 * zuzugreifen und diese zu verändern.
		 *
		 */
		class BaseFileHelper {
			String baseFile = defaultBaseFile;
			String basePath = defaultBaseFile;
		}
		final BaseFileHelper baseFileHelper = new BaseFileHelper();

		csv.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				FileDialog dataFile = new FileDialog(controllerFrame,
						"Datei auswählen", FileDialog.LOAD);
				dataFile.setFile("*.csv");
				dataFile.setVisible(true);
				if (dataFile.getFile() != null) {
					baseFileHelper.baseFile = dataFile.getFile();
					baseFileHelper.basePath = dataFile.getDirectory()
							+ dataFile.getFile();
				}
			}
		});

		Panel controls = new Panel();
		data.setLayout(new GridLayout(3, 1));
		Button serverStart = new Button("Serverstart");
		final Button serverStop = new Button("Serverstop");
		serverStart.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ex) {
				Controller controller = new Controller(Integer.parseInt(port
						.getText()), baseFileHelper.basePath);
				controller.start();

				controllerFrame.dispose();
				Panel info = new Panel();
				info.setLayout(new FlowLayout());
				if (baseFileHelper.baseFile == null) {
					info.add(new Label("Datenbasis: " + defaultBaseFile));
				} else {
					info.add(new Label("Datenbasis: " + baseFileHelper.baseFile));
				}
				controllerFrame.add(info);
				controllerFrame.setVisible(true);
			}
		});
		serverStop.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ex) {
				System.exit(0);
			}
		});

		controls.add(serverStart);
		controls.add(serverStop);

		controllerFrame.add(data);
		controllerFrame.add(controls);
		controllerFrame.setSize(500, 100);
		controllerFrame.setVisible(true);
	}

	/**
	 * Ist für das Update der GUI zuständig, sobald sich die Anzahl der
	 * verbundenen Clients verändert.
	 *
	 * @param c
	 *            Client Anzahl
	 */
	public void updateGUI(int c) {
		controllerFrame.dispose();
		Panel countClients = new Panel();
		countClients.setLayout(new FlowLayout());
		countClients.add(new Label("Connected Clients: " + c));
		controllerFrame.add(countClients);
		controllerFrame.setVisible(true);
	}
}


text:
layout: default
class: about
category: page
published: true
maintitle: "About - {Young}ist"
headline: undefined
tagline: undefined
featuredphoto: undefined
featuredphotoalttext: undefined
videourl: undefined
contributorphoto: undefined
contributorshortbio: undefined
contributortwitter: undefined
contributorage: undefined
---

About Us

{Young}ist is your source for youth-led, fiercely independent political and cultural news, anaylsis, storytelling, and creative intervention by and for Millennials-in-action!

What We Do

{Young}ist was born in response to the scapegoating of our generation in mainstream, corporate media narratives.

As we are burdened with the economic crisis, a broken immigration system, and the rampant violence on young Black, Brown, queer, and transgender youth across the globe - we pursue storytelling not only as a vehicle to spread news, but also as a vital organizing tool to combating oppression. We see youth-led publishing and cross-pollination of ideas and strategies as a political necessity in this digital age.

Our Mission

 Reclaim the mediascape with a youth-powered team responsible and accountable to our political analysis, our peers, and to upcoming generations facing a multitude of oppressions.

 Network and amplify the stories of young people leading transformative projects in their communities

 Foster vibrant conversation between young activists, journalists, and culture creatives by delivering a diversity of content - from cultural analysis and artistic intervention, to political news and movement storytelling.

Statement of Principles

 We spawn change by creating a dynamic online community organized by us and for us.

 We aim to permeate our youth culture by instilling a habit of interrogating and and dismantling systems of power. This is reflected only in practicing a horizontal organizing structure, but also in our content.

 We are accountable to our extended community of artists and organizers, while still maintaining our autonomy.

 We strive in both content and conduct to interrogate and dismantle systems of privilege, power, and oppression in society at large; {Young}ist strives to highlight and amplify the stories and voices of frontline communities left out of prevailing movement narratives.

 We value the privacy of our users, and will allow neither government nor corporations to access user information.

Contact Us

Contact members of our staff with questions pertaining to specific question and concerns regarding content, engagement and design.

Direct submissions to:

Isabelle Nastasia -  isabelle@youngist.org

Editorial board:

Hira Mahmood - hira@youngist.org

Muna Mire - muna@youngist.org

Sara Chatterjee - sarachatterjee@gmail.com

Victor Valle - victor@youngist.org

Queen Arsem-O'Malley -  queen@youngist.org

Board of Advisors:

Cayden Mak - cayden@18millionrising.org

Web development and design:

Maya Richman - info@youngist.com

Commenting Policy

{Young}ist wants to encourage discussion on our Facebook page, and our policy is generally to not delete posts by the Facebook community. However, we may choose to remove posts that are explicitly racist, sexist, or otherwise triggering. Keep it civil, folks.

Attribution

Site source code can be found on Github compiled from Markdown with Jekyll, a static site generator, with style help from front-end framework Bootstrap. Please direct problems with the site to the issues section of our Github.

Speech Bubble by Samuel Q. Green from The Noun Project

Megaphone by Paul Tynes from The Noun Project

Social icons downloaded from ionicons.com


text:
package au.com.codeka.warworlds.game.starfield;

import java.util.Locale;

import org.andengine.entity.Entity;
import org.andengine.entity.primitive.Line;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.opengl.vbo.DrawType;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import au.com.codeka.common.Vector2;
import au.com.codeka.common.model.DesignKind;
import au.com.codeka.common.model.ShipDesign;
import au.com.codeka.warworlds.model.DesignManager;
import au.com.codeka.warworlds.model.Empire;
import au.com.codeka.warworlds.model.EmpireManager;
import au.com.codeka.warworlds.model.EmpireShieldManager;
import au.com.codeka.warworlds.model.Fleet;
import au.com.codeka.warworlds.model.FleetUpgrade;

/** An entity that represents a moving fleet. */
public class FleetEntity extends SelectableEntity {
    private StarfieldSceneManager mStarfield;
    private Vector2 mSrcPoint;
    private Vector2 mDestPoint;
    private Fleet mFleet;
    private FleetSprite mFleetSprite;
    private AnimatedSprite mBoostSprite;

    private Line mSelectionLine;

    public FleetEntity(StarfieldSceneManager starfield, Vector2 srcPoint, Vector2 destPoint, Fleet fleet,
                       VertexBufferObjectManager vertexBufferObjectManager) {
        super(0.0f, 0.0f, 1.0f, 1.0f);
        mStarfield = starfield;
        mSrcPoint = srcPoint;
        mDestPoint = destPoint;
        mFleet = fleet;
        setup(starfield, vertexBufferObjectManager);
    }

    @Override
    public Entity getTouchEntity() {
        return mFleetSprite;
    }

    @Override
    public void onSelected(SelectionIndicatorEntity selectionIndicator) {
        selectionIndicator.setScale(20.0f);

        if (mSelectionLine == null) {
            mSelectionLine = new Line(0.0f, 0.0f, 0.0f, 0.0f,
                    mStarfield.getActivity().getVertexBufferObjectManager());
            mSelectionLine.setColor(0.0f, 1.0f, 0.0f);
            mSelectionLine.setZIndex(-1);
        }

        float x = getX();
        float y = getY();

        mSelectionLine.setPosition((float) mSrcPoint.x - x, (float) mSrcPoint.y - y,
                                   (float) mDestPoint.x - x, (float) mDestPoint.y - y);
        if (mSelectionLine.getParent() != null) {
            detachChild(mSelectionLine);
        }
        attachChild(mSelectionLine);
        sortChildren();
    }

    @Override
    public void onDeselected(SelectionIndicatorEntity selectionIndicator) {
        detachChild(mSelectionLine);
    }

    @Override
    public void dispose() {
        super.dispose();
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            getChildByIndex(i).dispose();
        }
    }

    public Fleet getFleet() {
        return mFleet;
    }

    public void setup(StarfieldSceneManager starfield, VertexBufferObjectManager vertexBufferObjectManager) {
        // work out how far along the fleet has moved so we can draw the icon at the correct
        // spot. Also, we'll draw the name of the empire, number of ships etc.
        ShipDesign design = (ShipDesign) DesignManager.i.getDesign(DesignKind.SHIP, mFleet.getDesignID());
        float timeToDestinationInHours = mFleet.getTimeToDestination();
        float timeFromSourceInHours = mFleet.getTimeFromSource();

        double fractionComplete = timeFromSourceInHours / (timeFromSourceInHours + timeToDestinationInHours);
        if (fractionComplete > 1.0) {
            fractionComplete = 1.0;
        }

        ITextureRegion textureRegion = mStarfield.getSpriteTexture(design.getSpriteName());
        float spriteWidth = textureRegion.getWidth();
        float spriteHeight = textureRegion.getHeight();
        float aspect = spriteWidth / spriteHeight;
        if (spriteWidth > 40.0f) {
            spriteWidth = 40.0f;
            spriteHeight = 40.0f / aspect;
        }
        if (spriteHeight > 40.0f) {
            spriteWidth = 40.0f * aspect;
            spriteHeight = 40.0f;
        }

        Vector2 up = Vector2.pool.borrow().reset(1.0f, 0.0f);
        Vector2 direction = Vector2.pool.borrow().reset(mDestPoint);
        direction.subtract(mSrcPoint);
        direction.normalize();
        float angle = Vector2.angleBetweenCcw(up, direction);
        Vector2.pool.release(direction); direction = null;

        mFleetSprite = new FleetSprite(spriteWidth, spriteHeight, (float)(angle * 180.0f / Math.PI),
                textureRegion, vertexBufferObjectManager);
        attachChild(mFleetSprite);

        FleetUpgrade.BoostFleetUpgrade boostUpgrade = (FleetUpgrade.BoostFleetUpgrade) mFleet.getUpgrade("boost");
        if (boostUpgrade != null && boostUpgrade.isBoosting()) {
            mBoostSprite = new AnimatedSprite(9.0f, -5.0f, 12.0f, 12.0f, (ITiledTextureRegion) mStarfield.getSpriteTexture("ship.upgrade.boost"),
                    vertexBufferObjectManager, DrawType.STATIC);
            mFleetSprite.attachChild(mBoostSprite);
            mBoostSprite.animate(100);
        }

        Vector2 location = getLocation((float) fractionComplete);
/*
        // check if there's any other fleets nearby and offset this one by a bit so that they
        // don't overlap
        Random rand = new Random(mFleet.getKey().hashCode());
        ArrayList<FleetEntity> existingFleets = new ArrayList<FleetEntity>(starfield.getMovingFleets());
        for (int i = 0; i < existingFleets.size(); i++) {
            FleetEntity existingFleet = existingFleets.get(i);
            Vector2 existingPosition = Vector2.pool.borrow().reset(existingFleet.getX(), existingFleet.getY());
            if (existingPosition.distanceTo(location) < 30.0f) {
                // pick a random direction and offset it a bit
                Vector2 offset = Vector2.pool.borrow().reset(0, 40.0);
                offset.rotate(rand.nextFloat() * 2 * (float) Math.PI);
                location.add(offset);
                Vector2.pool.release(offset);
                i = 0;
            }
        }
*/
        setPosition((float) location.x, (float) location.y);
        Vector2.pool.release(location);

        Empire emp = EmpireManager.i.getEmpire(mFleet.getEmpireID());
        if (emp != null) {
            ITextureRegion texture = EmpireShieldManager.i.getShieldTexture(mStarfield.getActivity(), emp);
            Vector2 pt = Vector2.pool.borrow().reset(30.0f, 0.0f);
            if (texture != null) {
                Sprite shieldSprite = new Sprite(
                        (float) pt.x, (float) pt.y,
                        20.0f, 20.0f, texture, mStarfield.getActivity().getVertexBufferObjectManager());
                attachChild(shieldSprite);
            }

            String name;
            if (mFleet.getNumShips() > 1.0f) {
                name = String.format(Locale.ENGLISH, "%d × %s", (int) mFleet.getNumShips(), design.getDisplayName());
            } else {
                name = String.format(Locale.ENGLISH, "%s", design.getDisplayName());
            }
            Text fleetName = new Text((float) pt.x, (float) pt.y, mStarfield.getFont(),
                    name, mStarfield.getActivity().getVertexBufferObjectManager());
            fleetName.setScale(0.666f);
            float offset = ((fleetName.getLineWidthMaximum() * 0.666f) / 2.0f) + 14.0f;
            fleetName.setX(fleetName.getX() + offset);
            attachChild(fleetName);

            Vector2.pool.release(pt); pt = null;
        }
    }

    private Vector2 getLocation(float fractionComplete) {
        // we don't want to start the fleet over the top of the star, so we'll offset it a bit
        double distance = mSrcPoint.distanceTo(mDestPoint) - 40.0f;
        if (distance < 0) {
            distance = 0;
        }

        Vector2 direction = Vector2.pool.borrow().reset(mDestPoint);
        direction.subtract(mSrcPoint);
        direction.normalize();

        Vector2 location = Vector2.pool.borrow().reset(direction);
        location.scale(distance * fractionComplete);
        location.add(mSrcPoint);

        direction.scale(20.0f);
        location.add(direction);

        return location;
    }

    private class FleetSprite extends Sprite {
        public FleetSprite(float width, float height, float rotation, ITextureRegion textureRegion,
                VertexBufferObjectManager vertexBufferObjectManager) {
            super(0.0f, 0.0f, width, height, textureRegion, vertexBufferObjectManager);
            setRotation(rotation);
        }

        @Override
        public boolean onAreaTouched(final TouchEvent sceneTouchEvent,
                                     final float touchAreaLocalX,
                                     final float touchAreaLocalY) {
            StarfieldScene scene = mStarfield.getScene();
            if (sceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN) {
                scene.setSelectingEntity(FleetEntity.this);
            } else if (sceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
                SelectableEntity selectingEntity = scene.getSelectingEntity();
                if (selectingEntity == FleetEntity.this) {
                    scene.selectFleet(FleetEntity.this);
                    return true;
                }
            }
            return false;
        }
    }
}


text:
/*
 * stylesheet.js
 */

const gi = require('../')
const Gtk = gi.require('Gtk', '3.0')
const Gdk = gi.require('Gdk', '3.0')
// gi.require('GdkX11', '3.0') // Required if you're on X11

Gdk.init([])
Gtk.init()

const display = Gdk.Display.getDefault()
const screen = display.getDefaultScreen()
const css = new Gtk.CssProvider()
css.loadFromPath(__dirname + '/style.css')
Gtk.StyleContext.addProviderForScreen(screen, css, 1)


text:
namespace AjBase.Sql
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;

    public class Lexer
    {
        private const string NameCharacters = "_";
        private const string SeparatorCharacters = "(),.";
        private const string OperatorCharacters = "+-*/=";

        private TextReader reader;
        private char lastChar;
        private bool hasChar = false;
        private Stack<Token> tokenStack = new Stack<Token>();

        public Lexer(TextReader reader)
        {
            this.reader = reader;
        }

        public Lexer(string text)
            : this(new StringReader(text))
        {
        }

        public void PushToken(Token token)
        {
            if (token != null)
                this.tokenStack.Push(token);
        }

        public Token NextToken()
        {
            if (this.tokenStack.Count > 0)
                return this.tokenStack.Pop();

            char ch;

            try
            {
                this.SkipBlanks();
                ch = this.NextChar();

                if (ch == '[')
                    return this.NextBracketName();

                if (SeparatorCharacters.IndexOf(ch) >= 0)
                    return new Token() { TokenType = TokenType.Separator, Value = ch.ToString() };

                if (OperatorCharacters.IndexOf(ch) >= 0)
                    return new Token() { TokenType = TokenType.Operator, Value = ch.ToString() };

                if (ch == '\'')
                    return this.NextString();

                if (char.IsDigit(ch) || ch == '-')
                    return this.NextInteger(ch);

                if (char.IsLetter(ch))
                    return this.NextName(ch);

                throw new LexerException(string.Format("Invalid character '{0}'", ch));
            }
            catch (EndOfInputException)
            {
                return null;
            }
        }

        internal char NextChar()
        {
            if (this.hasChar)
            {
                this.hasChar = false;
                return this.lastChar;
            }

            int ch;
            ch = this.reader.Read();

            if (ch < 0)
            {
                throw new EndOfInputException();
            }

            return (char)ch;
        }

        internal void SkipUpToEndOfLine()
        {
            try
            {
                char ch = this.NextChar();

                while (ch != '\n' && ch != '\r')
                    ch = this.NextChar();

                this.PushChar(ch);
            }
            catch (EndOfInputException)
            {
            }
        }

        private Token NextName(char firstChar)
        {
            string name;

            name = firstChar.ToString();

            char ch;

            try
            {
                ch = this.NextChar();

                while (NameCharacters.IndexOf(ch) >= 0 || char.IsLetterOrDigit(ch))
                {
                    name += ch;
                    ch = this.NextChar();
                }

                this.PushChar(ch);
            }
            catch (EndOfInputException)
            {
            }

            Token token = new Token() { TokenType = TokenType.Name, Value = name };

            return token;
        }

        private Token NextBracketName()
        {
            string name = string.Empty;

            char ch;

            try
            {
                ch = this.NextChar();

                while (ch != ']')
                {
                    name += ch;
                    ch = this.NextChar();
                }
            }
            catch (EndOfInputException)
            {
            }

            Token token = new Token() { TokenType = TokenType.Name, Value = name };

            return token;
        }

        private Token NextInteger(char firstChar)
        {
            string integer;

            integer = new string(firstChar, 1);

            char ch;

            try
            {
                ch = this.NextChar();

                while (char.IsDigit(ch))
                {
                    integer += ch;
                    ch = this.NextChar();
                }

                this.PushChar(ch);
            }
            catch (EndOfInputException)
            {
            }

            Token token = new Token() { TokenType = TokenType.Integer, Value = integer };

            return token;
        }

        private Token NextString()
        {
            string text = string.Empty;

            char ch;

            try
            {
                ch = this.NextChar();

                while (ch != '\'')
                {
                    if (ch == '\\')
                        ch = this.NextChar();

                    text += ch;
                    ch = this.NextChar();
                }
            }
            catch (EndOfInputException)
            {
                throw new LexerException("Unclosed string");
            }

            Token token = new Token() { TokenType = TokenType.String, Value = text };

            return token;
        }

        private void PushChar(char ch)
        {
            this.lastChar = ch;
            this.hasChar = true;
        }

        private void SkipBlanks()
        {
            char ch;

            ch = this.NextChar();

            while (char.IsWhiteSpace(ch) || ch == ';')
            {
                if (ch == ';')
                    this.SkipUpToEndOfLine();

                ch = this.NextChar();
            }

            this.PushChar(ch);
        }
    }
}


text:
namespace net {
class SSLSocket;
}  // namespace net

namespace remoting {
namespace protocol {

// Labels for use when exporting the SSL master keys.
extern const char kClientAuthSslExporterLabel[];
extern const char kHostAuthSslExporterLabel[];

// Fake hostname used for SSL connections.
extern const char kSslFakeHostName[];

// Size of the HMAC-SHA-256 hash used as shared secret in SPAKE2.
const size_t kSharedSecretHashLength = 32;

// Size of the HMAC-SHA-256 digest used for channel authentication.
const size_t kAuthDigestLength = 32;

// Returns HMAC-SHA-256 hash for |shared_secret| with the specified |tag|.
std::string GetSharedSecretHash(const std::string& tag,
                                const std::string& shared_secret);

// Returns authentication bytes that must be used for the given
// |socket|. Empty string is returned in case of failure.
std::string GetAuthBytes(net::SSLSocket* socket,
                         const base::StringPiece& label,
                         const base::StringPiece& shared_secret);

}  // namespace protocol
}  // namespace remoting

#endif  // REMOTING_PROTOCOL_AUTH_UTIL_H_


text:
.site-commerce-catalog__search-form {
  margin: 0 0 2em 0;
}

.site-commerce-catalog__categories {
  margin: 2em 0 2em 0;
}

.site-commerce-categories,
.site-commerce-category {
  margin: 0;
  padding: 0;
}

.site-commerce-categories__item {
  margin: 0 0 1em 0;
  padding: 1em;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  border: #F0F0F0 solid 1px;
}

.site-commerce-category__item_root {
  text-align: center;
}

.site-commerce-category-children-image {
  display: inline-block;
  padding-right: 5px;
  vertical-align: middle;
}

.site-commerce-category-title {
  font-size: 1.5em;
}

.site-commerce-category__item_children {
  margin: 1em 0 0 0;
}

.site-commerce-category-children-image {
  display: inline-block;
  padding-right: 5px;
  vertical-align: middle;
}

@media screen and (min-width: 640px) {
  .site-commerce-categories__item {
    float: left;
    max-width: 250px;
    margin-right: 10px;
    min-height: 300px;
  }
}

@media screen and (min-width: 980px) {
  .site-commerce-categories__item {
    width: 25%;
  }

  .site-commerce-category-children-image {
    padding-right: 5px;
    vertical-align: middle;
    float: left;
  }

  .site-commerce-category__item_children {
    margin: 0.5em 0 0 0;
  }
}


text:
<?php

namespace CmsAdmin;

use Cms\App\CmsScopeConfig;
use Cms\App\CmsSkinsetConfig;
use CmsAdmin\Form\ScopeSelectForm;
use Mmi\Security\AuthInterface;
use Mmi\Http\Request;
use Mmi\Mvc\Controller;
use Mmi\Session\SessionInterface;

/**
 * Kontroler główny panelu administracyjnego
 */
class IndexController extends Controller
{
    private const MESSENGER_LOGIN_FAILED = 'messenger.index.login.fail';
    private const MESSENGER_LOGIN_SUCCESS = 'messenger.index.login.success';
    private const MESSENGER_LOGOUT_SUCCESS = 'messenger.index.logout.success';
    private const MESSENGER_PASSWORD_SUCCESS = 'messenger.index.password.success';
    private const MESSENGER_SCOPE_SUCCESS = 'messenger.index.scopeMenu.success';

    /**
     * @Inject
     */
    private AuthInterface $auth;

    /**
     * @Inject
     */
    private SessionInterface $session;

    /**
     * @Inject
     */
    private CmsScopeConfig $scopeConfig;

    /**
     * @Inject
     */
    private CmsSkinsetConfig $skinsetConfig;

    /**
     * @Inject
     */
    private Request $masterRequest;

    /**
     * Strona główna admina
     */
    public function indexAction()
    {
        $this->view->user = (new \Cms\Orm\CmsAuthQuery())->findPk($this->auth->getId());
    }

    /**
     * Logowanie
     */
    public function loginAction(Request $request)
    {
        //jesli zalogowany
        if ($this->auth->hasIdentity()) {
            return $this->getResponse()->redirect('cmsAdmin');
        }
        //formularz logowania
        $form = new \CmsAdmin\Form\Login();
        $this->view->loginForm = $form;
        //brak wysłanych danych
        if (!$form->isMine()) {
            return;
        }
        //logowanie niepoprawne
        if (!$form->isSaved()) {
            $this->getMessenger()->addMessage(self::MESSENGER_LOGIN_FAILED, false);
            return;
        }
        //regeneracja ID sesji
        $this->session->regenerateId();
        //zalogowano
        $this->getMessenger()->addMessage(self::MESSENGER_LOGIN_SUCCESS, true);
        $referer = $request->getReferer();
        //przekierowanie na referer
        if ($referer && $referer != $this->getRequest()->getServer()->requestUri) {
            return $this->getResponse()->redirectToUrl($referer);
        }
        $this->getResponse()->redirect('cmsAdmin');
    }

    /**
     * Akcja wylogowania
     */
    public function logoutAction()
    {
        $this->auth->clearIdentity();
        $this->getMessenger()->addMessage(self::MESSENGER_LOGOUT_SUCCESS, true);
        $this->getResponse()->redirect('cmsAdmin');
    }

    /**
     * Zmiana hasła
     */
    public function passwordAction()
    {
        $form = new \CmsAdmin\Form\Password();
        $this->view->passwordForm = $form;
        //brak wysłanych danych
        if (!$form->isMine()) {
            return;
        }
        //hasło niepoprawne (nowe lub stare)
        if (!$form->isSaved()) {
            return;
        }
        $this->getMessenger()->addMessage(self::MESSENGER_PASSWORD_SUCCESS, true);
        //wylogowanie
        $this->auth->clearIdentity();
        $this->getResponse()->redirect('cmsAdmin');
    }

    public function scopeMenuAction()
    {
        $options = [];
        //opcje
        foreach ($this->skinsetConfig->getSkins() as $skin) {
            $options[$skin->getKey()] = $skin->getName();
        }
        //brak domen
        if (count($options) < 2) {
            return;
        }
        $form = new ScopeSelectForm(null, [ScopeSelectForm::OPTION_SELECTED => $this->scopeConfig->getName(), ScopeSelectForm::OPTION_MULTIOPTIONS => $options]);
        //form do widoku
        $this->view->scopeSelectionForm = $form;
        //obsługa POST
        if ($form->isMine()) {
            $this->scopeConfig->setName($form->getElement('scope')->getValue());
            $this->getMessenger()->addMessage(self::MESSENGER_SCOPE_SUCCESS, true);
            //przekierowanie na referer
            if ($this->masterRequest->getReferer()) {
                return $this->getResponse()->redirectToUrl($this->masterRequest->getReferer());
            }
            return $this->getResponse()->redirect('cmsAdmin');
        }
    }
}


text:
package com.github.mati1979.play.soyplugin.ajax.hash;

import com.github.mati1979.play.soyplugin.ajax.allowedurls.SoyAllowedUrls;
import com.github.mati1979.play.soyplugin.config.SoyViewConf;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import org.apache.commons.io.input.ReaderInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: mszczap
 * Date: 29.06.13
 * Time: 23:58
 *
 * An MD5 algorithm implementation of a hash file generator
 *
 * It is important to notice that this implementation supports a dev and prod modes
 * in dev (hotReloadMode) mode the implementation will not cache md5 hash checksums, conversely
 * in prod mode it will cache it. The cache can be fine tuned via setters.
 */
public class MD5HashFileGenerator implements HashFileGenerator {

    private static final play.Logger.ALogger logger = play.Logger.of(MD5HashFileGenerator.class);

    public final static int DEF_CACHE_MAX_SIZE = 10000;

    public final static String DEF_TIME_UNIT = "DAYS";

    private final static int DEF_EXPIRE_AFTER_WRITE = 1;

    /** maximum number of entries this cache will hold */
    private int cacheMaxSize = DEF_CACHE_MAX_SIZE;

    /** number of time units after which once written entries will expire */
    private int expireAfterWrite = DEF_EXPIRE_AFTER_WRITE;

    /** String used to denote a TimeUnit */
    private String expireAfterWriteUnit = DEF_TIME_UNIT;

    /**friendly*/ Cache<URL, String> cache = CacheBuilder.newBuilder()
            .expireAfterWrite(expireAfterWrite, TimeUnit.valueOf(expireAfterWriteUnit))
            .maximumSize(cacheMaxSize)
            .build();

    private SoyAllowedUrls soyAllowedUrls;

    private SoyViewConf soyViewConf;

    public MD5HashFileGenerator(final SoyAllowedUrls soyAllowedUrls,
                                final SoyViewConf soyViewConf) {
        this.soyAllowedUrls = soyAllowedUrls;
        this.soyViewConf = soyViewConf;
    }

    public void init() {
        cache = CacheBuilder.newBuilder()
                .expireAfterWrite(expireAfterWrite, TimeUnit.valueOf(expireAfterWriteUnit))
                .maximumSize(cacheMaxSize)
                .build();
    }

    /**
     * Calculates a md5 hash for an url
     *
     * If a passed in url is absent then this method will return absent as well
     *
     * @param url - an url to a soy template file
     * @return - md5 checksum of a template file
     * @throws IOException - in a case there is an IO error calculating md5 checksum
     */
    private Optional<String> hashP(final Optional<URL> url) throws IOException {
        if (!url.isPresent()) {
            return Optional.empty();
        }
        logger.debug("Calculating md5 hash, url:{}", url);
        if (!soyViewConf.globalHotReloadMode()) {
            final String md5 = cache.getIfPresent(url.get());

            logger.debug("md5 hash:{}", md5);

            if (md5 != null) {
                return Optional.of(md5);
            }
        }

        final InputStream is = url.get().openStream();
        final String md5 = getMD5Checksum(is);

        if (!soyViewConf.globalHotReloadMode()) {
            logger.debug("caching url:{} with hash:{}", url, md5);

            cache.put(url.get(), md5);
        }

        return Optional.ofNullable(md5);
    }

    @Override
    public Optional<String> hash() throws IOException {
        if (soyAllowedUrls.urls().isEmpty()) {
            logger.warn("Cannot calculate hash, soyAllowedUrls is empty!");
            return Optional.empty();
        }
        if (soyAllowedUrls.urls().size() == 1) {
            final Optional<String> hashOpt = hashP(Optional.of(soyAllowedUrls.resolvedUrls().iterator().next()));
            logger.debug("Returning url hash:" + hashOpt);

            return hashOpt;
        }

        final List<String> hashes = new ArrayList<>();
        for (final URL url : soyAllowedUrls.resolvedUrls()) {
            final Optional<String> hash = hashP(Optional.of(url));
            if (hash.isPresent()) {
                hashes.add(hash.get());
            }
        }

        final StringBuilder builder = new StringBuilder();
        for (final String hash : hashes) {
            builder.append(hash);
        }

        final Optional<String> hashOpt = Optional.ofNullable(getMD5Checksum(new ReaderInputStream(new StringReader(builder.toString()))));
        logger.debug("Returning url hash:" + hashOpt);

        return hashOpt;
    }

    public static String getMD5Checksum(final InputStream is) throws IOException {
        final HashFunction hf = Hashing.md5();

        final HashCode hashCode = hf.hashBytes(getBytesFromInputStream(is));

        return hashCode.toString();
    }

    private static byte[] getBytesFromInputStream(final InputStream inStream) throws IOException {
        // Get the size of the file
        long streamLength = inStream.available();

        if (streamLength > Integer.MAX_VALUE) {
            // File is too large
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) streamLength];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = inStream.read(bytes,
                offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file ");
        }

        // Close the input stream and return bytes
        inStream.close();

        return bytes;
    }

}


text:
using System.Collections;

namespace System.Data
{
    public sealed class DataRowCollection : InternalDataCollectionBase
    {
        private sealed class DataRowTree : RBTree<DataRow>
        {
            internal DataRowTree() : base(TreeAccessMethod.INDEX_ONLY) { }

            protected override int CompareNode(DataRow record1, DataRow record2)
            {
                throw ExceptionBuilder.InternalRBTreeError(RBTreeError.CompareNodeInDataRowTree);
            }
            protected override int CompareSateliteTreeNode(DataRow record1, DataRow record2)
            {
                throw ExceptionBuilder.InternalRBTreeError(RBTreeError.CompareSateliteTreeNodeInDataRowTree);
            }
        }

        private readonly DataTable _table;
        private readonly DataRowTree _list = new DataRowTree();
        internal int _nullInList = 0;

        /// <summary>
        /// Creates the DataRowCollection for the given table.
        /// </summary>
        internal DataRowCollection(DataTable table)
        {
            _table = table;
        }

        public override int Count => _list.Count;

        /// <summary>
        /// Gets the row at the specified index.
        /// </summary>
        public DataRow this[int index] => _list[index];

        /// <summary>
        /// Adds the specified <see cref='System.Data.DataRow'/> to the <see cref='System.Data.DataRowCollection'/> object.
        /// </summary>
        public void Add(DataRow row) => _table.AddRow(row, -1);

        public void InsertAt(DataRow row, int pos)
        {
            if (pos < 0)
            {
                throw ExceptionBuilder.RowInsertOutOfRange(pos);
            }

            if (pos >= _list.Count)
            {
                _table.AddRow(row, -1);
            }
            else
            {
                _table.InsertRow(row, -1, pos);
            }
        }

        internal void DiffInsertAt(DataRow row, int pos)
        {
            if ((pos < 0) || (pos == _list.Count))
            {
                _table.AddRow(row, pos > -1 ? pos + 1 : -1);
                return;
            }

            if (_table.NestedParentRelations.Length > 0)
            { // get in this trouble only if  table has a nested parent
              // get into trouble if table has JUST a nested parent? how about multi parent!
                if (pos < _list.Count)
                {
                    if (_list[pos] != null)
                    {
                        throw ExceptionBuilder.RowInsertTwice(pos, _table.TableName);
                    }
                    _list.RemoveAt(pos);
                    _nullInList--;
                    _table.InsertRow(row, pos + 1, pos);
                }
                else
                {
                    while (pos > _list.Count)
                    {
                        _list.Add(null);
                        _nullInList++;
                    }
                    _table.AddRow(row, pos + 1);
                }
            }
            else
            {
                _table.InsertRow(row, pos + 1, pos > _list.Count ? -1 : pos);
            }
        }

        public int IndexOf(DataRow row) => (null == row) || (row.Table != _table) || ((0 == row.RBTreeNodeId) && (row.RowState == DataRowState.Detached)) ?
            -1 :
            _list.IndexOf(row.RBTreeNodeId, row);

        /// <summary>
        /// Creates a row using specified values and adds it to the <see cref='System.Data.DataRowCollection'/>.
        /// </summary>
        internal DataRow AddWithColumnEvents(params object[] values)
        {
            DataRow row = _table.NewRow(-1);
            row.ItemArray = values;
            _table.AddRow(row, -1);
            return row;
        }

        public DataRow Add(params object[] values)
        {
            int record = _table.NewRecordFromArray(values);
            DataRow row = _table.NewRow(record);
            _table.AddRow(row, -1);
            return row;
        }

        internal void ArrayAdd(DataRow row) => row.RBTreeNodeId = _list.Add(row);

        internal void ArrayInsert(DataRow row, int pos) => row.RBTreeNodeId = _list.Insert(pos, row);

        internal void ArrayClear() => _list.Clear();

        internal void ArrayRemove(DataRow row)
        {
            if (row.RBTreeNodeId == 0)
            {
                throw ExceptionBuilder.InternalRBTreeError(RBTreeError.AttachedNodeWithZerorbTreeNodeId);
            }
            _list.RBDelete(row.RBTreeNodeId);
            row.RBTreeNodeId = 0;
        }

        /// <summary>
        /// Gets the row specified by the primary key value.
        /// </summary>
        public DataRow Find(object key) => _table.FindByPrimaryKey(key);

        /// <summary>
        /// Gets the row containing the specified primary key values.
        /// </summary>
        public DataRow Find(object[] keys) => _table.FindByPrimaryKey(keys);

        /// <summary>
        /// Clears the collection of all rows.
        /// </summary>
        public void Clear() => _table.Clear(false);

        /// <summary>
        /// Gets a value indicating whether the primary key of any row in the
        /// collection contains the specified value.
        /// </summary>
        public bool Contains(object key) => (_table.FindByPrimaryKey(key) != null);

        /// <summary>
        /// Gets a value indicating if the <see cref='System.Data.DataRow'/> with
        /// the specified primary key values exists.
        /// </summary>
        public bool Contains(object[] keys) => (_table.FindByPrimaryKey(keys) != null);

        public override void CopyTo(Array ar, int index) => _list.CopyTo(ar, index);

        public void CopyTo(DataRow[] array, int index) => _list.CopyTo(array, index);

        public override IEnumerator GetEnumerator() => _list.GetEnumerator();

        /// <summary>
        /// Removes the specified <see cref='System.Data.DataRow'/> from the collection.
        /// </summary>
        public void Remove(DataRow row)
        {
            if ((null == row) || (row.Table != _table) || (-1 == row.rowID))
            {
                throw ExceptionBuilder.RowOutOfRange();
            }

            if ((row.RowState != DataRowState.Deleted) && (row.RowState != DataRowState.Detached))
            {
                row.Delete();
            }

            if (row.RowState != DataRowState.Detached)
            {
                row.AcceptChanges();
            }
        }

        /// <summary>
        /// Removes the row with the specified index from the collection.
        /// </summary>
        public void RemoveAt(int index) => Remove(this[index]);
    }
}


text:
package com.sixsq.slipstream.resource;

import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ResourceException;

import com.sixsq.slipstream.util.HtmlUtil;

public abstract class SimpleRepresentationBaseResource extends BaseResource {

	private String message;

	abstract protected String getPageRepresentation();

	protected void setResponse(String content, MediaType mediaType, Status status) {
		getResponse().setEntity(new StringRepresentation(content, mediaType));
		getResponse().setStatus(status);
	}

	protected void setPostResponse(String content, MediaType mediaType) {
		getResponse().setEntity(new StringRepresentation(content, mediaType));
		getResponse().setStatus(Status.SUCCESS_CREATED);
	}

	protected void setPostResponse() {
		getResponse().setEntity(generateHtml(), MediaType.TEXT_HTML);
		getResponse().setStatus(Status.SUCCESS_CREATED);
	}

	protected void handleError(Exception e) {
		e.printStackTrace();
		throw(new ResourceException(Status.SERVER_ERROR_INTERNAL, e));
	}

	protected String generateHtml() {

		return HtmlUtil.toHtml(getMessage(),
				getPageRepresentation(), getUser(), getRequest());

	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}


text:
const tape = require('tape')
const testing = require('ethereumjs-testing')
const rlp = require('ethereumjs-util').rlp
const Block = require('../index.js')

tape('[Block]: block functions', function (t) {
  const testData = require('./testdata.json')

  function testTransactionValidation (st, block) {
    st.equal(block.validateTransactions(), true)

    block.genTxTrie(function () {
      st.equal(block.validateTransactionsTrie(), true)
      st.end()
    })
  }

  t.test('should test transaction validation', function (st) {
    var block = new Block(rlp.decode(testData.blocks[0].rlp))
    st.plan(2)
    testTransactionValidation(st, block)
  })

  t.test('should test transaction validation with empty transaction list', function (st) {
    var block = new Block()
    st.plan(2)
    testTransactionValidation(st, block)
  })

  const testData2 = require('./testdata2.json')
  t.test('should test uncles hash validation', function (st) {
    var block = new Block(rlp.decode(testData2.blocks[2].rlp))
    st.equal(block.validateUnclesHash(), true)
    st.end()
  })

  t.test('should test isGenesis', function (st) {
    var block = new Block()
    st.notEqual(block.isGenesis(), true)
    block.header.number = new Buffer([])
    st.equal(block.isGenesis(), true)
    st.end()
  })

  const testDataGenesis = testing.getSingleFile('BasicTests/genesishashestest.json')
  t.test('should test genesis hashes', function (st) {
    var genesisBlock = new Block()
    genesisBlock.setGenesisParams()
    var rlp = genesisBlock.serialize()
    st.strictEqual(rlp.toString('hex'), testDataGenesis.genesis_rlp_hex, 'rlp hex match')
    st.strictEqual(genesisBlock.hash().toString('hex'), testDataGenesis.genesis_hash, 'genesis hash match')
    st.end()
  })

  t.test('should test toJSON', function (st) {
    var block = new Block(rlp.decode(testData2.blocks[2].rlp))
    st.equal(typeof (block.toJSON()), 'object')
    st.equal(typeof (block.toJSON(true)), 'object')
    st.end()
  })
})