text:
// Some reusable functions that have
// been abstracted from individual days

var global_config = {

    // only works on my domain, throttled.
    GOOGLE_API_KEY: 'AIzaSyAM4K04yxd6F2-M6w8rEm4p97PMN6y2r0w',
    is_mobile: /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()),
    basic_fonts: [
    'Lato',
    'Georgia',
    'Consolas',
    'Verdana',
    'Tahoma',
    'Arial',
    'Helvetica',
    'Lucida Sans',
    'Lucida Console',
    'Lucida',
    'Big Caslon',
    'Book Antiqua',
    'Palatino Linotype',
    'Bodoni MT',
    'Didot',
    'Didot LT STD',
    'Hoefler Text',
    'Garamond',
    'Calisto MT',
    'Bookman Old Style',
    'Bookman',
    'Goudy Old Style',
    'Bitstream Charter',
    'Optima',
    'Segoe',
    'Candara',
    'Geneva',
    'Futura',
    'Trebuchet MS',
    'Franklin Gothic Medium',
    'ITC Franklin Gothic',
    'Gill Sans',
    'Calibri',
    'Baskerville old face',
    'Courier New'
    ]
};

var globalLoader = {
    load_speed: 200,
    load: function(opts) {
        var loader = $('

');
        loader
        .css(opts.css)
        .find('.text').text(opts.msg || 'Loading...');

        $('body')
        .prepend(loader)
        .hide()
        .fadeIn(globalLoader.load_speed);
    },
    unload: function(opts) {
        var delay;
        try {
            delay = opts.delay;
        }
        catch(e) {
            delay = 0;
        }
        setTimeout(function(){
            $('body')
            .find('#global-loader')
            .fadeOut(globalLoader.load_speed, function(){
                $(this).remove();
            });
        }, delay);
    }
};

function successionPlugin(container, advance_speed, callback) {
    // move to plugin format
    // at some point
    var successions = $(container).find('[data-succession]');

    successions
    .hide()
    .each(function(k, succession){
        var _text = $(succession);
        var speed = _text.data('fade-speed');
        var start = _text.data('start');
        var end   = _text.data('stop');

        // set timeout for starting point
        setTimeout(function(){
            _text.fadeIn(speed);
        }, start * advance_speed);

        // set timeout for ending point
        setTimeout(function(){
            _text.fadeOut(speed, function(){
                if(callback) {
                    callback();
                }
            });
        }, end * advance_speed);
    });
    return;
}

/* Math */

function calculateRadialAngle(deg, index, size) {
    // Calculates the positioning for x/y
    // coords along a circle.
    var rad = (Math.PI / 180);
    return [
        Math.sin((deg * index) * rad) * size,
        Math.cos((deg * index) * rad) * size
    ];
}

function sum(arr) {
    var _sum = 0;
    for(var i = 0; i < arr.length; i++) {
        _sum += arr[i];
    }
    return _sum;
}

function findPrime(num) {
    var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23];
    var is_prime = false;
    for(var i = 0, len = primes.length - 1; i <= len; i++) {
        if(primes[i] === num) {
            is_prime = true;
        }
    }
    return is_prime;
}

function distance(pos1, pos2){
    // http://snipplr.com/view/47207/distance-between-two-points/
    var xs = 0;
    var ys = 0;
    xs = pos2.x - pos1.x;
    xs = xs * xs;
    ys = pos2.y - pos1.y;
    ys = ys * ys;
    return Math.sqrt(xs + ys);
}

/* UI / DOM related */

function setActiveFn(els, funcs, el, active_fn) {
    // allows a map of functions to
    // work with a map of DOM elements
    // removing some boilerplate of setting
    // up event handlers and setting/getting the right functions.
    // @els: the DOM elements that need events bound to them.
    // @funcs: the map of functions to reference
    // @el: the scope of the element to call from (e.g: this)
    els.removeClass('active');
    // requires the text to be used as function name
    // so it must match the map key name.
    var fn = el.text();
    el.addClass('active');
    // assign the func
    active_fn = funcs[fn];
    return active_fn;
}

function populateMenu(list, menu, el, use_both) {
    // populates a menu with an array
    // or object, into another dom element
    // also allows you to pass in an el,
    // so it can be used for anything,
    // e.g.
 or <select> or
.
    // @use_both: Boolean - allows both
    // k and v to be added with a colon
    $.each(list, function(k, v) {
        var value = ($.isArray(list) ? v : k);
        var item = $(el);
        value = use_both ? (list[k] + ' ' + value) : value;
        item.html(value);
        menu.append(item);
    });
}

function buttonsWithFuncs(container_el, funcs, set_active_fn, btn_classes) {
    // A vanilla js version of populateMenu and setActiveFn.
    // Easier to user and a mostly better mapper that
    // takes a list of funcs and creates buttons and events.
    // Just give it a container and a list of functions, and voila!
    for(var func in funcs) {
        var btn = document.createElement('a');
        btn.setAttribute('href', '#');
        btn.setAttribute('id', func);
        btn.setAttribute('class', btn_classes || '');
        btn.innerText = func;
        container_el.appendChild(btn);
        // custom function that must be capable
        // of setting the value of a current variable to this functions
        // matching name. Must be in a higher scope.
        btn.onclick = set_active_fn;
    }
}

function addCanvasUI(generate) {
    var export_btn;
    var generate_btn;
    // adds some common reusable
    // elements to the DOM
    // expects the ids to exist;
    // expects a reference to the generating
    // function to be passed in
    try {
        export_btn   = $('#export-btn');
        generate_btn = $('#generate-btn');
        export_btn.on('click', function(){
            exportCanvas(canvas || canvas_elem);
        });
        generate_btn.on('click', generate);
    } catch(e) {
        // ReferenceError
        export_btn   = document.getElementById('export-btn');
        generate_btn = document.getElementById('generate-btn');
        if(export_btn) {
            export_btn.addEventListener('click', function(){
                exportCanvas(canvas || canvas_elem);
            });
        }
        if (generate_btn) {
            generate_btn.addEventListener('click', generate);
        }
    }
}

function newArr(count, mapfn) {
    // Fills an array @count times with return value of @mapfn.
    return Array.apply(null, new Array(count)).map(mapfn);
}

function pad(str, amt, atom) {
    // similar to Python's padding.
    atom = atom || '\u00A0';
    var s = ''
    for(var i = 0 ; i < amt; i++) {
        if(i === amt / 2) {
            s += str;
        } else {
            s += atom;
        }
    }
    return s;
}

function findIn(match, set) {
    for(var i = 0; i < set.length; i++) {
        if(set[i] === match) {
            return true;
        }
    }
    return false;
}

function getLastOf(input) {
    // returns the last char
    // of a given string
    if(typeof input !== 'string') {
        return input;
    }
    return input.substr(input.length - 1, input.length);
}

function simpleLetterSequence(opts) {
    // animate a sequence of letters,
    // allow for transition from one css state
    // to another, which allows for all
    // kinds of possibilities
    // Parameters:
    // @opts.container [DOM element]
        // the container to append items to
    // @opts.word
    // @opts.css_before [Object] initial css state
    // @opts.css_after [Object] final css state
    // @opts.len [Number] indicating length (optional)
    // @opts.fade [Number] fade speed
    // @opts.timing [Number] delay timeout
    // @opts.callback [Function] a callback to execute
    var len = opts.len || (opts.word.length - 1);
    for(var i = 0; i <= len; i++) {
        (function(i){
            setTimeout(function(){
                var letter = opts.word[i];
                var block  = '' + letter + '';
                opts.container
                .append(block)
                .find('span')
                .last()
                .hide()
                .css(opts.css_before)
                .fadeIn(opts.fade, function(){
                    $(this).css(opts.css_after);
                });
            }, i * opts.timing);
        })(i);
    }
    if(opts.callback) {
        // add a callback that
        // finishes after all loops
        setTimeout(opts.callback, len * opts.timing);
    }
    return;
}

function initGoogleFonts() {
    // defters to type library:
    // github.com/christabor/typey
    window.myTypeLibrary = fonTypey({

        // public, limited access only
        // for github.com/christabor
        api_key: global_config.GOOGLE_API_KEY
    });
    myTypeLibrary.initAllFeatures('body');
    return;
}

function disableForMobile() {
    // disable all scripts
    // before they load
    var html = [
    '
Sorry, but this page does not work well in mobile browsers.
',
    '
Please try again with a desktop device. <333
'
    ].join('');

    // add message to dom
    // replace original content
    document
    .querySelector('body')
    .innerHTML = html;
    return;
}

function hasJS() {
    // remove no-js classes for
    // compatibility and enhancement
    $('body').removeClass('no-js');
    return;
}

/********************* Misc. *********************/

function randomArrayValue(arr) {
    return arr[getKey(arr)];
}

function randomObjValue(obj) {
    if(!Object.keys) return;

    // get the random "key" as integer
    var counter = 0;
    var rand    = rando(Object.keys(obj).length);
    var el      = {};
    $.each(obj, function(k, v){
        // see if the current key
        // matches the random integer
        if(counter === rand) {
            el[k] = v;
        }
        counter += 1;
    });
    if(!el) return obj;
    return el;
}

function getKey(arr) {
    // get a random key by the length
    // of a given array
    return Math.floor(Math.random() * arr.length);
}

function rando(max) {
    return Math.floor(Math.random() * max);
}

function randomFixedString(count) {
    // generate a random string
    // of fixed length
    var tokens = 'abcdefghijklmopqrstuvwxyz'.split('');
    var str = '';
    for(var i = 0; i <= count; i++) {
        str += tokens[rando(tokens.length)];
    }
    return str;
}

function randomNumberArray(length, max) {
    var arr = [];
    for(var i = 0; i <= length; i++) {
        arr.push(rando(max || 500));
    }
    return arr;
}

function coordify(x, y) {
    // object from args
    return {'x': x, 'y': y};
}

function randomCoords(max_x, max_y) {
    // returns a single object containing
    // x and y coords
    return {
        x: rando(max_x),
        y: rando(max_y)
    };
}

function convertPxToNum(str) {
    return parseInt(str.replace('px', ''), 10);
}

function randomCSSColorAttr(elem, props, color_max) {
    // only works on color related
    // css properties
    var multiple = $.isArray(props);
    var multi_map = {};

    if(multiple) {
        for (var i = 0, len = props.length; i < len; i++) {
            multi_map[props[i]] = randomColor(color_max);
            elem.css(multi_map);
        }
    } else {
        elem.css(props, randomColor(color_max));
    }
    return;
}

function animatePath(path) {
    // taken from http://jakearchibald.com/2013/animated-line-drawing-svg/
    var length = path.getTotalLength();
    // Clear any previous transition
    path.style.transition = path.style.WebkitTransition = 'none';
    path.style.strokeDasharray = length + ' ' + length;
    path.style.strokeDashoffset = length;
    // Trigger a layout so styles are calculated & the browser
    // picks up the starting position before animating
    path.getBoundingClientRect();
    // Define our transition
    transition = 'stroke-dashoffset 2s ease-in-out';
    path.style.transition = path.style.WebkitTransition = transition;
    path.style.strokeDashoffset = '0';
}

/********************* Fabric.JS *********************/

function randomCommandValues(iterations, max) {
    // generates the numerical
    // values separate of a given command type
    var values = [];
    for (var i = 0; i < iterations; i++) {
        values.push(rando(max));
    }
    return values.join('-');
}

function randomSVGMoveTo(max) {
    // M = absolute, m = relative
    // produces something like:
    // M100,50
    var pathdata = '';
    if(rando(10) > 5) {
        pathdata += 'M';
    } else {
        pathdata += 'm';
    }
    pathdata += rando(max) + ',' + rando(max);
    return pathdata;
}

function randomSVGLineTo(max) {
    // L = absolute, l = relative
    // produces something like:
    // L50,50
    var pathdata = '';
    if(rando(10) > 5) {
        pathdata += 'L';
    } else {
        pathdata += 'l';
    }
    pathdata += rando(max) + ',' + rando(max);
    return pathdata;
}

function randomSVGCurveTo(max) {
    // Q = absolute, q = relative
    // produces something like:
    // Q cx,cy x,y" or "q dcx,dcy, dx, dy"
    var pathdata = '';
    var cx = rando(max);
    var cy = rando(max);
    var x  = rando(max);
    var y  = rando(max);
    if(rando(10) > 5) {
        pathdata += 'Q';
    } else {
        pathdata += 'q';
    }
    pathdata += [cx, cy, x, y].join(',');
    return pathdata;
}

function randomSVGArcTo(max) {
    // A = absolute, a = relative
    // produces something like:
    // A rx,ry xAxisRotate LargeArcFlag, SweepFlag x,y
    var pathdata    = '';
    var rx          = rando(max);
    var ry          = rando(max);
    var axis_rotate = rando(360);
    var x           = rando(max);
    var y           = rando(max);
    var arc_flag    = (rando(10) > 5 ? 1: 0);
    var sweep_flag  = (rando(10) > 5 ? 1: 0);

    if(rando(10) > 5) {
        pathdata += 'A';
    } else {
        pathdata += 'a';
    }
    pathdata += [rx, ry, axis_rotate, arc_flag, sweep_flag, x, y].join(',');
    return pathdata;
}

function randomPrecisePath(max) {
    // Combine all effects
    // in a relatively normal order
    // with more precise formatting than
    // randomPath() produces something like
    // "M73,4,l26,70,q29,22,97,6,a2,42,88,1,0,43,67"
    return [
    randomSVGMoveTo(max),
    randomSVGLineTo(max),
    randomSVGCurveTo(max),
    randomSVGArcTo(max)
    ].join(',');
}

function smartPath(seed) {
    var data = [];
    data.push(randomSVGMoveTo(seed));

    for (var i = 0; i < seed; i++) {
        data.push(randomSVGCurveTo(i));
        data.push(randomSVGLineTo(i));
        data.push(randomSVGArcTo(i));
    }
    data.push(',z');
    return data.join(',');
}

function randomCommandPair(iterations, max) {
    // adds command type and numerical combination
    return randomCommand() + randomCommandValues(iterations, max);
}

function randomCommand() {
    // M = moveto
    // L = lineto
    // H = horizontal lineto
    // V = vertical lineto
    // C = curveto
    // S = smooth curveto
    // Q = quadratic Bézier curve
    // T = smooth quadratic Bézier curveto
    // A = elliptical Arc
    // Z = closepath
    var commands = ['M', 'L', 'H', 'V', 'C', 'S', 'Q', 'T', 'A', 'Z'];

    // adds random the command type
    return randomArrayValue(commands);
}

function randomPath(max, max_size) {
    var paths = [];
    for (var i = 0; i < max; i++) {
        paths.push(randomCommandPair(i, max_size));
    }
    return paths.join('');
}

function randomHTMLInput() {
    var inputs = ['type', 'radio', 'text', 'number', 'date', 'range'];
    return '<input type="' + inputs[rando(inputs.length)] + '">';
}

function randomBinary(max) {
    // generate some random binary of
    // @max size (e.g. 0101010101)
    var str = '';
    for(var i = 0; i <= max; i++) {
        str += rando(10) >= 5 ? '0' : '1';
    }
    return str;
}

function randomAlternatingString(chars, max) {
    // @chars: an array of values
    // @max: number of times to run
    var str = '';
    doSomethingABunch(function(){
        str += randomArrayValue(chars);
    }, max);
    return str;
}

function randomStringLength(max) {
    // Returns a random string using
    // separate method, of random (MAX) characters
    return randomFixedString(rando(max));
}

function randomSentence(word_count, max_length, delimiter) {
    var words = [];
    for(var i = 0; i <= word_count; i++) {
        words.push(randomStringLength(max_length));
    }
    if(!delimiter) {
        delimiter = ' ';
    }
    return words.join(delimiter);
}

function randomColor(max, opacity) {
    // return a random color,
    // in rgba format
    if(isNaN(max)) {
        max = 255;
    }
    return rgbString(rando(max), rando(max), rando(max), opacity);
}

function rgbString(r, g, b, a) {
    r = r || 0;
    g = g || 0;
    b = b || 0;
    if(a) {
        return ['rgba(', r, ',', g, ',', b, ',', clamp(a, 0, 1), ')'].join('');
    } else {
        return ['rgb(', r, ',', g, ',', b, ')'].join('');
    }
}

function randomRGBA(max) {
    return randomColor(max);
}

function randomColorArray(max) {
    // assumed to always be RGB, though since it's
    // random it doesn't matter
    return [rando(max), rando(max), rando(max)];
}

function randomColorHex(is_octal) {
    // Creds: http://www.paulirish.com/2009/random-hex-color-code-snippets/
    var color = Math.floor(Math.random()*16777215).toString(16);

    // added a custom is_octal flag to determine if using
    // octal or not (useful in libraries like THREE.js)
    return is_octal ? '0x'+color : '#'+color;
}

function randomColorObject(max) {
    // return an RGB object
    return {
        r: rando(max),
        g: rando(max),
        b: rando(max)
    };
}

function randomGradientObj(max_stops) {
    var gradients   = [];
    var color_stops = 'bottom, ';
    var step        = '';
    var webkit;
    var o;
    var moz;
    var ms;
    var noprefix;

    // divide each color stop
    // by the max stops and add the color
    for (var i = max_stops; i > 0; i--) {
        if(i === max_stops) {
            // always start at 1%
            step = '1%, ';
        }
        else if(i === 1) {
            // remove trailing
            // comma on last color-step
            step = Math.round(100 / i) + '%';
        } else {
            step = Math.round(100 / i) + '%, ';
        }
        color_stops += randomColorHex() + ' ' + step;
    }
    color_stops += ')';

    // add all color stops and prefixes - ugh
    // pretty ugly, needs reworking
    gradients.push('-webkit-linear-gradient(' + color_stops);
        gradients.push('-ms-linear-gradient(' + color_stops);
            gradients.push('-o-linear-gradient(' + color_stops);
                gradients.push('-moz-linear-gradient(' + color_stops);
                    gradients.push('linear-gradient(' + color_stops);
                        return gradients;
                    }

                    function randomColorScheme(color_count, max) {
    // return an array of random colors @color_count long
    var colors = [];
    for(var i = 0; i <= color_count; i++) {
        colors[i] = randomColor(max);
    }
    return colors;
}

function bootstrapCanvas(callback, is_fabric, canvas_el, opts) {
    // a reusable function for bootstrapping
    // some common canvas inits. Also provides
    // a callback so everything is defined in order.
    window.dims = getViewportDimensions();
    // monkey patch options
    if(!opts) {
        opts = {
            'height': dims.height,
            'width': dims.width
        }
    }
    window.height      = opts.height;
    window.width       = opts.width;
    window.canvas_elem = document.querySelector(canvas_el || 'canvas');
    canvas_elem.width  = width;
    canvas_elem.height = height;
    if(is_fabric) {
        canvas = new fabric.Canvas(canvas_el || 'canvas');
        canvas.selection = false;
    } else {
        window.ctx = canvas_elem.getContext('2d');
    }
    if(callback) {
        callback();
    }
}

function setCanvasSize(canvas, factor) {
    // sets canvas based on existing
    // width or height attributes
    canvas.height = height * factor;
    canvas.width  = width * factor;
}

function clearCanvas(bg) {
    if(!bg) bg = 'white';
    // a simple clearing fn
    // -- assumes a global variable "ctx"
    ctx.fillStyle = bg;
    ctx.fillRect(0, 0, width, height);
}

function getDocumentDimensions() {
    // return a simple dimensions object
    // of the screen width and height
    return {
        'height': window.screen.availHeight,
        'width': window.screen.width
    };
}

function getViewportDimensions() {
    return {
        'height': document.documentElement.clientHeight,
        'width': document.documentElement.clientWidth
    };
}

function exportCanvas(canvas) {
    if(!canvas) return;
    try {
        if(fabric) {
            // remove outlines
            // and select boxes
            canvas.deactivateAll()
            .renderAll();
        }
    } catch(e) {}
    window.open(canvas.toDataURL());
}

function log(msg) {
    return console.log(msg);
}

function uid() {
    return rando(9999);
}

function cssUuid() {
    // appends `id_` to the beginning of random uuids,
    // since css selectors do not work on first numbers
    return 'id_' + uuid(1);
}

function uuid(count, delimiter) {
    // random unique identifier in the form 0000-0000-0000-0000
    var _uuid = [];
    count = count || 4;
    for(var i = 0; i < count; i++) {
        _uuid.push(uid());
    }
    return _uuid.join(delimiter || '-');
}

function makeHTMLTag(el, content) {
    return ['<', el, '>', content, '</', el, '>'].join('');
}

function stretchCanvas(canvas) {
    // makes canvas stretch across whole window size
    $(canvas)
    .height($(window).height())
    .width($(window).width());
    return;
}

function doSomethingABunch(thing, times, context) {
    // generic repeater
    if(times > 0) {
        thing(context);
        doSomethingABunch(thing, times - 1, context);
    }
    return;
}

function multiCopyToString(times, string, delimiter) {
    // copy a string multiple times
    // - similar to Pythons operator overloading
    // e.g. cat * 3 => catcatcat
    var copied = '';
    for(var i = 1; i <= times; i++) {
        copied += string + delimiter;
    }
    return copied;
}

function multiCopyToArray(times, string) {
    // similar to string copy,
    // but sends to array a number of times
    // e.g. fn(10, 'cat') => [cat, cat]
    var copied = [];
    for(var i = 1; i <= times; i++) {
        copied.push(string);
    }
    return copied;
}

function triggerLoading(on) {
    if(on) {
        $('body').css('cursor', 'progress');
    } else {
        $('body').css('cursor', 'auto');
    }
    return;
}

function getLocation(success, error) {
    // set some options to pass in
    var options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
    };

    // check if enabled
    if (navigator.geolocation) {
        coords = navigator
        .geolocation
        .getCurrentPosition(success, error, options);
    }
    else {
        alert('Geolocation is not supported by this browser.');
    }
    return coords;
}

function clamp(number, min, max) {
    return Math.min(Math.max(number, min), max);
}

function show(elem) {
    // more human-readable show
    elem.show();

    // make chainable
    return elem;
}

function hide(elem) {
    // more human-readable hide
    elem.hide();

    // make chainable
    return elem;
}

function arrayToHTMList(arr) {
    // creates a series of lis from an array -
    // parent element is not created.
    var html = '';
    for(var i = 0; i < arr.length; i++) {
        html += '
' + arr[i] + '
';
    }
    return html;
}

function arrayToHTMLOptions(arr) {
    // creates a dropdown form from an array -
    // parent element is not created.
    var html = '';
    for(var i = 0; i < arr.length; i++) {
        html += '<option>' + arr[i] + '</option>';
    }
    return html;
}

function arrayToHTMLCheckboxes(arr) {
    // creates a set of checkboxes form from an array
    var html = '';
    for(var i = 0; i < arr.length; i++) {
        var id = uuid(1) + '-' + i;
        html += strToHTMLCheckBox(arr[i], id, null);
    }
    return html;
}

function strToHTMLCheckBox(str, id, data) {
    // Create a single checkbox with a @param "string"
    // value and id of @param "id"
    // also allows for extra data-* attrs to be passed
    // to the checkbox via @param data.
    var data_attrs = '';
    for(var attr in data) {
        data_attrs += ('data-' + attr + '=' + data[attr]) + ' ';
    }
    return '' +
           '<input type="checkbox" ' +  data_attrs + '>' + str +
           '';
}

function createDTreeFromJSON(data, html, flattened) {
    // generates a decision tree via html,
    // recursively from the *appropriately*
    // formatted JSON data.
    // Required format:
    //   "title": "my title...",
    //   "q": "question 1",
    //   "yes": "if yes...",
    //   "no": {
    //     ... more "yes", "no", "q" objects or strings,
    //         which will be recursively enumerated until no
    //         more objects are found.
    //   }

    if(!html) html = '';
    if(!data.yes && !data.no) return html;
    html += '

' + data.q + '
';
    if(typeof data.yes === 'string'){
        html += '
Yes?

' + data.yes + '

';
    } else {
        html += '
Yes?

';
        return createDTreeFromJSON(data.yes, html);
    }
    if(typeof data.no === 'string'){
        html += '
No?

' + data.no + '

';
    } else {
        html += '
No?

';
        return createDTreeFromJSON(data.no, html);
    }
    html += '
';
    return html;
}

/********************* SHIMS *********************/

function hasGetUserMedia() {
    // http://www.html5rocks.com/en/tutorials/getusermedia/intro/
    return !!(navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia);
}

window.requestAnimFrame = (function(){
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame    ||
    window.oRequestAnimationFrame      ||
    window.msRequestAnimationFrame     ||
    function(/* function */ callback, /* DOMElement */ element){
        window.setTimeout(callback, 1000 / 60);
    };
})();

navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia);

/********************* THREE.js *********************/

function createTween(opts) {
    if(!TWEEN) return;

    // create tweening classes
    var new_tween = new TWEEN.Tween(opts.from)
    .to(opts.to, opts.duration || 1000)
    .easing(opts.easing)
    .onUpdate(opts.onUpdate)
    .onComplete(opts.onComplete);

    // start
    new_tween.start();
    return;
}

function addTHREEStats() {
    if(!Stats) return;

    // construct new stats
    // obj and add to DOM
    // scope is global, so it has
    // a more unique namespace
    three_stats = new Stats();
    three_stats.domElement.style.position = 'absolute';
    three_stats.domElement.style.top = '0px';
    container.appendChild(three_stats.domElement);
    return;
}

/********************* d3.js *********************/

// Dependencies: d3.js

function addTitle(container, title, fixed_size) {
    // creates a scale that will constrain the font size
    // to within the containers dimensions,
    // based on the number of letters in the title.
    var TOP_OFFSET = 10;
    var width = container[0][0].clientWidth;
    var constrainedBoxFontScale = d3.scale.linear()
    .domain([0, title.length]).range([10, clamp((width / title.length) * 1.8, 10, 30)]);
    return container.append('text')
    .attr('x', width / 2)
    .attr('y', function(d){
        return TOP_OFFSET + constrainedBoxFontScale(title.length);
    })
    .attr('class', 'svg-title')
    .attr('font-size', function(d){
        return fixed_size || constrainedBoxFontScale(title.length);
    })
    .attr('text-anchor', 'middle')
    .text(title);
}

function getSVG(id, dims, container) {
    return d3.select(container || '#svg-container')
    .append('svg').attr('id', id)
    .attr('width', dims.w || dims.width)
    .attr('height', dims.h || dims.height)
}

function getCenterTranslation(dims) {
    // returns a boilerplate center translation string
    return 'translate(' + [(dims.w || dims.width) / 2, (dims.h || dims.height) / 2].join(',') + ')';
}

function translation(w, h) {
    // Returns a translation string used in attr('transform');
    return 'translate(' + [w, h].join(',') + ')';
}

function transformMatrix(sx, sy, x, y) {
    // Returns a matrix translation
    // http://stackoverflow.com/questions/6711610/how-to-set-transform-origin-in-svg
    return 'matrix(' + sx + ', 0, 0, ' + sy + ', ' + (x - sx * x) + ', ' + (y - sy * y) + ')';
}

function transformMatrixUniform(scale, x, y) {
    return transformMatrix(scale, scale, x, y);
}

function flattenQuadtree(quadtree) {
    // http://bl.ocks.org/mbostock/4343214
    var nodes = [];
    quadtree.visit(function(node, x1, y1, x2, y2){
        nodes.push({'x': x1, 'y': y1, 'width': x2 - x1, 'height': y2 - y1});
    });
    return nodes;
}


text:
import csv
import sublime
from elasticsearch.helpers import bulk_index
from .base import CreateBaseCommand

def change_doc_index(docs, index):
    for doc in docs:
        doc['_index'] = index
        yield doc

def expand_action(data):
    data = data.copy()
    op_type = data.pop('_op_type', 'index')
    action = {op_type: {}}
    for key in ('_parent', '_percolate', '_routing', '_timestamp',
                '_ttl', '_type', '_version', '_version_type',
                '_id', '_retry_on_conflict'):
        if key in data:
            action[op_type][key] = data.pop(key)

    # no data payload for delete
    if op_type == 'delete':
        return action, None

    return action, data.get('_source', data)

class HelperImportCsvCommand(CreateBaseCommand):
    command_name = "elasticsearch:helper-import-csv"

    def is_enabled(self):
        return True

    def show_input_filename(self, label, default, index, doc_type, callback):
        def on_done(filename):
            callback(index=index, doc_type=doc_type, filename=filename)

        self.window.show_input_panel(label, default, on_done, None, None)

    def save_filename(self, filename):
        self.settings.set("dump_file", filename)
        self.settings.save()

    def run_request(self, index=None, doc_type=None, filename=None):
        if not index:
            self.show_index_list_panel(self.run)
            return

        if not doc_type:
            self.show_doc_type_list_panel(self.run)
            return

        if not filename:
            self.show_input_filename(
                "Open: ", '', index, doc_type, self.run)
            return

        docs = []
        with open(filename, encoding='utf-8', mode='r') as csvfile:
            for doc in csv.DictReader(csvfile, delimiter=','):
                docs.append(doc)
                sublime.status_message("Read: {}".format(len(docs)))

        options = dict(
            index=index,
            doc_type=doc_type,
            stats_only=False,
            chunk_size=self.settings.chunk_size,
            expand_action_callback=expand_action
        )

        success, errors = bulk_index(
            self.client, change_doc_index(docs, index), **options)

        if errors:
            return dict(
                command=self.command_name,
                index=index,
                filename=filename,
                status="ERROR",
                errors=errors
            )

        return dict(
            command=self.command_name,
            index=index,
            doc_type=doc_type,
            filename=filename,
            status="SUCCESS",
            docs=success
        )

redpajama_set_name: RedPajamaGithub


text:
__all__ = ('AuthenticationError', 'TwoFactorError', 'UnexpectedError')

class AuthenticationError(Exception):
    pass

class TwoFactorError(AuthenticationError):
    pass

class UnexpectedError(RuntimeError):
    pass


text:
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2015-2016 Rick Wargo. All Rights Reserved.
//
// Licensed under the MIT License (the "License"). You may not use this file
// except in compliance with the License. A copy of the License is located at
// http://opensource.org/licenses/MIT or in the "LICENSE" file accompanying
// this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
////////////////////////////////////////////////////////////////////////////////

/*jslint node: true */
/*jslint todo: true */
'use strict';

var AlexaSkill = (process.env.SERVER && process.env.SERVER === 'Local') ? require('./invokeLocal') : require('./invokeLambda');

var Config = require('../../config/lambda-config'),
    JSONtemplate = require('../inputs/request.json'),
    requestHelper = {};

function requestJSON(intent) {
    var json = JSON.parse(JSON.stringify(JSONtemplate));

    json.session.application.applicationId = Config.applicationId;
    json.session.application.timestamp = new Date().toISOString();
    json.request.timestamp = new Date().toISOString();
    if (intent) { json.request.intent = intent; }

    return json;
}

function launchJSON() {
    var json = requestJSON();

    json.request.type = 'LaunchRequest';
    json.session.new = true;
    return json;
}

// Generic unit test to see if it handles a bad application Id
requestHelper.badAppId = function () {
    var payload = launchJSON();

    payload.session.application.applicationId = 'amzn1.echo-sdk-ams.app.000000-0000-0000-0000-000000000000';
    return AlexaSkill.invoke(payload);
};

// Generic unit test to see if it handles capturing the text from starting up
requestHelper.launchRequest = function () {
    var payload = launchJSON();

    return AlexaSkill.invoke(payload);
};

requestHelper.intentRequest = function (intent) {
    var payload = requestJSON(intent);

    return AlexaSkill.invoke(payload);
};

module.exports = requestHelper;


text:
<?php

namespace Kazoo\Api\Collection;

use \Iterator;
use \Countable;
use \ArrayAccess;

use \Kazoo\Common\Utils;
use \Kazoo\Common\ChainableInterface;
use \Kazoo\Common\Exception\ReadOnly;
use \Kazoo\Api\AbstractResource;

abstract class AbstractCollection extends AbstractResource implements Iterator, Countable, ArrayAccess
{
    /**
     *
     *
     */
    private $element_wrapper;

    /**
     *
     *
     */
    private $collection;

    /**
     *
     *
     */
    private $keys;

    /**
     *
     *
     */
    private $default_filter = array();

    /**
     *
     *
     */
    public function __construct(ChainableInterface $chain, array $arguments = array()) {
        parent::__construct($chain, $arguments);

        $entity_name = $this->getEntityName();
        $this->setElementWrapper(new ElementWrapper($chain, $entity_name));

        if (count($arguments) > 1) {
            throw new Exception("invalid arguments...");
        }

        if (isset($arguments[0])) {
            $this->setDefaultFilter($arguments[0]);
        }
    }

    /**
     *
     *
     */
    public function __toString() {
        try {
            return $this->toJson();
        } catch (Exception $e) {
            // Because php...
            // Fatal error: Method xxx::__toString() must not throw an exception
            return json_encode(new stdClass);
        }
    }

    /**
     *
     *
     */
    public function __set($name, $value) {
        throw new ReadOnly("Collections are read-only");
    }

    /**
     *
     *
     */
    public function fetch(array $filter = array()) {
        $response = $this->get($this->getFilter($filter));
        $this->setCollection($response->getData());
        $this->rewind();
        return $this;
    }

    /**
     *
     *
     */
    public function rewind() {
        $collection = $this->getCollection();
        $this->keys = array_keys((array)$collection);
    }

    /**
     *
     *
     */
    public function current() {
        $key = $this->key();
        $collection = $this->getCollection();

        if (is_array($collection)) {
            return $this->loadElementWrapper($collection[$key], $key);
        } else if (is_object($collection)) {
            return $this->loadElementWrapper($collection->$key, $key);
        }

        return null;
    }

    /**
     *
     *
     */
    public function key() {
        if (is_null($this->keys)) {
            $this->fetch();
        }

        return current($this->keys);
    }

    /**
     *
     *
     */
    public function next() {
        if (is_null($this->keys)) {
            $this->fetch();
        }

        next($this->keys);
    }

    /**
     *
     *
     */
    public function valid() {
        return $this->key() !== false;
    }

    /**
     *
     *
     */
    public function count() {
        if (is_null($this->keys)) {
            $this->fetch();
        }

        return count($this->keys);
    }

    /**
     *
     *
     */
    public function offsetSet($offset, $value) {
        throw new ReadOnly("Collections are read only");
    }

    /**
     *
     *
     */
    public function offsetExists($offset) {
        return isset($this->keys[$offset]);
    }

    /**
     *
     *
     */
    public function offsetUnset($offset) {
        $collection = $this->getCollection();
        $key = $this->keys[$offset];

        if (is_array($collection)) {
            unset($collection[$key]);
        } else if (is_object($collection)) {
            unset($collection->$key);
        }

        unset($this->keys[$offset]);
    }

    /**
     *
     *
     */
    public function offsetGet($offset) {
        $collection = $this->getCollection();
        $key = $this->keys[$offset];

        if (is_array($collection)) {
            return $this->loadElementWrapper($collection[$key], $key);
        } else if (is_object($collection)) {
            return $this->loadElementWrapper($collection->$key, $key);
        }

        return null;
    }

    /**
     *
     *
     */
    public function toJson() {
        return (string)json_encode($this->getCollection());
    }

    /**
     *
     *
     */
    public function getFilter(array $filter = array()) {
        return array_merge($this->getDefaultFilter(), $filter);
    }

    /**
     *
     *
     */
    public function setDefaultFilter(array $filter = array()) {
        return $this->default_filter = $filter;
    }

    /**
     *
     *
     */
    protected function getDefaultFilter() {
        return $this->default_filter;
    }

    /**
     *
     *
     */
    protected function getUriSnippet() {
        return '/' . Utils::underscoreClassName($this);
    }

    /**
     *
     *
     */
    protected function getEntityName() {
        $className = Utils::shortClassName($this);
        return Utils::depluralize($className);
    }

    /**
     *
     *
     */
    protected function getCollection() {
        if (is_null($this->collection)) {
            $this->fetch();
        }

        return $this->collection;
    }

    /**
     *
     *
     */
    protected function setCollection($collection) {
        $this->collection = $collection;
        $this->rewind();
    }

    /**
     *
     *
     */
    protected function getElementWrapper() {
        return $this->element_wrapper;
    }

    /**
     *
     *
     */
    protected function loadElementWrapper($element, $key) {
        $element_wrapper = $this->getElementWrapper();
        $element_wrapper->setElement($element);
        return $element_wrapper;
    }

    /**
     *
     *
     */
    private function setElementWrapper(ElementWrapper $wrapper) {
        $this->element_wrapper = $wrapper;
    }

    public function remove($append_uri = null) {
        $this->delete(null, $append_uri);
        return $this;
    }
}


text:
require 'pry'

# Used to count occurrances of phrases in text
# Can also be used for simple word count, by giving range of 1
class PhraseCounter
  attr_accessor :phrases

  def initialize(text, options = { min_length: 3 })
    @text_array = text.downcase.split(/\s+/)
    phrase_options(options)
    @phrases = {}

    # Used to keep track of multiple phrase matches in a row, to find longer phrases
    @running_phrases = []

    # Keeps track of component phrases, to be removed after a pass is completed
    @component_phrases = Hash.new(0)
  end

  # Set the options for the phrase counter (e.g. min words per phrase)
  def phrase_options(new_options = nil)
    @options ||= {}
    return @options unless new_options

    # Set phrase length range
    min_length = new_options[:min_length] || new_options[:max_length]
    max_length = new_options[:max_length] || new_options[:min_length]

    @options[:length_range] = (min_length.to_i)..(max_length.to_i)
    @options[:min_length] = min_length.to_i
    @options[:max_length] = max_length.to_i

    # set longer phrase options
    @options[:look_longer] = new_options[:look_longer]
    @options[:hide_longer] = new_options[:hide_longer]

    @options
  end

  def word_count
    @word_count ||= @text_array.count
  end

  # Performs the phrase counting
  def perform
    phrase_options[:length_range].each do |length|
      @phrases[length] ||= Hash.new(0) # Default each phrase to zero occurances
      each_phrase(length) do |phrase|
        running_phrase_check(phrase) if @options[:look_longer] && (length == @options[:max_length])
        @phrases[length][phrase] += 1
      end

      # Check for presence of longer phrases only on last pass
      running_phrase_check('') if @options[:look_longer] && (length == @options[:max_length])
    end

    remove_component_phrases if @options[:hide_longer]
    sort_phrases
  end

  def sort_phrases
    @phrases = Hash[@phrases.sort_by{|length, _| length}]
    @phrases.each do |length, phrases|
      @phrases[length] = Hash[@phrases[length].sort_by{|_, occurances| occurances}.reverse]
    end
  end

  # TODO: Move to another class
  # Keeps a running list of sequentially matching phrases, to find longer phrases than currently being checked for
  def running_phrase_check(phrase)
    # Check if this phrase has been found before
    if @phrases[phrase.word_count][phrase] > 0
      @running_phrases << phrase
    else # Not found, so we are at the end of any longer phrase (if one exists)
      if @running_phrases.count > 1
        # Found more than one matching phrase in a row
        record_longer_phrase
      end
      @running_phrases.clear
    end
  end

  # TODO: Move to another class
  # Compiles component phrases into their complete phrase, and records in result set
  def record_longer_phrase
    compiled_phrase = compile_phrase
    compiled_phrase_length = compiled_phrase.word_count
    @phrases[compiled_phrase_length] ||= Hash.new(0)

    # The first duplicate we find needs to record both occurrances
    # TODO: Clean this up. Absolute mother to read.
    new_occurrances = @phrases[compiled_phrase_length][compiled_phrase] > 0 ? 1 : 2
    @phrases[compiled_phrase_length][compiled_phrase] += new_occurrances
  end

  # Iterates over the text array, and returns each phrase of agument length
  def each_phrase(length, text_array=nil)
    text_array ||= @text_array
    length = length.to_i
    max_index = text_array.length - length
    (0..max_index).each  do |index|
      yield text_array.slice(index, length).join(' ')
    end
  end

  # TODO: Move to another class
  # Compiles phrase components into their complete phrase
  # Returns the compiled phrase
  def compile_phrase
    @running_phrases.inject do |phrase, phrase_part|
      phrase + " #{phrase_part.last_word}"
    end
  end

  def remove_component_phrases
    # Start with the longest phrases
    @phrases = Hash[@phrases.sort_by{|length, _| length}.reverse]

    @phrases.each do |length, phrases|
      return if length == @options[:min_length]
      phrases.each do |phrase, occurrances|
        remove_component_phrase(phrase, occurrances) if occurrances > 1
      end
    end
  end

  def remove_component_phrase(phrase, occurrances)
    # Check all phrases we might have found up to the current phrase length
    (@options[:min_length]..(phrase.word_count - 1)).each do |component_length|
      next unless @phrases[component_length]
      phrase_array = phrase.split(' ')

      each_phrase(component_length, phrase_array) do |component_phrase|
        if @phrases[component_length][component_phrase]
          # p "Removing #{occurrances} occurrances of '#{component_phrase}' from results"
          @phrases[component_length][component_phrase] -= occurrances
          @phrases[component_length].delete(component_phrase) if @phrases[component_length][component_phrase] <= 0
        end
      end
    end
  end
end


text:
<!DOCTYPE html>
<title>Custom Elements: adopt node</title>
<link rel="help" href="https://dom.spec.whatwg.org/#concept-node-adopt">
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="resources/custom-elements-helpers.js"></script>
<body>
<script>
'use strict'

// 3.2 For each inclusiveDescendant in node's shadow-including inclusive descendants that is a custom
// element, enqueue a custom element callback reaction with inclusiveDescendant,
// callback name "adoptedCallback", and an empty argument list.
promise_test((t) => {
  return Promise.all([
    create_window_in_test(t),
    create_window_in_test(t)])
    .then(([w1, w2]) => {
      let invocations = [];
      class X extends w1.HTMLElement {
        adoptedCallback() { invocations.push(['adopted', this, arguments]); }
      }
      w1.customElements.define('a-a', X);
      let a = w1.document.createElement('a-a');
      w2.document.adoptNode(a);
      assert_array_equals_callback_invocations(invocations, [ ['adopted', a, [w1.document, w2.document]] ]);
    });
}, 'adopting a custom element to the different document should enqueue an adoptedCallback reaction');

// 3.3 For each inclusiveDescendant in node's shadow-including inclusive descendants, in
// shadow-including tree order, run the adopting steps with inclusiveDescendant and oldDocument.
promise_test((t) => {
  return Promise.all([
    create_window_in_test(t),
    create_window_in_test(t)])
    .then(([w1, w2]) => {
      w1.document.body.innerHTML = `
      <a-a id="a">
        <p>
          <a-a id="b"></a-a>
          <a-a id="c"></a-a>
        </p>
        <a-a id="d"></a-a>
      </a-a>`;
      let invocations = [];
      class X extends w1.HTMLElement {
        adoptedCallback() { invocations.push(this); }
      }
      w1.customElements.define('a-a', X);
      let a = w1.document.getElementById("a");
      w2.document.adoptNode(a);
      assert_array_equals(['a', 'b', 'c', 'd'], invocations.map((e) => e.id),
                      'four elements should have been removed in doc order');
    });
}, 'shadow-including inclusive descendants should be adopted in shadow-including tree order');
</script>
</body>


text:
using System.Linq;
using System.Reflection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Swashbuckle.AspNetCore.Annotations
{
    public class AnnotationsParameterFilter : IParameterFilter
    {
        public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
        {
            if (context.PropertyInfo != null)
            {
                ApplyPropertyAnnotations(parameter, context.PropertyInfo);
            }
            else if (context.ParameterInfo != null)
            {
                ApplyParamAnnotations(parameter, context.ParameterInfo);
            }
        }

        private void ApplyPropertyAnnotations(OpenApiParameter parameter, PropertyInfo propertyInfo)
        {
            var swaggerParameterAttribute = propertyInfo.GetCustomAttributes<SwaggerParameterAttribute>()
                .FirstOrDefault();

            if (swaggerParameterAttribute != null)
                ApplySwaggerParameterAttribute(parameter, swaggerParameterAttribute);
        }

        private void ApplyParamAnnotations(OpenApiParameter parameter, ParameterInfo parameterInfo)
        {

            var swaggerParameterAttribute = parameterInfo.GetCustomAttributes<SwaggerParameterAttribute>()
                .FirstOrDefault();

            if (swaggerParameterAttribute != null)
                ApplySwaggerParameterAttribute(parameter, swaggerParameterAttribute);
        }

        private void ApplySwaggerParameterAttribute(OpenApiParameter parameter, SwaggerParameterAttribute swaggerParameterAttribute)
        {
            if (swaggerParameterAttribute.Description != null)
                parameter.Description = swaggerParameterAttribute.Description;

            if (swaggerParameterAttribute.RequiredFlag.HasValue)
                parameter.Required = swaggerParameterAttribute.RequiredFlag.Value;
        }
    }
}


text:
const helpers = require('../helpers');

const support = require('../../lib/support');

// == Tests =================================================================

describe('support library', () => {
  describe('toCamelCase()', () => {
    const toCamelCase = support.toCamelCase;

    it('can handle simple terms', () => {
      assert.equal(toCamelCase('test'), 'test');
    });

    it('can handle an underscore', () => {
      assert.equal(toCamelCase('test_term'), 'testTerm');
    });

    it('can handle multiple underscores', () => {
      assert.equal(toCamelCase('test_term_extra'), 'testTermExtra');
    });
  });
});


text:
/**
 * This class is generated by jOOQ
 */
package jdblender.jooq.db.information_schema.tables.records;

import javax.annotation.Generated;

import jdblender.jooq.db.information_schema.tables.ColumnPrivileges;

import org.jooq.Field;
import org.jooq.Record8;
import org.jooq.Row8;
import org.jooq.impl.TableRecordImpl;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.8.5"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class ColumnPrivilegesRecord extends TableRecordImpl<ColumnPrivilegesRecord> implements Record8<String, String, String, String, String, String, String, String> {

    private static final long serialVersionUID = 2123509042;

    /**
     * Setter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.GRANTOR.
     */
    public void setGrantor(String value) {
        set(0, value);
    }

    /**
     * Getter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.GRANTOR.
     */
    public String getGrantor() {
        return (String) get(0);
    }

    /**
     * Setter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.GRANTEE.
     */
    public void setGrantee(String value) {
        set(1, value);
    }

    /**
     * Getter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.GRANTEE.
     */
    public String getGrantee() {
        return (String) get(1);
    }

    /**
     * Setter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.TABLE_CATALOG.
     */
    public void setTableCatalog(String value) {
        set(2, value);
    }

    /**
     * Getter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.TABLE_CATALOG.
     */
    public String getTableCatalog() {
        return (String) get(2);
    }

    /**
     * Setter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.TABLE_SCHEMA.
     */
    public void setTableSchema(String value) {
        set(3, value);
    }

    /**
     * Getter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.TABLE_SCHEMA.
     */
    public String getTableSchema() {
        return (String) get(3);
    }

    /**
     * Setter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.TABLE_NAME.
     */
    public void setTableName(String value) {
        set(4, value);
    }

    /**
     * Getter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.TABLE_NAME.
     */
    public String getTableName() {
        return (String) get(4);
    }

    /**
     * Setter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.COLUMN_NAME.
     */
    public void setColumnName(String value) {
        set(5, value);
    }

    /**
     * Getter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.COLUMN_NAME.
     */
    public String getColumnName() {
        return (String) get(5);
    }

    /**
     * Setter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.PRIVILEGE_TYPE.
     */
    public void setPrivilegeType(String value) {
        set(6, value);
    }

    /**
     * Getter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.PRIVILEGE_TYPE.
     */
    public String getPrivilegeType() {
        return (String) get(6);
    }

    /**
     * Setter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.IS_GRANTABLE.
     */
    public void setIsGrantable(String value) {
        set(7, value);
    }

    /**
     * Getter for INFORMATION_SCHEMA.COLUMN_PRIVILEGES.IS_GRANTABLE.
     */
    public String getIsGrantable() {
        return (String) get(7);
    }

    // -------------------------------------------------------------------------
    // Record8 type implementation
    // -------------------------------------------------------------------------

    /**
     * {@inheritDoc}
     */
    @Override
    public Row8<String, String, String, String, String, String, String, String> fieldsRow() {
        return (Row8) super.fieldsRow();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Row8<String, String, String, String, String, String, String, String> valuesRow() {
        return (Row8) super.valuesRow();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field1() {
        return ColumnPrivileges.COLUMN_PRIVILEGES.GRANTOR;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field2() {
        return ColumnPrivileges.COLUMN_PRIVILEGES.GRANTEE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field3() {
        return ColumnPrivileges.COLUMN_PRIVILEGES.TABLE_CATALOG;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field4() {
        return ColumnPrivileges.COLUMN_PRIVILEGES.TABLE_SCHEMA;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field5() {
        return ColumnPrivileges.COLUMN_PRIVILEGES.TABLE_NAME;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field6() {
        return ColumnPrivileges.COLUMN_PRIVILEGES.COLUMN_NAME;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field7() {
        return ColumnPrivileges.COLUMN_PRIVILEGES.PRIVILEGE_TYPE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field8() {
        return ColumnPrivileges.COLUMN_PRIVILEGES.IS_GRANTABLE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value1() {
        return getGrantor();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value2() {
        return getGrantee();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value3() {
        return getTableCatalog();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value4() {
        return getTableSchema();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value5() {
        return getTableName();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value6() {
        return getColumnName();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value7() {
        return getPrivilegeType();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value8() {
        return getIsGrantable();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ColumnPrivilegesRecord value1(String value) {
        setGrantor(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ColumnPrivilegesRecord value2(String value) {
        setGrantee(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ColumnPrivilegesRecord value3(String value) {
        setTableCatalog(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ColumnPrivilegesRecord value4(String value) {
        setTableSchema(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ColumnPrivilegesRecord value5(String value) {
        setTableName(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ColumnPrivilegesRecord value6(String value) {
        setColumnName(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ColumnPrivilegesRecord value7(String value) {
        setPrivilegeType(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ColumnPrivilegesRecord value8(String value) {
        setIsGrantable(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ColumnPrivilegesRecord values(String value1, String value2, String value3, String value4, String value5, String value6, String value7, String value8) {
        value1(value1);
        value2(value2);
        value3(value3);
        value4(value4);
        value5(value5);
        value6(value6);
        value7(value7);
        value8(value8);
        return this;
    }

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    /**
     * Create a detached ColumnPrivilegesRecord
     */
    public ColumnPrivilegesRecord() {
        super(ColumnPrivileges.COLUMN_PRIVILEGES);
    }

    /**
     * Create a detached, initialised ColumnPrivilegesRecord
     */
    public ColumnPrivilegesRecord(String grantor, String grantee, String tableCatalog, String tableSchema, String tableName, String columnName, String privilegeType, String isGrantable) {
        super(ColumnPrivileges.COLUMN_PRIVILEGES);

        set(0, grantor);
        set(1, grantee);
        set(2, tableCatalog);
        set(3, tableSchema);
        set(4, tableName);
        set(5, columnName);
        set(6, privilegeType);
        set(7, isGrantable);
    }
}


text: Apps Village pages


text:
package io.grpc.testing.integration;

import io.grpc.ChannelImpl;
import io.grpc.testing.TestUtils;
import io.grpc.transport.netty.GrpcSslContexts;
import io.grpc.transport.netty.NettyServerBuilder;
import io.grpc.transport.okhttp.OkHttpChannelBuilder;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.IOException;

/**
 * Integration tests for GRPC over Http2 using the OkHttp framework.
 */
@RunWith(JUnit4.class)
public class Http2OkHttpTest extends AbstractTransportTest {
  private static int serverPort = TestUtils.pickUnusedPort();

  /** Starts the server with HTTPS. */
  @BeforeClass
  public static void startServer() throws Exception {
    try {
      startStaticServer(NettyServerBuilder.forPort(serverPort)
          .sslContext(GrpcSslContexts.forServer(
                  TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key")).build()));
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
  }

  @AfterClass
  public static void stopServer() throws Exception {
    stopStaticServer();
  }

  @Override
  protected ChannelImpl createChannel() {
    OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("127.0.0.1", serverPort)
        .overrideHostForAuthority("foo.test.google.fr");
    try {
      builder.sslSocketFactory(TestUtils.getSslSocketFactoryForCertainCert(
              TestUtils.loadCert("ca.pem")));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return builder.build();
  }
}


text:
package net.ymate.platform.commons;

import net.ymate.platform.commons.annotation.ExportColumn;
import net.ymate.platform.commons.lang.BlurObject;
import net.ymate.platform.commons.util.ClassUtils;
import net.ymate.platform.commons.util.DateTimeUtils;
import net.ymate.platform.commons.util.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.NullArgumentException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;

import java.io.*;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @author 刘镇 (suninformation@163.com) on 2017/12/25 下午2:42
 */
public final class ExcelFileExportHelper {

    private Map<String, Object> data;

    private final Map<String, String> customFieldNames = new HashMap<>();

    private final List<String> excludedFieldNames = new ArrayList<>();

    private final Map<String, IExportDataRender> renders = new HashMap<>();

    private IExportDataProcessor processor;

    public static ExcelFileExportHelper bind() {
        return new ExcelFileExportHelper();
    }

    public static ExcelFileExportHelper bind(Map<String, Object> data) {
        return new ExcelFileExportHelper(data);
    }

    public static ExcelFileExportHelper bind(IExportDataProcessor processor) {
        return new ExcelFileExportHelper(processor);
    }

    private ExcelFileExportHelper() {
        data = new HashMap<>();
    }

    private ExcelFileExportHelper(Map<String, Object> data) {
        if (data == null) {
            throw new NullArgumentException("data");
        }
        this.data = data;
    }

    private ExcelFileExportHelper(IExportDataProcessor processor) {
        if (processor == null) {
            throw new NullArgumentException("processor");
        }
        this.processor = processor;
    }

    public ExcelFileExportHelper excludedFieldNames(String[] fieldNames) {
        if (fieldNames != null && fieldNames.length > 0) {
            excludedFieldNames.addAll(Arrays.asList(fieldNames));
        }
        return this;
    }

    public ExcelFileExportHelper putFieldRender(String fieldName, IExportDataRender render) {
        if (StringUtils.isNotBlank(fieldName) && render != null) {
            renders.put(fieldName, render);
        }
        return this;
    }

    public ExcelFileExportHelper putCustomFieldName(String name, String customFieldName) {
        if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(customFieldName)) {
            customFieldNames.put(name, customFieldName);
        }
        return this;
    }

    public ExcelFileExportHelper putData(String varName, Object data) {
        if (StringUtils.isBlank(varName)) {
            throw new NullArgumentException("varName");
        }
        if (data == null) {
            throw new NullArgumentException("data");
        }
        this.data.put(varName, data);
        return this;
    }

    public File export(Class<?> dataType) throws Exception {
        return export(dataType, false);
    }

    public File export(Class<?> dataType, boolean xssf) throws Exception {
        return export(dataType, null, xssf);
    }

    public File export(Class<?> dataType, String charset) throws Exception {
        return export(dataType, charset, false);
    }

    public File export(Class<?> dataType, String charset, boolean xssf) throws Exception {
        File file = null;
        if (processor != null) {
            List<File> files = new ArrayList<>();
            for (int idx = 1; ; idx++) {
                List<?> processorData = processor.getData(idx);
                if (processorData == null || processorData.isEmpty()) {
                    break;
                }
                files.add(doExport(dataType, idx, processorData, charset, xssf));
            }
            file = toZip(files);
        } else if (!data.isEmpty()) {
            file = doExport(dataType, 1, Collections.singletonList(data), charset, xssf);
        }
        return file;
    }

    private File toZip(List<File> files) throws IOException {
        if (!files.isEmpty()) {
            if (files.size() == 1) {
                return files.get(0);
            }
            return FileUtils.toZip("export_", files.toArray(new File[0]));
        }
        return null;
    }

    private File doExport(Class<?> dataType, int index, List<?> data, String charset, boolean xssf) throws Exception {
        ClassUtils.BeanWrapper<?> beanWrapper = ClassUtils.wrapperClass(dataType);
        if (beanWrapper != null) {
            Collection<Field> fields = beanWrapper.getFields();
            Map<String, ExportColumn> columnsMap = new HashMap<>(fields.size());
            List<String> columnNames = new ArrayList<>();
            fields.stream().filter(field -> !excludedFieldNames.contains(field.getName())).forEachOrdered(field -> {
                ExportColumn exportColumnAnn = field.getAnnotation(ExportColumn.class);
                if (exportColumnAnn != null) {
                    columnsMap.put(field.getName(), exportColumnAnn);
                    if (!exportColumnAnn.excluded()) {
                        if (!exportColumnAnn.render().equals(IExportDataRender.class)) {
                            IExportDataRender dataRender = ClassUtils.impl(exportColumnAnn.render(), IExportDataRender.class);
                            if (dataRender != null) {
                                renders.put(field.getName(), dataRender);
                            }
                        }
                        String colName = StringUtils.defaultIfBlank(exportColumnAnn.value(), field.getName());
                        columnNames.add(customFieldNames.getOrDefault(colName, colName));
                    }
                } else {
                    columnNames.add(customFieldNames.getOrDefault(field.getName(), field.getName()));
                }
            });
            if (xssf) {
                return doExportExcel(columnNames, columnsMap, index, data);
            } else {
                return doExportCsv(columnNames, columnsMap, index, data, charset);
            }
        }
        return null;
    }

    private File doExportExcel(List<String> columnNames, Map<String, ExportColumn> columnsMap, int index, List<?> data) throws Exception {
        try (Workbook workbook = WorkbookFactory.create(true)) {
            Sheet sheet = workbook.createSheet();
            CellStyle cellStyle = workbook.createCellStyle();
            int rowCount = 0;
            Row head = sheet.createRow(rowCount++);
            for (int i = 0; i < columnNames.size(); i++) {
                Cell cell = head.createCell(i);
                cell.setCellValue(columnNames.get(i));
                cell.setCellStyle(cellStyle);
            }
            for (Object item : data) {
                ClassUtils.BeanWrapper<?> objectBeanWrapper = ClassUtils.wrapper(item);
                Row newRow = sheet.createRow(rowCount++);
                int cellCount = 0;
                for (String fieldName : objectBeanWrapper.getFieldNames()) {
                    if (!excludedFieldNames.contains(fieldName)) {
                        String cellValue;
                        try {
                            ExportColumn exportColumnAnn = columnsMap.get(fieldName);
                            if (exportColumnAnn != null && exportColumnAnn.excluded()) {
                                continue;
                            }
                            IExportDataRender dataRender = renders.get(fieldName);
                            if (exportColumnAnn != null && dataRender != null) {
                                String valueStr = dataRender.render(exportColumnAnn, fieldName, objectBeanWrapper.getValue(fieldName));
                                if (StringUtils.isNotBlank(valueStr)) {
                                    cellValue = valueStr;
                                } else {
                                    cellValue = StringUtils.trimToEmpty(BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toStringValue());
                                }
                            } else if (exportColumnAnn != null && exportColumnAnn.dateTime()) {
                                cellValue = DateTimeUtils.formatTime(BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toLongValue(), DateTimeUtils.YYYY_MM_DD_HH_MM_SS);
                            } else if (exportColumnAnn != null && exportColumnAnn.dataRange().length > 0) {
                                cellValue = exportColumnAnn.dataRange()[BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toIntValue()];
                            } else if (exportColumnAnn != null && exportColumnAnn.currency()) {
                                cellValue = MathCalcHelper.bind(BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toStringValue()).scale(2).divide("100").toBlurObject().toStringValue();
                            } else {
                                cellValue = StringUtils.trimToEmpty(BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toStringValue());
                            }
                        } catch (Exception e) {
                            cellValue = StringUtils.trimToEmpty(BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toStringValue());
                        }
                        Cell cell = newRow.createCell(cellCount++);
                        cell.setCellValue(cellValue);
                        cell.setCellStyle(cellStyle);
                    }
                }
            }
            File tempFile = File.createTempFile("export_", "_" + index + ".xlsx");
            tempFile.deleteOnExit();
            try (OutputStream outputStream = new FileOutputStream(tempFile)) {
                workbook.write(outputStream);
            }
            return tempFile;
        }
    }

    private File doExportCsv(List<String> columnNames, Map<String, ExportColumn> columnsMap, int index, List<?> data, String charset) throws Exception {
        ConsoleTableBuilder tableBuilder = ConsoleTableBuilder.create(columnNames.size()).csv();
        if (!columnNames.isEmpty()) {
            columnNames.forEach(tableBuilder.addRow()::addColumn);
        }
        for (Object item : data) {
            ClassUtils.BeanWrapper<?> objectBeanWrapper = ClassUtils.wrapper(item);
            ConsoleTableBuilder.Row newRow = tableBuilder.addRow();
            for (String fieldName : objectBeanWrapper.getFieldNames()) {
                if (!excludedFieldNames.contains(fieldName)) {
                    try {
                        ExportColumn exportColumnAnn = columnsMap.get(fieldName);
                        if (exportColumnAnn != null && exportColumnAnn.excluded()) {
                            continue;
                        }
                        IExportDataRender dataRender = renders.get(fieldName);
                        if (exportColumnAnn != null && dataRender != null) {
                            String valueStr = dataRender.render(exportColumnAnn, fieldName, objectBeanWrapper.getValue(fieldName));
                            if (StringUtils.isNotBlank(valueStr)) {
                                newRow.addColumn(valueStr);
                            } else {
                                newRow.addColumn(StringUtils.trimToEmpty(BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toStringValue()));
                            }
                        } else if (exportColumnAnn != null && exportColumnAnn.dateTime()) {
                            newRow.addColumn(DateTimeUtils.formatTime(BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toLongValue(), DateTimeUtils.YYYY_MM_DD_HH_MM_SS));
                        } else if (exportColumnAnn != null && exportColumnAnn.dataRange().length > 0) {
                            newRow.addColumn(exportColumnAnn.dataRange()[BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toIntValue()]);
                        } else if (exportColumnAnn != null && exportColumnAnn.currency()) {
                            newRow.addColumn(MathCalcHelper.bind(BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toStringValue()).scale(2).divide("100").toBlurObject().toStringValue());
                        } else {
                            newRow.addColumn(StringUtils.trimToEmpty(BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toStringValue()));
                        }
                    } catch (Exception e) {
                        newRow.addColumn(StringUtils.trimToEmpty(BlurObject.bind(objectBeanWrapper.getValue(fieldName)).toStringValue()));
                    }
                }
            }
        }
        File tempFile = File.createTempFile("export_", "_" + index + ".csv");
        tempFile.deleteOnExit();
        try (OutputStream outputStream = new FileOutputStream(tempFile)) {
            IOUtils.write(tableBuilder.toString(), outputStream, StringUtils.defaultIfBlank(charset, "GB2312"));
        }
        return tempFile;
    }

    private File doExport(String tmplFile, int index, Map<String, Object> data) throws Exception {
        try (InputStream resourceAsStream = ExcelFileExportHelper.class.getResourceAsStream(tmplFile + ".xls")) {
            File tempFile = File.createTempFile("export_", "_" + index + ".xls");
            tempFile.deleteOnExit();
            try (OutputStream fileOutputStream = new FileOutputStream(tempFile)) {
                JxlsHelper.getInstance().processTemplate(resourceAsStream, fileOutputStream, new Context(data));
            }
            return tempFile;
        }
    }

    /**
     * @param tmplFile 模板文件名称
     * @return 将导出数据映射到tmplFile指定的Excel文件模板
     * @throws Exception 可能产生的任何异常
     */
    public File export(String tmplFile) throws Exception {
        if (StringUtils.isBlank(tmplFile)) {
            throw new NullArgumentException("tmplFile");
        }
        File file = null;
        if (processor != null) {
            List<File> files = new ArrayList<>();
            for (int idx = 1; ; idx++) {
                List<?> processorData = processor.getData(idx);
                if (processorData == null || processorData.isEmpty()) {
                    break;
                }
                files.add(doExport(tmplFile, idx, Collections.singletonMap("data", processorData)));
            }
            file = toZip(files);
        } else if (!data.isEmpty()) {
            file = doExport(tmplFile, 1, data);
        }
        return file;
    }
}


text:
<?php

namespace Ingewikkeld\Rest\OAuthServerBundle\Form;

use Ingewikkeld\Rest\ResourceBundle\Resource\FormTypeInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Url;

class ClientType extends AbstractType implements FormTypeInterface
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'redirectUris',
                'collection',
                array(
                    'required' => true,
                    'type'     => 'url',
                    'constraints' => new All(
                        array(
                            'constraints' => array(
                                new NotBlank(),
                                new Url()
                            )
                        )
                    )
                )
            )
            ->add(
                'grants',
                'choice',
                array(
                    'required' => false,
                    'choices' => array(
                        'token' => 'token',
                        'authorization_code' => 'authorization_code'
                    ),
                    'multiple' => true
                )
            );
    }

    /**
     * Returns the name of this type.
     *
     * @return string The name of this type
     */
    public function getName()
    {
        return 'client';
    }
}


text:
var canReorderSingle = require('./reorderable').canReorderSingle;
var extractProperties = require('./extract-properties');
var isMergeable = require('./is-mergeable');
var tidyRuleDuplicates = require('./tidy-rule-duplicates');

var Token = require('../../tokenizer/token');

var cloneArray = require('../../utils/clone-array');

var serializeBody = require('../../writer/one-time').body;
var serializeRules = require('../../writer/one-time').rules;

function naturalSorter(a, b) {
  return a > b ? 1 : -1;
}

function cloneAndMergeSelectors(propertyA, propertyB) {
  var cloned = cloneArray(propertyA);
  cloned[5] = cloned[5].concat(propertyB[5]);

  return cloned;
}

function restructure(tokens, context) {
  var options = context.options;
  var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
  var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
  var mergeLimit = options.compatibility.selectors.mergeLimit;
  var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
  var specificityCache = context.cache.specificity;
  var movableTokens = {};
  var movedProperties = [];
  var multiPropertyMoveCache = {};
  var movedToBeDropped = [];
  var maxCombinationsLevel = 2;
  var ID_JOIN_CHARACTER = '%';

  function sendToMultiPropertyMoveCache(position, movedProperty, allFits) {
    for (var i = allFits.length - 1; i >= 0; i--) {
      var fit = allFits[i][0];
      var id = addToCache(movedProperty, fit);

      if (multiPropertyMoveCache[id].length > 1 && processMultiPropertyMove(position, multiPropertyMoveCache[id])) {
        removeAllMatchingFromCache(id);
        break;
      }
    }
  }

  function addToCache(movedProperty, fit) {
    var id = cacheId(fit);
    multiPropertyMoveCache[id] = multiPropertyMoveCache[id] || [];
    multiPropertyMoveCache[id].push([movedProperty, fit]);
    return id;
  }

  function removeAllMatchingFromCache(matchId) {
    var matchSelectors = matchId.split(ID_JOIN_CHARACTER);
    var forRemoval = [];
    var i;

    for (var id in multiPropertyMoveCache) {
      var selectors = id.split(ID_JOIN_CHARACTER);
      for (i = selectors.length - 1; i >= 0; i--) {
        if (matchSelectors.indexOf(selectors[i]) > -1) {
          forRemoval.push(id);
          break;
        }
      }
    }

    for (i = forRemoval.length - 1; i >= 0; i--) {
      delete multiPropertyMoveCache[forRemoval[i]];
    }
  }

  function cacheId(cachedTokens) {
    var id = [];
    for (var i = 0, l = cachedTokens.length; i < l; i++) {
      id.push(serializeRules(cachedTokens[i][1]));
    }
    return id.join(ID_JOIN_CHARACTER);
  }

  function tokensToMerge(sourceTokens) {
    var uniqueTokensWithBody = [];
    var mergeableTokens = [];

    for (var i = sourceTokens.length - 1; i >= 0; i--) {
      if (!isMergeable(serializeRules(sourceTokens[i][1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) {
        continue;
      }

      mergeableTokens.unshift(sourceTokens[i]);
      if (sourceTokens[i][2].length > 0 && uniqueTokensWithBody.indexOf(sourceTokens[i]) == -1)
        uniqueTokensWithBody.push(sourceTokens[i]);
    }

    return uniqueTokensWithBody.length > 1 ?
      mergeableTokens :
      [];
  }

  function shortenIfPossible(position, movedProperty) {
    var name = movedProperty[0];
    var value = movedProperty[1];
    var key = movedProperty[4];
    var valueSize = name.length + value.length + 1;
    var allSelectors = [];
    var qualifiedTokens = [];

    var mergeableTokens = tokensToMerge(movableTokens[key]);
    if (mergeableTokens.length < 2)
      return;

    var allFits = findAllFits(mergeableTokens, valueSize, 1);
    var bestFit = allFits[0];
    if (bestFit[1] > 0)
      return sendToMultiPropertyMoveCache(position, movedProperty, allFits);

    for (var i = bestFit[0].length - 1; i >=0; i--) {
      allSelectors = bestFit[0][i][1].concat(allSelectors);
      qualifiedTokens.unshift(bestFit[0][i]);
    }

    allSelectors = tidyRuleDuplicates(allSelectors);
    dropAsNewTokenAt(position, [movedProperty], allSelectors, qualifiedTokens);
  }

  function fitSorter(fit1, fit2) {
    return fit1[1] > fit2[1] ? 1 : (fit1[1] == fit2[1] ? 0 : -1);
  }

  function findAllFits(mergeableTokens, propertySize, propertiesCount) {
    var combinations = allCombinations(mergeableTokens, propertySize, propertiesCount, maxCombinationsLevel - 1);
    return combinations.sort(fitSorter);
  }

  function allCombinations(tokensVariant, propertySize, propertiesCount, level) {
    var differenceVariants = [[tokensVariant, sizeDifference(tokensVariant, propertySize, propertiesCount)]];
    if (tokensVariant.length > 2 && level > 0) {
      for (var i = tokensVariant.length - 1; i >= 0; i--) {
        var subVariant = Array.prototype.slice.call(tokensVariant, 0);
        subVariant.splice(i, 1);
        differenceVariants = differenceVariants.concat(allCombinations(subVariant, propertySize, propertiesCount, level - 1));
      }
    }

    return differenceVariants;
  }

  function sizeDifference(tokensVariant, propertySize, propertiesCount) {
    var allSelectorsSize = 0;
    for (var i = tokensVariant.length - 1; i >= 0; i--) {
      allSelectorsSize += tokensVariant[i][2].length > propertiesCount ? serializeRules(tokensVariant[i][1]).length : -1;
    }
    return allSelectorsSize - (tokensVariant.length - 1) * propertySize + 1;
  }

  function dropAsNewTokenAt(position, properties, allSelectors, mergeableTokens) {
    var i, j, k, m;
    var allProperties = [];

    for (i = mergeableTokens.length - 1; i >= 0; i--) {
      var mergeableToken = mergeableTokens[i];

      for (j = mergeableToken[2].length - 1; j >= 0; j--) {
        var mergeableProperty = mergeableToken[2][j];

        for (k = 0, m = properties.length; k < m; k++) {
          var property = properties[k];

          var mergeablePropertyName = mergeableProperty[1][1];
          var propertyName = property[0];
          var propertyBody = property[4];
          if (mergeablePropertyName == propertyName && serializeBody([mergeableProperty]) == propertyBody) {
            mergeableToken[2].splice(j, 1);
            break;
          }
        }
      }
    }

    for (i = properties.length - 1; i >= 0; i--) {
      allProperties.unshift(properties[i][3]);
    }

    var newToken = [Token.RULE, allSelectors, allProperties];
    tokens.splice(position, 0, newToken);
  }

  function dropPropertiesAt(position, movedProperty) {
    var key = movedProperty[4];
    var toMove = movableTokens[key];

    if (toMove && toMove.length > 1) {
      if (!shortenMultiMovesIfPossible(position, movedProperty))
        shortenIfPossible(position, movedProperty);
    }
  }

  function shortenMultiMovesIfPossible(position, movedProperty) {
    var candidates = [];
    var propertiesAndMergableTokens = [];
    var key = movedProperty[4];
    var j, k;

    var mergeableTokens = tokensToMerge(movableTokens[key]);
    if (mergeableTokens.length < 2)
      return;

    movableLoop:
    for (var value in movableTokens) {
      var tokensList = movableTokens[value];

      for (j = mergeableTokens.length - 1; j >= 0; j--) {
        if (tokensList.indexOf(mergeableTokens[j]) == -1)
          continue movableLoop;
      }

      candidates.push(value);
    }

    if (candidates.length < 2)
      return false;

    for (j = candidates.length - 1; j >= 0; j--) {
      for (k = movedProperties.length - 1; k >= 0; k--) {
        if (movedProperties[k][4] == candidates[j]) {
          propertiesAndMergableTokens.unshift([movedProperties[k], mergeableTokens]);
          break;
        }
      }
    }

    return processMultiPropertyMove(position, propertiesAndMergableTokens);
  }

  function processMultiPropertyMove(position, propertiesAndMergableTokens) {
    var valueSize = 0;
    var properties = [];
    var property;

    for (var i = propertiesAndMergableTokens.length - 1; i >= 0; i--) {
      property = propertiesAndMergableTokens[i][0];
      var fullValue = property[4];
      valueSize += fullValue.length + (i > 0 ? 1 : 0);

      properties.push(property);
    }

    var mergeableTokens = propertiesAndMergableTokens[0][1];
    var bestFit = findAllFits(mergeableTokens, valueSize, properties.length)[0];
    if (bestFit[1] > 0)
      return false;

    var allSelectors = [];
    var qualifiedTokens = [];
    for (i = bestFit[0].length - 1; i >= 0; i--) {
      allSelectors = bestFit[0][i][1].concat(allSelectors);
      qualifiedTokens.unshift(bestFit[0][i]);
    }

    allSelectors = tidyRuleDuplicates(allSelectors);
    dropAsNewTokenAt(position, properties, allSelectors, qualifiedTokens);

    for (i = properties.length - 1; i >= 0; i--) {
      property = properties[i];
      var index = movedProperties.indexOf(property);

      delete movableTokens[property[4]];

      if (index > -1 && movedToBeDropped.indexOf(index) == -1)
        movedToBeDropped.push(index);
    }

    return true;
  }

  function boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) {
    var propertyName = property[0];
    var movedPropertyName = movedProperty[0];
    if (propertyName != movedPropertyName)
      return false;

    var key = movedProperty[4];
    var toMove = movableTokens[key];
    return toMove && toMove.indexOf(token) > -1;
  }

  for (var i = tokens.length - 1; i >= 0; i--) {
    var token = tokens[i];
    var isRule;
    var j, k, m;
    var samePropertyAt;

    if (token[0] == Token.RULE) {
      isRule = true;
    } else if (token[0] == Token.NESTED_BLOCK) {
      isRule = false;
    } else {
      continue;
    }

    // We cache movedProperties.length as it may change in the loop
    var movedCount = movedProperties.length;

    var properties = extractProperties(token);
    movedToBeDropped = [];

    var unmovableInCurrentToken = [];
    for (j = properties.length - 1; j >= 0; j--) {
      for (k = j - 1; k >= 0; k--) {
        if (!canReorderSingle(properties[j], properties[k], specificityCache)) {
          unmovableInCurrentToken.push(j);
          break;
        }
      }
    }

    for (j = properties.length - 1; j >= 0; j--) {
      var property = properties[j];
      var movedSameProperty = false;

      for (k = 0; k < movedCount; k++) {
        var movedProperty = movedProperties[k];

        if (movedToBeDropped.indexOf(k) == -1 && (!canReorderSingle(property, movedProperty, specificityCache) && !boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) ||
            movableTokens[movedProperty[4]] && movableTokens[movedProperty[4]].length === mergeLimit)) {
          dropPropertiesAt(i + 1, movedProperty);

          if (movedToBeDropped.indexOf(k) == -1) {
            movedToBeDropped.push(k);
            delete movableTokens[movedProperty[4]];
          }
        }

        if (!movedSameProperty) {
          movedSameProperty = property[0] == movedProperty[0] && property[1] == movedProperty[1];

          if (movedSameProperty) {
            samePropertyAt = k;
          }
        }
      }

      if (!isRule || unmovableInCurrentToken.indexOf(j) > -1)
        continue;

      var key = property[4];

      if (movedSameProperty && movedProperties[samePropertyAt][5].length + property[5].length > mergeLimit) {
        dropPropertiesAt(i + 1, movedProperties[samePropertyAt]);
        movedProperties.splice(samePropertyAt, 1);
        movableTokens[key] = [token];
        movedSameProperty = false;
      } else {
        movableTokens[key] = movableTokens[key] || [];
        movableTokens[key].push(token);
      }

      if (movedSameProperty) {
        movedProperties[samePropertyAt] = cloneAndMergeSelectors(movedProperties[samePropertyAt], property);
      } else {
        movedProperties.push(property);
      }
    }

    movedToBeDropped = movedToBeDropped.sort(naturalSorter);
    for (j = 0, m = movedToBeDropped.length; j < m; j++) {
      var dropAt = movedToBeDropped[j] - j;
      movedProperties.splice(dropAt, 1);
    }
  }

  var position = tokens[0] && tokens[0][0] == Token.AT_RULE && tokens[0][1].indexOf('@charset') === 0 ? 1 : 0;
  for (; position < tokens.length - 1; position++) {
    var isImportRule = tokens[position][0] === Token.AT_RULE && tokens[position][1].indexOf('@import') === 0;
    var isComment = tokens[position][0] === Token.COMMENT;
    if (!(isImportRule || isComment))
      break;
  }

  for (i = 0; i < movedProperties.length; i++) {
    dropPropertiesAt(position, movedProperties[i]);
  }
}

module.exports = restructure;


text:
package net.greghaines.jesque;

import org.junit.Assert;
import org.junit.Test;

public class TestConfig {

    @Test(expected = IllegalArgumentException.class)
    public void testConstructor_NullHost() {
        new Config(null, 0, -1, null, null, -1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructor_EmptyHost() {
        new Config("", 0, -1, null, null, -1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructor_LowPort() {
        new Config("foo", 0, -1, null, null, -1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructor_HighPort() {
        new Config("foo", Integer.MAX_VALUE, -1, null, null, -1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructor_NegativeTimeout() {
        new Config("foo", 123, -1, null, null, -1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructor_NullNamespace() {
        new Config("foo", 123, 0, null, null, -1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructor_EmptyNamespace() {
        new Config("foo", 123, 0, null, "", -1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructor_NegativeDatabase() {
        new Config("foo", 123, 0, null, "bar", -1);
    }

    @Test
    public void testConstructorAndGetters() {
        final Config config = new Config("foo", 123, 456, "secret", "bar", 10);
        Assert.assertEquals("foo", config.getHost());
        Assert.assertEquals(123, config.getPort());
        Assert.assertEquals(456, config.getTimeout());
        Assert.assertEquals("secret", config.getPassword());
        Assert.assertEquals("bar", config.getNamespace());
        Assert.assertEquals(10, config.getDatabase());
        Assert.assertEquals("foo", config.getHost());
        Assert.assertEquals("redis://foo:123/10", config.getURI());
        Assert.assertNotNull(config.toString());
        Assert.assertTrue(config.equals(config));
    }
}


text:
/*
 *	robot - Hardware abstraction Layer
 *  @date 	12/06/2010
 *  @author robot
 */

#ifdef __USE_CMSIS
#include "system_LPC13xx.h"
#endif

#include "LPC13xx.h"
#include "led.h"
#include "sensor.h"
#include "encoder.h"
#include "motor.h"
#include "pushbutton.h"
#include "FreeRTOS.h"
#include "task.h"
#include "uart.h"

// void HAL_delay_ms(uint16_t delay) {
// 	portTickType delay_ticks = delay / portTICK_RATE_MS;
//     vTaskDelay(delay_ticks);
// }

// void HAL_delay_ticks(portTickType delay_ticks) {
//     vTaskDelay(delay_ticks);
// }

/**
 * Initialize robot hardware
 */
void HAL_init(void) {

  // Initialize leds
  led_init();

  // Initialize sensors
  sensor_init();

  // Initialize encoders
  encoder_init();

  // Initialize motors
  motor_init();

  // Initialize delay module
  //delay_init();

  // Initialize pushbutton
  pushbutton_init();

  // Initialize uart
  UARTInit(57600);
}

/**
 * Put the device into sleep mode
 * Sleep mode is exited automatically when an interrupt arrives at the processor
 */
/*
void HAL_enter_sleep_mode()
{
	LPC_SYSCON->PDAWAKECFG = LPC_SYSCON->PDRUNCFG;
	__ASM volatile ("WFI");
	return;
}
*/


text:
require 'spec_helper'

describe Puppet::Type.type(:dsc_webdeploy) do

  let :dsc_webdeploy do
    Puppet::Type.type(:dsc_webdeploy).new(
      :name     => 'foo',
      :dsc_packagepath => 'foo',
      :dsc_contentpath => 'foo',
    )
  end

  it "should stringify normally" do
    expect(dsc_webdeploy.to_s).to eq("Dsc_webdeploy[foo]")
  end

  it 'should default to ensure => present' do
    expect(dsc_webdeploy[:ensure]).to eq :present
  end

  it 'should require that dsc_packagepath is specified' do
    #dsc_webdeploy[:dsc_packagepath]
    expect { Puppet::Type.type(:dsc_webdeploy).new(
      :name     => 'foo',
      :dsc_contentpath => 'foo',
      :dsc_ensure => 'Present',
    )}.to raise_error(Puppet::Error, /dsc_packagepath is a required attribute/)
  end

  it 'should not accept array for dsc_packagepath' do
    expect{dsc_webdeploy[:dsc_packagepath] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_packagepath' do
    expect{dsc_webdeploy[:dsc_packagepath] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_packagepath' do
    expect{dsc_webdeploy[:dsc_packagepath] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_packagepath' do
    expect{dsc_webdeploy[:dsc_packagepath] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should require that dsc_contentpath is specified' do
    #dsc_webdeploy[:dsc_contentpath]
    expect { Puppet::Type.type(:dsc_webdeploy).new(
      :name     => 'foo',
      :dsc_packagepath => 'foo',
      :dsc_ensure => 'Present',
    )}.to raise_error(Puppet::Error, /dsc_contentpath is a required attribute/)
  end

  it 'should not accept array for dsc_contentpath' do
    expect{dsc_webdeploy[:dsc_contentpath] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_contentpath' do
    expect{dsc_webdeploy[:dsc_contentpath] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_contentpath' do
    expect{dsc_webdeploy[:dsc_contentpath] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_contentpath' do
    expect{dsc_webdeploy[:dsc_contentpath] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept dsc_ensure predefined value Present' do
    dsc_webdeploy[:dsc_ensure] = 'Present'
    expect(dsc_webdeploy[:dsc_ensure]).to eq('Present')
  end

  it 'should accept dsc_ensure predefined value present' do
    dsc_webdeploy[:dsc_ensure] = 'present'
    expect(dsc_webdeploy[:dsc_ensure]).to eq('present')
  end

  it 'should accept dsc_ensure predefined value present and update ensure with this value (ensure end value should be a symbol)' do
    dsc_webdeploy[:dsc_ensure] = 'present'
    expect(dsc_webdeploy[:ensure]).to eq(dsc_webdeploy[:dsc_ensure].downcase.to_sym)
  end

  it 'should accept dsc_ensure predefined value Absent' do
    dsc_webdeploy[:dsc_ensure] = 'Absent'
    expect(dsc_webdeploy[:dsc_ensure]).to eq('Absent')
  end

  it 'should accept dsc_ensure predefined value absent' do
    dsc_webdeploy[:dsc_ensure] = 'absent'
    expect(dsc_webdeploy[:dsc_ensure]).to eq('absent')
  end

  it 'should accept dsc_ensure predefined value absent and update ensure with this value (ensure end value should be a symbol)' do
    dsc_webdeploy[:dsc_ensure] = 'absent'
    expect(dsc_webdeploy[:ensure]).to eq(dsc_webdeploy[:dsc_ensure].downcase.to_sym)
  end

  it 'should not accept values not equal to predefined values' do
    expect{dsc_webdeploy[:dsc_ensure] = 'invalid value'}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_ensure' do
    expect{dsc_webdeploy[:dsc_ensure] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_ensure' do
    expect{dsc_webdeploy[:dsc_ensure] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_ensure' do
    expect{dsc_webdeploy[:dsc_ensure] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_ensure' do
    expect{dsc_webdeploy[:dsc_ensure] = 16}.to raise_error(Puppet::ResourceError)
  end

  # Configuration PROVIDER TESTS

  describe "powershell provider tests" do

    it "should successfully instanciate the provider" do
      described_class.provider(:powershell).new(dsc_webdeploy)
    end

    before(:each) do
      @provider = described_class.provider(:powershell).new(dsc_webdeploy)
    end

    describe "when dscmeta_import_resource is true (default) and dscmeta_module_name existing/is defined " do

      it "should compute powershell dsc test script with Invoke-DscResource" do
        expect(@provider.ps_script_content('test')).to match(/Invoke-DscResource/)
      end

      it "should compute powershell dsc test script with method Test" do
        expect(@provider.ps_script_content('test')).to match(/Method\s+=\s*'test'/)
      end

      it "should compute powershell dsc set script with Invoke-DscResource" do
        expect(@provider.ps_script_content('set')).to match(/Invoke-DscResource/)
      end

      it "should compute powershell dsc test script with method Set" do
        expect(@provider.ps_script_content('set')).to match(/Method\s+=\s*'set'/)
      end

    end

    describe "when dsc_ensure is 'present'" do

      before(:each) do
        dsc_webdeploy.original_parameters[:dsc_ensure] = 'present'
        dsc_webdeploy[:dsc_ensure] = 'present'
        @provider = described_class.provider(:powershell).new(dsc_webdeploy)
      end

      it "should update :ensure to :present" do
        expect(dsc_webdeploy[:ensure]).to eq(:present)
      end

      it "should compute powershell dsc test script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/)
      end

      it "should compute powershell dsc set script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('set')).to match(/ensure = 'present'/)
      end

    end

    describe "when dsc_ensure is 'absent'" do

      before(:each) do
        dsc_webdeploy.original_parameters[:dsc_ensure] = 'absent'
        dsc_webdeploy[:dsc_ensure] = 'absent'
        @provider = described_class.provider(:powershell).new(dsc_webdeploy)
      end

      it "should update :ensure to :absent" do
        expect(dsc_webdeploy[:ensure]).to eq(:absent)
      end

      it "should compute powershell dsc test script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/)
      end

      it "should compute powershell dsc set script in which ensure value is 'absent'" do
        expect(@provider.ps_script_content('set')).to match(/ensure = 'absent'/)
      end

    end

  end
end


text:
var config = require('../config.js');

module.exports = {
    getUrl(route) {
        return `https://${config.host}${config.basePath}${route}`;
    },
};