text:
<?php

/* WebProfilerBundle:Profiler:base_js.html.twig */
class __TwigTemplate_ec09b60151bf759d32e79290ce953910626715c888e0ae6110567a3afe48dec2 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_65623515d1f14684ff164270d3a152dd6924bec7a54dc8d9f0f4294ecce37d26 = $this->env->getExtension("native_profiler");
        $__internal_65623515d1f14684ff164270d3a152dd6924bec7a54dc8d9f0f4294ecce37d26->enter($__internal_65623515d1f14684ff164270d3a152dd6924bec7a54dc8d9f0f4294ecce37d26_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "WebProfilerBundle:Profiler:base_js.html.twig"));

        // line 1
        echo "<script>/*<![CDATA[*/
    ";
        // line 5
        echo "
    Sfjs = (function() {
        \"use strict\";

        var classListIsSupported = 'classList' in document.documentElement;

        if (classListIsSupported) {
            var hasClass = function (el, cssClass) { return el.classList.contains(cssClass); };
            var removeClass = function(el, cssClass) { el.classList.remove(cssClass); };
            var addClass = function(el, cssClass) { el.classList.add(cssClass); };
            var toggleClass = function(el, cssClass) { el.classList.toggle(cssClass); };
        } else {
            var hasClass = function (el, cssClass) { return el.className.match(new RegExp('\\\\b' + cssClass + '\\\\b')); };
            var removeClass = function(el, cssClass) { el.className = el.className.replace(new RegExp('\\\\b' + cssClass + '\\\\b'), ' '); };
            var addClass = function(el, cssClass) { if (!hasClass(el, cssClass)) { el.className += \" \" + cssClass; } };
            var toggleClass = function(el, cssClass) { hasClass(el, cssClass) ? removeClass(el, cssClass) : addClass(el, cssClass); };
        }

        var noop = function() {},

            collectionToArray = function (collection) {
                var length = collection.length || 0,
                    results = new Array(length);

                while (length--) {
                    results[length] = collection[length];
                }

                return results;
            },

            profilerStorageKey = 'sf2/profiler/',

            request = function(url, onSuccess, onError, payload, options) {
                var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
                options = options || {};
                options.maxTries = options.maxTries || 0;
                xhr.open(options.method || 'GET', url, true);
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                xhr.onreadystatechange = function(state) {
                    if (4 !== xhr.readyState) {
                        return null;
                    }

                    if (xhr.status == 404 && options.maxTries > 1) {
                        setTimeout(function(){
                            options.maxTries--;
                            request(url, onSuccess, onError, payload, options);
                        }, 500);

                        return null;
                    }

                    if (200 === xhr.status) {
                        (onSuccess || noop)(xhr);
                    } else {
                        (onError || noop)(xhr);
                    }
                };
                xhr.send(payload || '');
            },

            getPreference = function(name) {
                if (!window.localStorage) {
                    return null;
                }

                return localStorage.getItem(profilerStorageKey + name);
            },

            setPreference = function(name, value) {
                if (!window.localStorage) {
                    return null;
                }

                localStorage.setItem(profilerStorageKey + name, value);
            },

            requestStack = [],

            renderAjaxRequests = function() {
                var requestCounter = document.querySelectorAll('.sf-toolbar-ajax-requests');
                if (!requestCounter.length) {
                    return;
                }

                var ajaxToolbarPanel = document.querySelector('.sf-toolbar-block-ajax');
                var tbodies = document.querySelectorAll('.sf-toolbar-ajax-request-list');
                var state = 'ok';
                if (tbodies.length) {
                    var tbody = tbodies[0];

                    var rows = document.createDocumentFragment();

                    if (requestStack.length) {
                        for (var i = 0; i < requestStack.length; i++) {
                            var request = requestStack[i];

                            var row = document.createElement('tr');
                            rows.insertBefore(row, rows.firstChild);

                            var methodCell = document.createElement('td');
                            if (request.error) {
                                methodCell.className = 'sf-ajax-request-error';
                            }
                            methodCell.textContent = request.method;
                            row.appendChild(methodCell);

                            var pathCell = document.createElement('td');
                            pathCell.className = 'sf-ajax-request-url';
                            if ('GET' === request.method) {
                                var pathLink = document.createElement('a');
                                pathLink.setAttribute('href', request.url);
                                pathLink.textContent = request.url;
                                pathCell.appendChild(pathLink);
                            } else {
                                pathCell.textContent = request.url;
                            }
                            pathCell.setAttribute('title', request.url);
                            row.appendChild(pathCell);

                            var durationCell = document.createElement('td');
                            durationCell.className = 'sf-ajax-request-duration';

                            if (request.duration) {
                                durationCell.textContent = request.duration + \"ms\";
                            } else {
                                durationCell.textContent = '-';
                            }
                            row.appendChild(durationCell);

                            row.appendChild(document.createTextNode(' '));
                            var profilerCell = document.createElement('td');

                            if (request.profilerUrl) {
                                var profilerLink = document.createElement('a');
                                profilerLink.setAttribute('href', request.profilerUrl);
                                profilerLink.textContent = request.profile;
                                profilerCell.appendChild(profilerLink);
                            } else {
                                profilerCell.textContent = 'n/a';
                            }

                            row.appendChild(profilerCell);

                            var requestState = 'ok';
                            if (request.error) {
                                requestState = 'error';
                                if (state != \"loading\" && i > requestStack.length - 4) {
                                    state = 'error';
                                }
                            } else if (request.loading) {
                                requestState = 'loading';
                                state = 'loading';
                            }
                            row.className = 'sf-ajax-request sf-ajax-request-' + requestState;
                        }

                        var infoSpan = document.querySelectorAll(\".sf-toolbar-ajax-info\")[0];
                        var children = collectionToArray(tbody.children);
                        for (var i = 0; i < children.length; i++) {
                            tbody.removeChild(children[i]);
                        }
                        tbody.appendChild(rows);

                        if (infoSpan) {
                            var text = requestStack.length + ' AJAX request' + (requestStack.length > 1 ? 's' : '');
                            infoSpan.textContent = text;
                        }

                        ajaxToolbarPanel.style.display = 'block';
                    } else {
                        ajaxToolbarPanel.style.display = 'none';
                    }
                }

                requestCounter[0].textContent = requestStack.length;

                var className = 'sf-toolbar-ajax-requests sf-toolbar-value';
                requestCounter[0].className = className;

                if (state == 'ok') {
                    Sfjs.removeClass(ajaxToolbarPanel, 'sf-ajax-request-loading');
                    Sfjs.removeClass(ajaxToolbarPanel, 'sf-toolbar-status-red');
                } else if (state == 'error') {
                    Sfjs.addClass(ajaxToolbarPanel, 'sf-toolbar-status-red');
                    Sfjs.removeClass(ajaxToolbarPanel, 'sf-ajax-request-loading');
                } else {
                    Sfjs.addClass(ajaxToolbarPanel, 'sf-ajax-request-loading');
                }
            };

        var addEventListener;

        var el = document.createElement('div');
        if (!'addEventListener' in el) {
            addEventListener = function (element, eventName, callback) {
                element.attachEvent('on' + eventName, callback);
            };
        } else {
            addEventListener = function (element, eventName, callback) {
                element.addEventListener(eventName, callback, false);
            };
        }

        ";
        // line 210
        if (array_key_exists("excluded_ajax_paths", $context)) {
            // line 211
            echo "            if (window.XMLHttpRequest && XMLHttpRequest.prototype.addEventListener) {
                var proxied = XMLHttpRequest.prototype.open;

                XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
                    var self = this;

                    /* prevent logging AJAX calls to static and inline files, like templates */
                    var path = url;
                    if (url.substr(0, 1) === '/') {
                        if (0 === url.indexOf('";
            // line 220
            echo twig_escape_filter($this->env, twig_escape_filter($this->env, $this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "basePath", array()), "js"), "html", null, true);
            echo "')) {
                            path = url.substr(";
            // line 221
            echo twig_escape_filter($this->env, twig_length_filter($this->env, $this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "basePath", array())), "html", null, true);
            echo ");
                        }
                    }
                    else if (0 === url.indexOf('";
            // line 224
            echo twig_escape_filter($this->env, twig_escape_filter($this->env, ($this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "schemeAndHttpHost", array()) . $this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "basePath", array())), "js"), "html", null, true);
            echo "')) {
                        path = url.substr(";
            // line 225
            echo twig_escape_filter($this->env, twig_length_filter($this->env, ($this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "schemeAndHttpHost", array()) . $this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "basePath", array()))), "html", null, true);
            echo ");
                    }

                    if (!path.match(new RegExp(";
            // line 228
            echo twig_jsonencode_filter((isset($context["excluded_ajax_paths"]) ? $context["excluded_ajax_paths"] : $this->getContext($context, "excluded_ajax_paths")));
            echo "))) {
                        var stackElement = {
                            loading: true,
                            error: false,
                            url: url,
                            method: method,
                            start: new Date()
                        };

                        requestStack.push(stackElement);

                        this.addEventListener('readystatechange', function() {
                            if (self.readyState == 4) {
                                stackElement.duration = new Date() - stackElement.start;
                                stackElement.loading = false;
                                stackElement.error = self.status < 200 || self.status >= 400;
                                stackElement.profile = self.getResponseHeader(\"X-Debug-Token\");
                                stackElement.profilerUrl = self.getResponseHeader(\"X-Debug-Token-Link\");

                                Sfjs.renderAjaxRequests();
                            }
                        }, false);

                        Sfjs.renderAjaxRequests();
                    }

                    proxied.apply(this, Array.prototype.slice.call(arguments));
                };
            }
        ";
        }
        // line 258
        echo "
        return {
            hasClass: hasClass,

            removeClass: removeClass,

            addClass: addClass,

            toggleClass: toggleClass,

            getPreference: getPreference,

            setPreference: setPreference,

            addEventListener: addEventListener,

            request: request,

            renderAjaxRequests: renderAjaxRequests,

            load: function(selector, url, onSuccess, onError, options) {
                var el = document.getElementById(selector);

                if (el && el.getAttribute('data-sfurl') !== url) {
                    request(
                        url,
                        function(xhr) {
                            el.innerHTML = xhr.responseText;
                            el.setAttribute('data-sfurl', url);
                            removeClass(el, 'loading');
                            (onSuccess || noop)(xhr, el);
                        },
                        function(xhr) { (onError || noop)(xhr, el); },
                        '',
                        options
                    );
                }

                return this;
            },

            toggle: function(selector, elOn, elOff) {
                var tmp = elOn.style.display,
                    el = document.getElementById(selector);

                elOn.style.display = elOff.style.display;
                elOff.style.display = tmp;

                if (el) {
                    el.style.display = 'none' === tmp ? 'none' : 'block';
                }

                return this;
            },

            createTabs: function() {
                var tabGroups = document.querySelectorAll('.sf-tabs');

                /* create the tab navigation for each group of tabs */
                for (var i = 0; i < tabGroups.length; i++) {
                    var tabs = tabGroups[i].querySelectorAll('.tab');
                    var tabNavigation = document.createElement('ul');
                    tabNavigation.className = 'tab-navigation';

                    for (var j = 0; j < tabs.length; j++) {
                        var tabId = 'tab-' + i + '-' + j;
                        var tabTitle = tabs[j].querySelector('.tab-title').innerHTML;

                        var tabNavigationItem = document.createElement('li');
                        tabNavigationItem.setAttribute('data-tab-id', tabId);
                        if (j == 0) { Sfjs.addClass(tabNavigationItem, 'active'); }
                        if (Sfjs.hasClass(tabs[j], 'disabled')) { Sfjs.addClass(tabNavigationItem, 'disabled'); }
                        tabNavigationItem.innerHTML = tabTitle;
                        tabNavigation.appendChild(tabNavigationItem);

                        var tabContent = tabs[j].querySelector('.tab-content');
                        tabContent.parentElement.setAttribute('id', tabId);
                    }

                    tabGroups[i].insertBefore(tabNavigation, tabGroups[i].firstChild);
                }

                /* display the active tab and add the 'click' event listeners */
                for (i = 0; i < tabGroups.length; i++) {
                    tabNavigation = tabGroups[i].querySelectorAll('.tab-navigation li');

                    for (j = 0; j < tabNavigation.length; j++) {
                        tabId = tabNavigation[j].getAttribute('data-tab-id');
                        document.getElementById(tabId).querySelector('.tab-title').className = 'hidden';

                        if (Sfjs.hasClass(tabNavigation[j], 'active')) {
                            document.getElementById(tabId).className = 'block';
                        } else {
                            document.getElementById(tabId).className = 'hidden';
                        }

                        tabNavigation[j].addEventListener('click', function(e) {
                            var activeTab = e.target || e.srcElement;

                            /* needed because when the tab contains HTML contents, user can click */
                            /* on any of those elements instead of their parent '<li>' element */
                            while (activeTab.tagName.toLowerCase() !== 'li') {
                                activeTab = activeTab.parentNode;
                            }

                            /* get the full list of tabs through the parent of the active tab element */
                            var tabNavigation = activeTab.parentNode.children;
                            for (var k = 0; k < tabNavigation.length; k++) {
                                var tabId = tabNavigation[k].getAttribute('data-tab-id');
                                document.getElementById(tabId).className = 'hidden';
                                Sfjs.removeClass(tabNavigation[k], 'active');
                            }

                            Sfjs.addClass(activeTab, 'active');
                            var activeTabId = activeTab.getAttribute('data-tab-id');
                            document.getElementById(activeTabId).className = 'block';
                        });
                    }
                }
            },

            createToggles: function() {
                var toggles = document.querySelectorAll('.sf-toggle');

                for (var i = 0; i < toggles.length; i++) {
                    var elementSelector = toggles[i].getAttribute('data-toggle-selector');
                    var element = document.querySelector(elementSelector);

                    Sfjs.addClass(element, 'sf-toggle-content');

                    if (toggles[i].hasAttribute('data-toggle-initial') && toggles[i].getAttribute('data-toggle-initial') == 'display') {
                        Sfjs.addClass(element, 'sf-toggle-visible');
                    } else {
                        Sfjs.addClass(element, 'sf-toggle-hidden');
                    }

                    Sfjs.addEventListener(toggles[i], 'click', function(e) {
                        e.preventDefault();

                        var toggle = e.target || e.srcElement;

                        /* needed because when the toggle contains HTML contents, user can click */
                        /* on any of those elements instead of their parent '.sf-toggle' element */
                        while (!Sfjs.hasClass(toggle, 'sf-toggle')) {
                            toggle = toggle.parentNode;
                        }

                        var element = document.querySelector(toggle.getAttribute('data-toggle-selector'));

                        Sfjs.toggleClass(element, 'sf-toggle-hidden');
                        Sfjs.toggleClass(element, 'sf-toggle-visible');

                        /* the toggle doesn't change its contents when clicking on it */
                        if (!toggle.hasAttribute('data-toggle-alt-content')) {
                            return;
                        }

                        if (!toggle.hasAttribute('data-toggle-original-content')) {
                            toggle.setAttribute('data-toggle-original-content', toggle.innerHTML);
                        }

                        var currentContent = toggle.innerHTML;
                        var originalContent = toggle.getAttribute('data-toggle-original-content');
                        var altContent = toggle.getAttribute('data-toggle-alt-content');
                        toggle.innerHTML = currentContent !== altContent ? altContent : originalContent;
                    });
                }
            }
        };
    })();

    Sfjs.addEventListener(window, 'load', function() {
        Sfjs.createTabs();
        Sfjs.createToggles();
    });

/*]]>*/</script>
";

        $__internal_65623515d1f14684ff164270d3a152dd6924bec7a54dc8d9f0f4294ecce37d26->leave($__internal_65623515d1f14684ff164270d3a152dd6924bec7a54dc8d9f0f4294ecce37d26_prof);

    }

    public function getTemplateName()
    {
        return "WebProfilerBundle:Profiler:base_js.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  298 => 258,  265 => 228,  259 => 225,  255 => 224,  249 => 221,  245 => 220,  234 => 211,  232 => 210,  25 => 5,  22 => 1,);
    }
}
/* <script>/*<![CDATA[*//* */
/*     {# Caution: the contents of this file are processed by Twig before loading*/
/*                 them as JavaScript source code. Always use '/*' comments instead*/
/*                 of '//' comments to avoid impossible-to-debug side-effects #}*/
/* */
/*     Sfjs = (function() {*/
/*         "use strict";*/
/* */
/*         var classListIsSupported = 'classList' in document.documentElement;*/
/* */
/*         if (classListIsSupported) {*/
/*             var hasClass = function (el, cssClass) { return el.classList.contains(cssClass); };*/
/*             var removeClass = function(el, cssClass) { el.classList.remove(cssClass); };*/
/*             var addClass = function(el, cssClass) { el.classList.add(cssClass); };*/
/*             var toggleClass = function(el, cssClass) { el.classList.toggle(cssClass); };*/
/*         } else {*/
/*             var hasClass = function (el, cssClass) { return el.className.match(new RegExp('\\b' + cssClass + '\\b')); };*/
/*             var removeClass = function(el, cssClass) { el.className = el.className.replace(new RegExp('\\b' + cssClass + '\\b'), ' '); };*/
/*             var addClass = function(el, cssClass) { if (!hasClass(el, cssClass)) { el.className += " " + cssClass; } };*/
/*             var toggleClass = function(el, cssClass) { hasClass(el, cssClass) ? removeClass(el, cssClass) : addClass(el, cssClass); };*/
/*         }*/
/* */
/*         var noop = function() {},*/
/* */
/*             collectionToArray = function (collection) {*/
/*                 var length = collection.length || 0,*/
/*                     results = new Array(length);*/
/* */
/*                 while (length--) {*/
/*                     results[length] = collection[length];*/
/*                 }*/
/* */
/*                 return results;*/
/*             },*/
/* */
/*             profilerStorageKey = 'sf2/profiler/',*/
/* */
/*             request = function(url, onSuccess, onError, payload, options) {*/
/*                 var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');*/
/*                 options = options || {};*/
/*                 options.maxTries = options.maxTries || 0;*/
/*                 xhr.open(options.method || 'GET', url, true);*/
/*                 xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');*/
/*                 xhr.onreadystatechange = function(state) {*/
/*                     if (4 !== xhr.readyState) {*/
/*                         return null;*/
/*                     }*/
/* */
/*                     if (xhr.status == 404 && options.maxTries > 1) {*/
/*                         setTimeout(function(){*/
/*                             options.maxTries--;*/
/*                             request(url, onSuccess, onError, payload, options);*/
/*                         }, 500);*/
/* */
/*                         return null;*/
/*                     }*/
/* */
/*                     if (200 === xhr.status) {*/
/*                         (onSuccess || noop)(xhr);*/
/*                     } else {*/
/*                         (onError || noop)(xhr);*/
/*                     }*/
/*                 };*/
/*                 xhr.send(payload || '');*/
/*             },*/
/* */
/*             getPreference = function(name) {*/
/*                 if (!window.localStorage) {*/
/*                     return null;*/
/*                 }*/
/* */
/*                 return localStorage.getItem(profilerStorageKey + name);*/
/*             },*/
/* */
/*             setPreference = function(name, value) {*/
/*                 if (!window.localStorage) {*/
/*                     return null;*/
/*                 }*/
/* */
/*                 localStorage.setItem(profilerStorageKey + name, value);*/
/*             },*/
/* */
/*             requestStack = [],*/
/* */
/*             renderAjaxRequests = function() {*/
/*                 var requestCounter = document.querySelectorAll('.sf-toolbar-ajax-requests');*/
/*                 if (!requestCounter.length) {*/
/*                     return;*/
/*                 }*/
/* */
/*                 var ajaxToolbarPanel = document.querySelector('.sf-toolbar-block-ajax');*/
/*                 var tbodies = document.querySelectorAll('.sf-toolbar-ajax-request-list');*/
/*                 var state = 'ok';*/
/*                 if (tbodies.length) {*/
/*                     var tbody = tbodies[0];*/
/* */
/*                     var rows = document.createDocumentFragment();*/
/* */
/*                     if (requestStack.length) {*/
/*                         for (var i = 0; i < requestStack.length; i++) {*/
/*                             var request = requestStack[i];*/
/* */
/*                             var row = document.createElement('tr');*/
/*                             rows.insertBefore(row, rows.firstChild);*/
/* */
/*                             var methodCell = document.createElement('td');*/
/*                             if (request.error) {*/
/*                                 methodCell.className = 'sf-ajax-request-error';*/
/*                             }*/
/*                             methodCell.textContent = request.method;*/
/*                             row.appendChild(methodCell);*/
/* */
/*                             var pathCell = document.createElement('td');*/
/*                             pathCell.className = 'sf-ajax-request-url';*/
/*                             if ('GET' === request.method) {*/
/*                                 var pathLink = document.createElement('a');*/
/*                                 pathLink.setAttribute('href', request.url);*/
/*                                 pathLink.textContent = request.url;*/
/*                                 pathCell.appendChild(pathLink);*/
/*                             } else {*/
/*                                 pathCell.textContent = request.url;*/
/*                             }*/
/*                             pathCell.setAttribute('title', request.url);*/
/*                             row.appendChild(pathCell);*/
/* */
/*                             var durationCell = document.createElement('td');*/
/*                             durationCell.className = 'sf-ajax-request-duration';*/
/* */
/*                             if (request.duration) {*/
/*                                 durationCell.textContent = request.duration + "ms";*/
/*                             } else {*/
/*                                 durationCell.textContent = '-';*/
/*                             }*/
/*                             row.appendChild(durationCell);*/
/* */
/*                             row.appendChild(document.createTextNode(' '));*/
/*                             var profilerCell = document.createElement('td');*/
/* */
/*                             if (request.profilerUrl) {*/
/*                                 var profilerLink = document.createElement('a');*/
/*                                 profilerLink.setAttribute('href', request.profilerUrl);*/
/*                                 profilerLink.textContent = request.profile;*/
/*                                 profilerCell.appendChild(profilerLink);*/
/*                             } else {*/
/*                                 profilerCell.textContent = 'n/a';*/
/*                             }*/
/* */
/*                             row.appendChild(profilerCell);*/
/* */
/*                             var requestState = 'ok';*/
/*                             if (request.error) {*/
/*                                 requestState = 'error';*/
/*                                 if (state != "loading" && i > requestStack.length - 4) {*/
/*                                     state = 'error';*/
/*                                 }*/
/*                             } else if (request.loading) {*/
/*                                 requestState = 'loading';*/
/*                                 state = 'loading';*/
/*                             }*/
/*                             row.className = 'sf-ajax-request sf-ajax-request-' + requestState;*/
/*                         }*/
/* */
/*                         var infoSpan = document.querySelectorAll(".sf-toolbar-ajax-info")[0];*/
/*                         var children = collectionToArray(tbody.children);*/
/*                         for (var i = 0; i < children.length; i++) {*/
/*                             tbody.removeChild(children[i]);*/
/*                         }*/
/*                         tbody.appendChild(rows);*/
/* */
/*                         if (infoSpan) {*/
/*                             var text = requestStack.length + ' AJAX request' + (requestStack.length > 1 ? 's' : '');*/
/*                             infoSpan.textContent = text;*/
/*                         }*/
/* */
/*                         ajaxToolbarPanel.style.display = 'block';*/
/*                     } else {*/
/*                         ajaxToolbarPanel.style.display = 'none';*/
/*                     }*/
/*                 }*/
/* */
/*                 requestCounter[0].textContent = requestStack.length;*/
/* */
/*                 var className = 'sf-toolbar-ajax-requests sf-toolbar-value';*/
/*                 requestCounter[0].className = className;*/
/* */
/*                 if (state == 'ok') {*/
/*                     Sfjs.removeClass(ajaxToolbarPanel, 'sf-ajax-request-loading');*/
/*                     Sfjs.removeClass(ajaxToolbarPanel, 'sf-toolbar-status-red');*/
/*                 } else if (state == 'error') {*/
/*                     Sfjs.addClass(ajaxToolbarPanel, 'sf-toolbar-status-red');*/
/*                     Sfjs.removeClass(ajaxToolbarPanel, 'sf-ajax-request-loading');*/
/*                 } else {*/
/*                     Sfjs.addClass(ajaxToolbarPanel, 'sf-ajax-request-loading');*/
/*                 }*/
/*             };*/
/* */
/*         var addEventListener;*/
/* */
/*         var el = document.createElement('div');*/
/*         if (!'addEventListener' in el) {*/
/*             addEventListener = function (element, eventName, callback) {*/
/*                 element.attachEvent('on' + eventName, callback);*/
/*             };*/
/*         } else {*/
/*             addEventListener = function (element, eventName, callback) {*/
/*                 element.addEventListener(eventName, callback, false);*/
/*             };*/
/*         }*/
/* */
/*         {% if excluded_ajax_paths is defined %}*/
/*             if (window.XMLHttpRequest && XMLHttpRequest.prototype.addEventListener) {*/
/*                 var proxied = XMLHttpRequest.prototype.open;*/
/* */
/*                 XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {*/
/*                     var self = this;*/
/* */
/*                     /* prevent logging AJAX calls to static and inline files, like templates *//* */
/*                     var path = url;*/
/*                     if (url.substr(0, 1) === '/') {*/
/*                         if (0 === url.indexOf('{{ request.basePath|e('js') }}')) {*/
/*                             path = url.substr({{ request.basePath|length }});*/
/*                         }*/
/*                     }*/
/*                     else if (0 === url.indexOf('{{ (request.schemeAndHttpHost ~ request.basePath)|e('js') }}')) {*/
/*                         path = url.substr({{ (request.schemeAndHttpHost ~ request.basePath)|length }});*/
/*                     }*/
/* */
/*                     if (!path.match(new RegExp({{ excluded_ajax_paths|json_encode|raw }}))) {*/
/*                         var stackElement = {*/
/*                             loading: true,*/
/*                             error: false,*/
/*                             url: url,*/
/*                             method: method,*/
/*                             start: new Date()*/
/*                         };*/
/* */
/*                         requestStack.push(stackElement);*/
/* */
/*                         this.addEventListener('readystatechange', function() {*/
/*                             if (self.readyState == 4) {*/
/*                                 stackElement.duration = new Date() - stackElement.start;*/
/*                                 stackElement.loading = false;*/
/*                                 stackElement.error = self.status < 200 || self.status >= 400;*/
/*                                 stackElement.profile = self.getResponseHeader("X-Debug-Token");*/
/*                                 stackElement.profilerUrl = self.getResponseHeader("X-Debug-Token-Link");*/
/* */
/*                                 Sfjs.renderAjaxRequests();*/
/*                             }*/
/*                         }, false);*/
/* */
/*                         Sfjs.renderAjaxRequests();*/
/*                     }*/
/* */
/*                     proxied.apply(this, Array.prototype.slice.call(arguments));*/
/*                 };*/
/*             }*/
/*         {% endif %}*/
/* */
/*         return {*/
/*             hasClass: hasClass,*/
/* */
/*             removeClass: removeClass,*/
/* */
/*             addClass: addClass,*/
/* */
/*             toggleClass: toggleClass,*/
/* */
/*             getPreference: getPreference,*/
/* */
/*             setPreference: setPreference,*/
/* */
/*             addEventListener: addEventListener,*/
/* */
/*             request: request,*/
/* */
/*             renderAjaxRequests: renderAjaxRequests,*/
/* */
/*             load: function(selector, url, onSuccess, onError, options) {*/
/*                 var el = document.getElementById(selector);*/
/* */
/*                 if (el && el.getAttribute('data-sfurl') !== url) {*/
/*                     request(*/
/*                         url,*/
/*                         function(xhr) {*/
/*                             el.innerHTML = xhr.responseText;*/
/*                             el.setAttribute('data-sfurl', url);*/
/*                             removeClass(el, 'loading');*/
/*                             (onSuccess || noop)(xhr, el);*/
/*                         },*/
/*                         function(xhr) { (onError || noop)(xhr, el); },*/
/*                         '',*/
/*                         options*/
/*                     );*/
/*                 }*/
/* */
/*                 return this;*/
/*             },*/
/* */
/*             toggle: function(selector, elOn, elOff) {*/
/*                 var tmp = elOn.style.display,*/
/*                     el = document.getElementById(selector);*/
/* */
/*                 elOn.style.display = elOff.style.display;*/
/*                 elOff.style.display = tmp;*/
/* */
/*                 if (el) {*/
/*                     el.style.display = 'none' === tmp ? 'none' : 'block';*/
/*                 }*/
/* */
/*                 return this;*/
/*             },*/
/* */
/*             createTabs: function() {*/
/*                 var tabGroups = document.querySelectorAll('.sf-tabs');*/
/* */
/*                 /* create the tab navigation for each group of tabs *//* */
/*                 for (var i = 0; i < tabGroups.length; i++) {*/
/*                     var tabs = tabGroups[i].querySelectorAll('.tab');*/
/*                     var tabNavigation = document.createElement('ul');*/
/*                     tabNavigation.className = 'tab-navigation';*/
/* */
/*                     for (var j = 0; j < tabs.length; j++) {*/
/*                         var tabId = 'tab-' + i + '-' + j;*/
/*                         var tabTitle = tabs[j].querySelector('.tab-title').innerHTML;*/
/* */
/*                         var tabNavigationItem = document.createElement('li');*/
/*                         tabNavigationItem.setAttribute('data-tab-id', tabId);*/
/*                         if (j == 0) { Sfjs.addClass(tabNavigationItem, 'active'); }*/
/*                         if (Sfjs.hasClass(tabs[j], 'disabled')) { Sfjs.addClass(tabNavigationItem, 'disabled'); }*/
/*                         tabNavigationItem.innerHTML = tabTitle;*/
/*                         tabNavigation.appendChild(tabNavigationItem);*/
/* */
/*                         var tabContent = tabs[j].querySelector('.tab-content');*/
/*                         tabContent.parentElement.setAttribute('id', tabId);*/
/*                     }*/
/* */
/*                     tabGroups[i].insertBefore(tabNavigation, tabGroups[i].firstChild);*/
/*                 }*/
/* */
/*                 /* display the active tab and add the 'click' event listeners *//* */
/*                 for (i = 0; i < tabGroups.length; i++) {*/
/*                     tabNavigation = tabGroups[i].querySelectorAll('.tab-navigation li');*/
/* */
/*                     for (j = 0; j < tabNavigation.length; j++) {*/
/*                         tabId = tabNavigation[j].getAttribute('data-tab-id');*/
/*                         document.getElementById(tabId).querySelector('.tab-title').className = 'hidden';*/
/* */
/*                         if (Sfjs.hasClass(tabNavigation[j], 'active')) {*/
/*                             document.getElementById(tabId).className = 'block';*/
/*                         } else {*/
/*                             document.getElementById(tabId).className = 'hidden';*/
/*                         }*/
/* */
/*                         tabNavigation[j].addEventListener('click', function(e) {*/
/*                             var activeTab = e.target || e.srcElement;*/
/* */
/*                             /* needed because when the tab contains HTML contents, user can click *//* */
/*                             /* on any of those elements instead of their parent '<li>' element *//* */
/*                             while (activeTab.tagName.toLowerCase() !== 'li') {*/
/*                                 activeTab = activeTab.parentNode;*/
/*                             }*/
/* */
/*                             /* get the full list of tabs through the parent of the active tab element *//* */
/*                             var tabNavigation = activeTab.parentNode.children;*/
/*                             for (var k = 0; k < tabNavigation.length; k++) {*/
/*                                 var tabId = tabNavigation[k].getAttribute('data-tab-id');*/
/*                                 document.getElementById(tabId).className = 'hidden';*/
/*                                 Sfjs.removeClass(tabNavigation[k], 'active');*/
/*                             }*/
/* */
/*                             Sfjs.addClass(activeTab, 'active');*/
/*                             var activeTabId = activeTab.getAttribute('data-tab-id');*/
/*                             document.getElementById(activeTabId).className = 'block';*/
/*                         });*/
/*                     }*/
/*                 }*/
/*             },*/
/* */
/*             createToggles: function() {*/
/*                 var toggles = document.querySelectorAll('.sf-toggle');*/
/* */
/*                 for (var i = 0; i < toggles.length; i++) {*/
/*                     var elementSelector = toggles[i].getAttribute('data-toggle-selector');*/
/*                     var element = document.querySelector(elementSelector);*/
/* */
/*                     Sfjs.addClass(element, 'sf-toggle-content');*/
/* */
/*                     if (toggles[i].hasAttribute('data-toggle-initial') && toggles[i].getAttribute('data-toggle-initial') == 'display') {*/
/*                         Sfjs.addClass(element, 'sf-toggle-visible');*/
/*                     } else {*/
/*                         Sfjs.addClass(element, 'sf-toggle-hidden');*/
/*                     }*/
/* */
/*                     Sfjs.addEventListener(toggles[i], 'click', function(e) {*/
/*                         e.preventDefault();*/
/* */
/*                         var toggle = e.target || e.srcElement;*/
/* */
/*                         /* needed because when the toggle contains HTML contents, user can click *//* */
/*                         /* on any of those elements instead of their parent '.sf-toggle' element *//* */
/*                         while (!Sfjs.hasClass(toggle, 'sf-toggle')) {*/
/*                             toggle = toggle.parentNode;*/
/*                         }*/
/* */
/*                         var element = document.querySelector(toggle.getAttribute('data-toggle-selector'));*/
/* */
/*                         Sfjs.toggleClass(element, 'sf-toggle-hidden');*/
/*                         Sfjs.toggleClass(element, 'sf-toggle-visible');*/
/* */
/*                         /* the toggle doesn't change its contents when clicking on it *//* */
/*                         if (!toggle.hasAttribute('data-toggle-alt-content')) {*/
/*                             return;*/
/*                         }*/
/* */
/*                         if (!toggle.hasAttribute('data-toggle-original-content')) {*/
/*                             toggle.setAttribute('data-toggle-original-content', toggle.innerHTML);*/
/*                         }*/
/* */
/*                         var currentContent = toggle.innerHTML;*/
/*                         var originalContent = toggle.getAttribute('data-toggle-original-content');*/
/*                         var altContent = toggle.getAttribute('data-toggle-alt-content');*/
/*                         toggle.innerHTML = currentContent !== altContent ? altContent : originalContent;*/
/*                     });*/
/*                 }*/
/*             }*/
/*         };*/
/*     })();*/
/* */
/*     Sfjs.addEventListener(window, 'load', function() {*/
/*         Sfjs.createTabs();*/
/*         Sfjs.createToggles();*/
/*     });*/
/* */
/* /*]]>*//* </script>*/
/* */


text:
package autotee

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"

	"github.com/deckarep/golang-set"
	"github.com/juju/errors"
)

type IcecastUrls struct {
	mapset.Set
}

type Icecast struct {
	config *Config
	client http.Client
}

func NewIcecast(config *Config) Server {
	return &Icecast{
		config: config,
		client: http.Client{Timeout: config.Times.ServerRequestTimeout},
	}
}

// Get a list of active streams of a specific app from an Icecast server.
func (nr *Icecast) GetActiveStreams() (mapset.Set, error) {

	// Make HTTP request
	resp, err := nr.client.Get(nr.config.Server.Url)
	if err != nil {
		return nil, errors.Trace(err)
	}
	defer resp.Body.Close()

	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.Trace(err)
	}

	urls := IcecastUrls{mapset.NewSet()}
	err = json.Unmarshal(bytes, &urls)
	if err != nil {
		return nil, errors.Trace(err)
	}

	return urls.Set, nil
}

func (iu *IcecastUrls) UnmarshalJSON(bytes []byte) error {

	var aux struct {
		Icestats struct {
			// No source => missing (nil)
			// One source => dict (map[string]interface{})
			// More sources => list ([]interface{})
			Source interface{} `json:"source"`
		} `json:"icestats"`
	}

	if err := json.Unmarshal(bytes, &aux); err != nil {
		return errors.Trace(err)
	}

	switch obj := aux.Icestats.Source.(type) {

	// No source?
	case nil:
		return nil

	// Exactly one source?
	default:
		return iu.addSourceObj(obj)

	// More than one source?
	case []interface{}:
		for _, subobj := range obj {
			if err := iu.addSourceObj(subobj); err != nil {
				return errors.Trace(err)
			}
		}
		return nil
	}
}

func (iu *IcecastUrls) addSourceObj(sourceObj interface{}) error {
	m, ok := sourceObj.(map[string]interface{})
	if !ok {
		return errors.New("source wasn't a JSON object")
	}

	urlObj, ok := m["listenurl"]
	if !ok {
		return errors.New("listenurl field not present")
	}

	urlStr, ok := urlObj.(string)
	if !ok {
		return errors.New("listenurl field did not contain a string")
	}

	url, err := url.Parse(urlStr)
	if !ok {
		return errors.Annotate(err, "failed to parse listenurl")
	}

	iu.Add(strings.TrimLeft(url.Path, "/"))
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
import React, {Component} from "react";
import {Nav, NavItem} from 'react-bootstrap';
import find from "lodash/fp/find";
import map from "lodash/fp/map";
const mapWithIndex = map.convert({cap: false});

const getActiveTab = ({props: {eventKey}}) => eventKey;
const renderTab = (activeTab, onSelect) => ({props: {eventKey, title}}, i) => <NavItem key={i} eventKey={eventKey} active={activeTab === eventKey} onSelect={onSelect}>{title}</NavItem>;

export default class TabContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {active: 1};
        this.changeTab = this.changeTab.bind(this);
    }

    changeTab(eventKey) {
        this.setState({active: eventKey});
    }

    render() {
        const {children} = this.props;
        const {active} = this.state;

        const tab = find(tab => getActiveTab(tab) === active)(children);
        const navItems = mapWithIndex(renderTab(active, this.changeTab))(children);

        return

                {navItems}

                {tab && React.cloneElement(tab, {active: true})}

    }
}


text:
from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url

from .views import GlobalOverview

urlpatterns = patterns('',
    url(r'^$', GlobalOverview.as_view(), name='index'),
)


text:
"""Tests for tensorflow.python.client.session.Session's list_devices API."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.core.protobuf import cluster_pb2
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.platform import googletest
from tensorflow.python.training import server_lib

ops._USE_C_API = True

class SessionListDevicesTest(test_util.TensorFlowTestCase):

  @test_util.disable_c_api  # list_devices doesn't work with C API
  def testListDevices(self):
    with session.Session() as sess:
      devices = sess.list_devices()
      self.assertTrue('/job:localhost/replica:0/task:0/device:CPU:0' in set(
          [d.name for d in devices]), devices)
      self.assertGreaterEqual(1, len(devices), devices)

  @test_util.disable_c_api  # list_devices doesn't work with C API
  def testListDevicesGrpcSession(self):
    server = server_lib.Server.create_local_server()
    with session.Session(server.target) as sess:
      devices = sess.list_devices()
      self.assertTrue('/job:local/replica:0/task:0/device:CPU:0' in set(
          [d.name for d in devices]), devices)
      self.assertGreaterEqual(1, len(devices), devices)

  @test_util.disable_c_api  # list_devices doesn't work with C API
  def testListDevicesClusterSpecPropagation(self):
    server1 = server_lib.Server.create_local_server()
    server2 = server_lib.Server.create_local_server()

    cluster_def = cluster_pb2.ClusterDef()
    job = cluster_def.job.add()
    job.name = 'worker'
    job.tasks[0] = server1.target[len('grpc://'):]
    job.tasks[1] = server2.target[len('grpc://'):]
    config = config_pb2.ConfigProto(cluster_def=cluster_def)
    with session.Session(server1.target, config=config) as sess:
      devices = sess.list_devices()
      device_names = set([d.name for d in devices])
      self.assertTrue(
          '/job:worker/replica:0/task:0/device:CPU:0' in device_names)
      self.assertTrue(
          '/job:worker/replica:0/task:1/device:CPU:0' in device_names)
      self.assertGreaterEqual(2, len(devices), devices)

if __name__ == '__main__':
  googletest.main()


text:
class CreateSongs < ActiveRecord::Migration
  def self.up
    create_table :songs do |t|
      t.integer :position
      t.string :title
      t.string :mp3_file_name
      t.string :mp3_content_type
      t.integer :mp3_file_size
      t.datetime :mp3_updated_at
      t.string :ogg_file_name
      t.string :ogg_content_type
      t.integer :ogg_file_size
      t.datetime :ogg_updated_at
      t.string :description

      t.timestamps
    end
  end

  def self.down
    drop_table :songs
  end
end


text:
<?php
namespace Unrulynatives\Helpers\Helpers;

use App\User;

class AvatarHelper {

    public static function dispAvatar($itemkind,$string=null) {
        if ($string == '') {
            $avatar = '_empty_'.$itemkind.'.jpg';

      } else {
        $avatar = $string;
      }

       return $avatar;
   }

    public static function userAvatar($userid) {
        if($userid == '') {
          return '';
        }
        $user = User::find($userid);
        $hash = md5(strtolower($user->email));
        return "http://www.gravatar.com/avatar/$hash";
      // return 'xx';

   }

}


text:
package org.quartz;

/**
 *

 * A marker interface for {@link org.quartz.JobDetail} s that
 * wish to have their state maintained between executions.
 *

 *
 *

 * StatefulJob instances follow slightly different rules from
 * regular Job instances. The key difference is that their
 * associated {@link JobDataMap} is re-persisted after every
 * execution of the job, thus preserving state for the next execution. The
 * other difference is that stateful jobs are not allowed to execute
 * concurrently, which means new triggers that occur before the completion of
 * the execute(xx) method will be delayed.
 *

 *
 * @see Job
 * @see JobDetail
 * @see JobDataMap
 * @see Scheduler
 *
 * @author James House
 */
public interface StatefulJob extends Job {

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Interface.
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

}


text:
var Promise = require("bluebird"),
  indexBy = require('lodash.indexby'),
  readFile = Promise.promisify(require("fs").readFile),
  parseXml = Promise.promisify(require("xml2js").parseString);

var SVG_FILE = require.resolve("font-awesome/fonts/fontawesome-webfont.svg");

function getFontData() {
  return readFile(SVG_FILE)
    .then(function (fontData) {
      return fontData.toString("utf-8");
    })
    .then(parseXml)
    .then(function (parsedXml) {
      return parsedXml.svg.defs[0].font[0].glyph;
    })
    .map(function (xmlGlyph) {
        if (xmlGlyph.$.unicode) {
          return {
            data: xmlGlyph.$,
            unicodeDec: xmlGlyph.$.unicode.charCodeAt(0)
          };
      }
    })
    .then(function (fontData) {
      return indexBy(fontData, "unicodeDec");
    });
}

module.exports = getFontData;


text:
#include <deque>
#include "m-deque.h"

DEQUE_DEF(deque_float, float)

// Transform an integer 'i' into a M*LIB base item 'a'
#define TYPE_SET_INT(a, i) (a) = (i)

// Container OPLIST
#define CONT_OPL   DEQUE_OPLIST(deque_float, M_OPL_float())

// C++ Base class of the item in the container
#define BASE_CLASS float

// Transform an integer 'i' into a C++ base item 'a'
#define CLASS_SET_INT(a, i) (a) = (i)

// C++ Container class
#define CONT_CLASS std::deque<float>

// Compare the M*LIB container a to the C++ container b
#define CMP_CONT(a, b) cmp_cont(a, b)

// Compare the M*LIB base object to the C++ base object
#define CMP_BASE(a, b) assert( (a) == (b) )

void cmp_cont(deque_float_t a, std::deque<float> b)
{
  deque_float_it_t ita;
  deque_float_it(ita, a);
  auto          itb = b.begin();
  while (itb != b.end()) {
    assert(!deque_float_end_p(ita));
    const float *b0 = deque_float_cref(ita);
    float &b1 = *itb;
    CMP_BASE(*b0, b1);
    itb++;
    deque_float_next(ita);
  }
  assert(deque_float_end_p(ita));
}

#define DEFAULT_NUMBER 1000000
#define HAVE_PUSH_FRONT
#define HAVE_POP_FRONT
#include "check-generic.hpp"


text:
#ifndef QSGDISTANCEFIELDGLYPHNODE_P_H
#define QSGDISTANCEFIELDGLYPHNODE_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <private/qsgadaptationlayer_p.h>
#include <QtQuick/qsgtexture.h>

#include <QtQuick/private/qquicktext_p.h>

QT_BEGIN_NAMESPACE

class QSGRenderContext;
class QSGDistanceFieldGlyphCacheManager;
class QSGDistanceFieldTextMaterial;
class QSGDistanceFieldGlyphNode: public QSGGlyphNode, public QSGDistanceFieldGlyphConsumer
{
public:
    QSGDistanceFieldGlyphNode(QSGRenderContext *context);
    ~QSGDistanceFieldGlyphNode();

    virtual QPointF baseLine() const { return m_baseLine; }
    virtual void setGlyphs(const QPointF &position, const QGlyphRun &glyphs);
    virtual void setColor(const QColor &color);

    virtual void setPreferredAntialiasingMode(AntialiasingMode mode);

    virtual void setStyle(QQuickText::TextStyle style);
    virtual void setStyleColor(const QColor &color);

    virtual void update();
    void preprocess();

    void invalidateGlyphs(const QVector<quint32> &glyphs);

    void updateGeometry();

private:
    enum DistanceFieldGlyphNodeType {
        RootGlyphNode,
        SubGlyphNode
    };

    void setGlyphNodeType(DistanceFieldGlyphNodeType type) { m_glyphNodeType = type; }
    void updateMaterial();

    DistanceFieldGlyphNodeType m_glyphNodeType;
    QColor m_color;
    QPointF m_baseLine;
    QSGRenderContext *m_context;
    QSGDistanceFieldTextMaterial *m_material;
    QPointF m_originalPosition;
    QPointF m_position;
    QGlyphRun m_glyphs;
    QSGDistanceFieldGlyphCache *m_glyph_cache;
    QSGGeometry m_geometry;
    QQuickText::TextStyle m_style;
    QColor m_styleColor;
    AntialiasingMode m_antialiasingMode;
    QRectF m_boundingRect;
    const QSGDistanceFieldGlyphCache::Texture *m_texture;
    QLinkedList<QSGNode *> m_nodesToDelete;

    struct GlyphInfo {
        QVector<quint32> indexes;
        QVector<QPointF> positions;
    };
    QSet<quint32> m_allGlyphIndexesLookup;

    uint m_dirtyGeometry: 1;
    uint m_dirtyMaterial: 1;
};

QT_END_NAMESPACE

#endif


text:
package java.nio.charset;

/**
 * @since 1.4
 */
public class MalformedInputException extends CharacterCodingException
{
  private static final long serialVersionUID = - 3438823399834806194L;

  private int inputLength;

  /**
   * Creates the exception
   *
   * @param inputLength the position of malformed input in the input stream
   */
  public MalformedInputException (int inputLength)
  {
    super ();
    this.inputLength = inputLength;
  }

  /**
   * Retrieves the position of the malformed input in the input stream.
   *
   * @return the position
   */
  public int getInputLength ()
  {
    return inputLength;
  }

  /**
   * Returns the detail message string of this throwable
   *
   * @return the message
   */
  public String getMessage ()
  {
    return "Input length = " + inputLength;
  }
}


text:
import unittest

from nlglib.microplanning import *

class TestXmlFormatting(unittest.TestCase):

    def test_string(self):
        v = XmlVisitor()
        s = String('hello')
        expected = """\
<child xsi:type="WordElement" canned="true"  cat="ANY">
  <base>hello</base>
</child>
"""
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

    def test_word(self):
        v = XmlVisitor()
        s = Word('house', 'NOUN')
        expected = ('<child xsi:type="WordElement" cat="NOUN">\n'
                    '  <base>house</base>\n'
                    '</child>\n')
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

    def test_var(self):
        v = XmlVisitor()
        s = Var(0, 'truck')
        expected = """\
<child xsi:type="WordElement" canned="true"  cat="ANY">
  <base>truck</base>
</child>
"""
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

    def test_np(self):
        v = XmlVisitor()
        s = NP(Determiner('the'), Noun('truck'))
        expected = """\
<child xsi:type="NPPhraseSpec" cat="NOUN_PHRASE">
  <spec xsi:type="WordElement" cat="DETERMINER" discourseFunction="specifier">
    <base>the</base>
  </spec>

    <base>truck</base>

</child>
"""
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

    def test_vp(self):
        v = XmlVisitor()
        s = VP(Verb('drive'), Noun('truck'))
        expected = """\
<child xsi:type="VPPhraseSpec" cat="VERB_PHRASE">

    <base>drive</base>

  <compl xsi:type="WordElement" cat="NOUN">
    <base>truck</base>
  </compl>
</child>
"""
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

    def test_pp(self):
        v = XmlVisitor()
        s = PP(Preposition('in'), NP(Noun('office'), Determiner('the')))
        expected = """\
<child xsi:type="PPPhraseSpec" cat="PREPOSITION_PHRASE">

    <base>in</base>

  <compl xsi:type="NPPhraseSpec" cat="NOUN_PHRASE">
    <spec xsi:type="WordElement" cat="NOUN" discourseFunction="specifier">
      <base>office</base>
    </spec>

      <base>the</base>

  </compl>
</child>
"""
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

    def test_adjp(self):
        v = XmlVisitor()
        s = AdjP(Adjective('large'), Noun('office'))
        expected = """\
<child xsi:type="AdjPhraseSpec" cat="ADJECTIVE_PHRASE">

    <base>large</base>

  <compl xsi:type="WordElement" cat="NOUN">
    <base>office</base>
  </compl>
</child>
"""
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

    def test_advp(self):
        v = XmlVisitor()
        s = AdvP(Adverb('quickly'), VP(Verb('run')))
        expected = """\
<child xsi:type="AdvPhraseSpec" cat="ADVERB_PHRASE">

    <base>quickly</base>

  <compl xsi:type="VPPhraseSpec" cat="VERB_PHRASE">

      <base>run</base>

  </compl>
</child>
"""
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

    def test_clause(self):
        v = XmlVisitor()
        s = Clause(NP(Noun('Arthur')), VP(Verb('smiled'),
                                          features={'TENSE': 'PAST'}))
        expected = """\
<child xsi:type="SPhraseSpec" cat="CLAUSE">
  <subj xsi:type="NPPhraseSpec" cat="NOUN_PHRASE" discourseFunction="subject">

      <base>Arthur</base>

  </subj>
  <vp xsi:type="VPPhraseSpec" TENSE="PAST" cat="VERB_PHRASE" discourseFunction="predicate">

      <base>smiled</base>

  </vp>
</child>
"""
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

    def test_coordination(self):
        v = XmlVisitor()
        s = Coordination(Noun('truck'), Noun('car'), Noun('train'), conj='and')
        expected = """\
<child xsi:type="CoordinatedPhraseElement" cat="COORDINATION" conj="and">
  <coord xsi:type="WordElement" cat="NOUN">
    <base>truck</base>
  </coord>
  <coord xsi:type="WordElement" cat="NOUN">
    <base>car</base>
  </coord>
  <coord xsi:type="WordElement" cat="NOUN">
    <base>train</base>
  </coord>
</child>
"""
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

    def test_format(self):
        v = XmlVisitor(depth=1, indent='    ')
        s = Clause(NP(Noun('Arthur')), VP(Verb('smiled'),
                                          features={'TENSE': 'PAST'}))
        expected = """\
    <child xsi:type="SPhraseSpec" cat="CLAUSE">
        <subj xsi:type="NPPhraseSpec" cat="NOUN_PHRASE" discourseFunction="subject">

                <base>Arthur</base>

        </subj>
        <vp xsi:type="VPPhraseSpec" TENSE="PAST" cat="VERB_PHRASE" discourseFunction="predicate">

                <base>smiled</base>

        </vp>
    </child>
"""
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

        v = XmlVisitor(indent='', sep='')
        s = Clause(NP(Noun('Arthur')), VP(Verb('smiled'),
                                          features={'TENSE': 'PAST'}))
        expected = '<child xsi:type="SPhraseSpec" cat="CLAUSE">' \
                   '<subj xsi:type="NPPhraseSpec" cat="NOUN_PHRASE" discourseFunction="subject">' \
                   '' \
                   '<base>Arthur</base></subj>' \
                   '<vp xsi:type="VPPhraseSpec" TENSE="PAST" cat="VERB_PHRASE" ' \
                   'discourseFunction="predicate">' \
                   '' \
                   '<base>smiled</base></vp></child>'
        s.accept(v)
        actual = v.xml
        self.assertEqual(expected, actual)

class TestRepresentation(unittest.TestCase):

    def test_string(self):
        v = ReprVisitor()
        s = String('hello')
        expected = "String('hello')"
        s.accept(v)
        actual = str(v)
        self.assertEqual(expected, actual)

    def test_word(self):
        v = ReprVisitor()
        s = Noun('truck')
        expected = "Word('truck', 'NOUN')"
        s.accept(v)
        actual = str(v)
        self.assertEqual(s, eval(actual))
        self.assertEqual(expected, actual)

        v = ReprVisitor()
        s = Noun('truck')
        s['NUMBER'] = 'PLURAL'
        expected = "Word('truck', 'NOUN', features={'NUMBER': 'PLURAL'})"
        s.accept(v)
        actual = str(v)
        self.assertEqual(s, eval(actual))
        self.assertEqual(expected, actual)

    def test_var(self):
        v = ReprVisitor()
        s = Var(0, 'truck')
        expected = "Var(0, String('truck'))"
        s.accept(v)
        actual = str(v)
        self.assertEqual(expected, actual)

    def test_clause(self):
        v = ReprVisitor()
        s = Clause(NP(Noun('Python')), VP(Verb('rocks')))
        expected = ("Clause(NounPhrase(Word('Python', 'NOUN')),\n"
                    "       VerbPhrase(Word('rocks', 'VERB')))")
        s.accept(v)
        actual = str(v)
        self.assertEqual(expected, actual)
        self.assertEqual(s, eval(actual))

        v = ReprVisitor()
        s = Clause(NP(Noun('Python')), VP(Verb('rocks')))
        s.premodifiers.append(Adverb('today'))
        s['foo'] = 'bar'
        expected = ("Clause(NounPhrase(Word('Python', 'NOUN')),\n"
                    "       VerbPhrase(Word('rocks', 'VERB')),\n"
                    "       features={'foo': 'bar'},\n"
                    "       premodifiers=[Word('today', 'ADVERB')])")
        s.accept(v)
        actual = str(v)
        self.assertEqual(expected, actual)
        self.assertEqual(s, eval(actual))

    def test_vp(self):
        v = ReprVisitor()
        s = VP(Verb('put'), NP('the', 'bat'), PP('on', NP('the', 'mat')))
        expected = """\
VerbPhrase(Word('put', 'VERB'),
           NounPhrase(Word('bat', 'NOUN'), Word('the', 'DETERMINER')),
           PrepositionPhrase(Word('on', 'PREPOSITION'),
                             NounPhrase(Word('mat', 'NOUN'), Word('the', 'DETERMINER'))))"""
        s.accept(v)
        actual = str(v)
        self.assertEqual(s, eval(actual))
        self.assertEqual(expected, actual)

    def test_np(self):
        v = ReprVisitor()
        s = NP('the', 'war')
        expected = "NounPhrase(Word('war', 'NOUN'), Word('the', 'DETERMINER'))"
        s.accept(v)
        actual = str(v)
        self.assertEqual(s, eval(actual))
        self.assertEqual(expected, actual)

        v = ReprVisitor()
        s = NP('the', 'war')
        s.postmodifiers.append(PP('of',
                                  NP('the', 'worlds',
                                     features={'NUMBER': 'PLURAL'})))
        expected = "NounPhrase(Word('war', 'NOUN'), Word('the', 'DETERMINER'),\n"\
                   "           postmodifiers=[PrepositionPhrase(Word('of', 'PREPOSITION'), " \
                   "NounPhrase(Word('worlds', 'NOUN'), Word('the', 'DETERMINER'), " \
                   "features={'NUMBER': 'PLURAL'}))])"
        s.accept(v)
        actual = str(v)
        self.assertEqual(s, eval(actual))
        self.assertEqual(expected, actual)

    def test_pp(self):
        v = ReprVisitor()
        s = PP('on', NP('the', 'mat'))
        expected = ("PrepositionPhrase(Word('on', 'PREPOSITION'),\n"
                    "                  NounPhrase(Word('mat', 'NOUN'), Word('the', 'DETERMINER')))")
        s.accept(v)
        actual = str(v)
        self.assertEqual(s, eval(actual))
        self.assertEqual(expected, actual)

    def test_coordination(self):
        v = ReprVisitor()
        s = Coordination(Noun('truck'), Noun('bike'))
        expected = ("Coordination(Word('truck', 'NOUN'),\n"
                    "             Word('bike', 'NOUN'),\n"
                    "             conj=String('and'))")
        s.accept(v)
        actual = str(v)
        self.assertEqual(s, eval(actual))
        self.assertEqual(expected, actual)

class TestElementVisitor(unittest.TestCase):

    def test_string(self):
        v = ElementVisitor()
        s = String('hello')
        expected = [s]
        s.accept(v)
        actual = v.elements
        self.assertEqual(expected, actual)

    def test_word(self):
        v = ElementVisitor()
        s = NNP('Arthur Dent')
        expected = [s]
        s.accept(v)
        actual = v.elements
        self.assertEqual(expected, actual)

    def test_var(self):
        v = ElementVisitor()
        s = Var(0, 'Arthur Dent')
        expected = [s]
        s.accept(v)
        actual = v.elements
        self.assertEqual(expected, actual)

    def test_NP(self):
        v = ElementVisitor()
        s = NP('the', 'life')
        expected = [Word('the', 'DETERMINER'), Word('life', 'NOUN')]
        s.accept(v)
        actual = v.elements
        self.assertEqual(expected, actual)

    def test_vp(self):
        v = ElementVisitor()
        s = VP(Verb('run'), PP(Preposition('for'), NP('your', 'life')))
        expected = [Word('run', 'VERB'),
                    Word('for', 'PREPOSITION'),
                    Word('your', 'DETERMINER'),
                    Word('life', 'NOUN')]
        s.accept(v)
        actual = v.elements
        self.assertEqual(expected, actual)

    def test_pp(self):
        v = ElementVisitor()
        s = PP(Preposition('for'), NP('your', 'life'))
        expected = [Word('for', 'PREPOSITION'),
                    Word('your', 'DETERMINER'),
                    Word('life', 'NOUN')]
        s.accept(v)
        actual = v.elements
        self.assertEqual(expected, actual)

    def test_adjp(self):
        v = ElementVisitor()
        s = AdjP(Adjective('happy'), Noun('life'))
        expected = [Word('happy', 'ADJECTIVE'),
                    Word('life', 'NOUN')]
        s.accept(v)
        actual = v.elements
        self.assertEqual(expected, actual)

    def test_advp(self):
        v = ElementVisitor()
        s = AdvP(Adverb('gently'), Verb('run'))
        expected = [Word('gently', 'ADVERB'),
                    Word('run', 'VERB')]
        s.accept(v)
        actual = v.elements
        self.assertEqual(expected, actual)

    def test_coordination(self):
        v = ElementVisitor()
        s = AdvP(Adverb('gently'), Verb('run'))
        expected = [Word('gently', 'ADVERB'),
                    Word('run', 'VERB')]
        s.accept(v)
        actual = v.elements
        self.assertEqual(expected, actual)

if __name__ == '__main__':
    unittest.main()


text:
package io.quarkus.platform.catalog.processor;

import static io.quarkus.registry.catalog.Category.MD_PINNED;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import io.quarkus.registry.catalog.Category;
import io.quarkus.registry.catalog.Extension;

public final class ProcessedCategory {
    private final Category category;
    private final Collection<Extension> extensions;

    public ProcessedCategory(Category category, Collection<Extension> extensions) {
        this.category = Objects.requireNonNull(category);
        this.extensions = Objects.requireNonNull(extensions);
    }

    public Category getCategory() {
        return category;
    }

    public Collection<Extension> getExtensions() {
        return extensions;
    }

    public List<Extension> getSortedExtensions() {
        return extensions.stream().sorted(extensionsComparator()).collect(Collectors.toList());
    }

    private Comparator<Extension> extensionsComparator() {
        final List<String> pinnedList = MetadataValue.get(category.getMetadata(), MD_PINNED).asStringList();
        return Comparator.<Extension> comparingInt(e -> getPinnedIndex(pinnedList, e))
                .thenComparing(Extension::getName, String.CASE_INSENSITIVE_ORDER);
    }

    private int getPinnedIndex(List<String> pinnedList, Extension e) {
        final int index = pinnedList.indexOf(e.managementKey());
        return index >= 0 ? index : Integer.MAX_VALUE;
    }

}


text:
import * as React from "react";
import { i18n } from "i18next";

// tslint:disable-next-line:interface-name
export interface I18nextProviderProps {
    i18n: i18n;
    initialI18nStore?: any;
    initialLanguage?: string;
    children: React.ReactNode;
}

export default class I18nextProvider extends React.Component<I18nextProviderProps> { }


text:
//
//  DSYGroupCellView.h
//  MiniPlayer
//
//  Created by Syed Haris Ali on 3/5/14.
//  Copyright (c) 2014 Beats Music. All rights reserved.
//

#import <Cocoa/Cocoa.h>

/**
 The DSYGroupCellView, a subclass of the NSTableCellView, provides a custom tableview cell with a titleLabel as a DSYTextField for custom font loading.
 */
@interface DSYGroupCellView : NSTableCellView

#pragma mark - Properties
///-----------------------------------------------------------
/// @name Properties
///-----------------------------------------------------------

/**
 The DSYTextField used to display the title label.
 */
@property (nonatomic,weak) IBOutlet DSYTextField *titleLabel;

@end


text:
TransactionalSet
================

.. automodule:: hazelcast.proxy.transactional_set


text:
DateTime.Field = {};
// These are ints not enumerations as they represent genuine int values
/** Constant (0) representing AM, the morning (from Calendar) */
DateTime.Field.AM = 0;
/** Constant (1) representing PM, the afternoon (from Calendar) */
DateTime.Field.PM = 1;
/** Constant (0) representing BC, years before zero (from Calendar) */
DateTime.Field.BC = 0;
/** Alternative constant (0) representing BCE, Before Common Era (secular) */
DateTime.Field.BCE = 0;
/**
 * Constant (1) representing AD, years after zero (from Calendar).
 *

 * All new chronologies with differrent Era values should try to assign
 * eras as follows. The era that was in force at 1970-01-01 (ISO) is assigned
 * the value 1. Earlier eras are assigned sequentially smaller numbers.
 * Later eras are assigned sequentially greater numbers.
 */
DateTime.Field.AD = 1;
/**
 * Alternative constant (1) representing CE, Common Era (secular).
 *

 * All new chronologies with differrent Era values should try to assign
 * eras as follows. The era that was in force at 1970-01-01 (ISO) is assigned
 * the value 1. Earlier eras are assigned sequentially smaller numbers.
 * Later eras are assigned sequentially greater numbers.
 */
DateTime.Field.CE = 1;


text:
unibabel-js
=====

Moved to https://git.daplie.com/Daplie/unibabel-js


text:
package fredboat.util.rest;

import fredboat.commandmeta.MessagingException;

public class APILimitException extends MessagingException {

    public APILimitException(String string) {
        super(string);
    }
}


text:
<?php

namespace FOS\GoogleBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;

class FOSGoogleExtension extends Extension
{
    protected $resources = array(
        'google' => 'google.xml',
        'security' => 'security.xml'
    );

    public function load(array $configs, ContainerBuilder $container)
    {
        $processor = new Processor();
        $configuration = new Configuration();
        $config = $processor->processConfiguration($configuration, $configs);

        $this->loadDefaults($container);

        if (isset($config['alias'])) {
            $container->setAlias($config['alias'], 'fos_google.api');
        }

        foreach (array('api', 'helper', 'twig') as $attribute) {
            $container->setParameter('fos_google.'.$attribute.'.class', $config['class'][$attribute]);
        }

        foreach (array('app_name', 'client_id', 'client_secret', 'redirect_uri', 'state', 'access_type', 'approval_prompt', 'scopes') as $attribute) {
            $container->setParameter('fos_google.'.$attribute, $config[$attribute]);
        }
    }

    /**
     * @codeCoverageIgnore
     */
    public function getXsdValidationBasePath()
    {
        return __DIR__ . '/../Resources/config/schema';
    }

    /**
     * @codeCoverageIgnore
     */
    public function getNamespace()
    {
        return 'http://symfony.com/schema/dic/fos_google';
    }

    /**
     * @codeCoverageIgnore
     */
    protected function loadDefaults($container)
    {
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));

        foreach ($this->resources as $resource) {
            $loader->load($resource);
        }
    }
}


text:
var scriptStartTime = new Date();

var cursor = db.users.find({
    $and: [
    {anonymous: false},
    {schoolName: {$exists: true}},
    {schoolName: {$ne: ''}}
    ]
}, {schoolName: 1});

var schoolCountMap = {};
while (cursor.hasNext()) {
    var doc = cursor.next();
    if (!schoolCountMap[doc.schoolName]) schoolCountMap[doc.schoolName] = 0;
    schoolCountMap[doc.schoolName]++;
}

var schoolCounts = [];
for (var schoolName in schoolCountMap) {
  schoolCounts.push({schoolName: schoolName, count: schoolCountMap[schoolName]});
}
schoolCounts.sort(function(a, b) {
  if (a.count > b.count) return -1;
  else if (a.count === b.count) return 0;
  return 1;
});

var count = 0;
for (var i = 0; i < schoolCounts.length; i++) {
  if (schoolCounts[i].count >= 2) {
    print(++count, '\t', schoolCounts[i].count, schoolCounts[i].schoolName);
  }
}

log("Script runtime: " + (new Date() - scriptStartTime));

function log(str) {
  print(new Date().toISOString() + " " + str);
}


text:
#ifndef _MEASUREMENT_H
#define _MEASUREMENT_H

#define SOS_MEASUREMENT_IDLE_START()
#define SOS_MEASUREMENT_IDLE_END()

#define SOS_MEASUREMENT_DEQUEUE_START()
#define SOS_MEASUREMENT_DEQUEUE_END()

#define SOS_MEASUREMENT_MALLOC_START()
#define SOS_MEASUREMENT_MALLOC_END()

#endif /* #ifndef _MEASUREMENT_H */


text:
module GrafikaApp {
    export module Drawing {
        export module Directives {

            export class ImageUploadOptions {
                previewWidth: number;
                previewHeight: number;
                actualWidth: number;
                actualHeight: number;
                onUpload: (data: Models.IImageData | any) => ng.IPromise<any>;
                onClosed: () => void;
            }

            export class ImageUploaderDirective implements ng.IDirective {
                restrict = 'A';
                scope = {
                    previewWidth: '=',
                    previewHeight: '=',
                    actualWidth: '=',
                    actualHeight: '=',
                    onUpload: '&',
                    onClosed: '&'
                };
                link = (scope: ng.IScope, elem: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctr: any) => {
                    elem.bind('click', (evt) => {
                        let useFullScreen: boolean = (this.appCommon.$mdMedia('sm') || this.appCommon.$mdMedia('xs'));
                        this.appCommon.$mdDialog.show({
                            fullscreen: useFullScreen,
                            controller: ImageUploaderController,
                            controllerAs: 'vm',
                            parent: angular.element(document.body),
                            templateUrl: '/js/drawing/GrafikaApp.Drawing.Directives.ImageUploaderDirective.html',
                            locals: { uploadOptions: scope }
                        });
                    });
                    /*

                        fullscreen: useFullScreen,
                        controller: controller,
                        controllerAs: controllerAs,
                        parent: angular.element(document.body),
                        templateUrl: templateUrl,
                        clickOutsideToClose: true,
                        targetEvent: event
                    */
                };

                constructor(private appCommon: AppCommon) {
                }

                static factory(): ng.IDirectiveFactory {
                    const directive = (appCommon: AppCommon) => new ImageUploaderDirective(appCommon);
                    directive.$inject = ['appCommon'];
                    return directive;
                }
            }

            function ImageUploaderController(scope: ng.IScope, appCommon: AppCommon, uploadOptions: ImageUploadOptions) {
                let vm: any = this;

                vm.message = '';
                vm.preview = (evt) => {
                    vm.uploading = true;
                    let fileReader = new FileReader();
                    let file = (<HTMLInputElement>$('#image-file')[0]).files[0];
                    fileReader.onload = () => {
                        if (!file) return;
                        vm.message = 'Resizing...';
                        let canvas: HTMLCanvasElement = <HTMLCanvasElement>$('#image-canvas')[0];
                        let context = canvas.getContext('2d');
                        let canvasWidth: number = $('#image-canvas').width();
                        let canvasHeight: number = $('#image-canvas').height();
                        let img = new Image();
                        img.onload = () => {
                            context.drawImage(img, 0, 0, canvasWidth, canvasHeight);
                            let data = new Models.ImageData(file.name, file.size, file.type, () => getCanvasBlob());
                            vm.upload(data);
                        };
                        if (!img.src) {
                            img.src = fileReader.result;
                        }
                    };
                    fileReader.readAsDataURL(file);
                };
                vm.upload = (imageData: ImageData) => {
                    vm.message = 'Uploading...';
                    vm.uploading = false;
                    return uploadOptions.onUpload({ $imageData: imageData })
                        .then(() => vm.message = 'Successfully uploaded')
                        .catch((err) => vm.message = 'Unable to upload. ' + appCommon.formatErrorMessage(err))
                        .finally(() => vm.uploading = false);
                };
                vm.close = () => {
                    if (uploadOptions.onClosed) uploadOptions.onClosed();
                    appCommon.$mdDialog.hide();
                };

                function initialize() {
                    appCommon.$log.log('Checking canvas', null, 'image-uploader');
                    if ($('#image-canvas').length == 0) return;

                    $('#image-canvas').attr('width', uploadOptions.actualWidth)
                        .attr('height', uploadOptions.actualHeight)
                        .css('width', uploadOptions.previewWidth)
                        .css('height', uploadOptions.previewHeight);
                    appCommon.$interval.cancel(checkCanvas);
                    checkCanvas = undefined;
                    vm.canvasReady = true;
                };

                function getCanvasBlob() {
                    let canvas: HTMLCanvasElement = <HTMLCanvasElement>$('#image-canvas')[0];
                    let binary = atob(canvas.toDataURL("image/png", 100).split(',')[1]);
                    let array = [];
                    for (let i = 0; i < binary.length; i++) {
                        array.push(binary.charCodeAt(i));
                    }
                    return new Blob([new Uint8Array(array)], { type: 'image/png' });
                }

                // wait for canvas to initialized
                let checkCanvas = appCommon.$interval(initialize, 1000);
            }
        }
    }
}


text:
Template.ticketTable.onCreated(function(){
  this.subscribe("allTickets");
});

Template.ticketTable.helpers({
  tickets: function(){
    return Tickets.find({
        },{
          sort: {
            timestamp: -1
          }
        }

    );
  },
  rowClass: function(){
    if (this.status === "COMPLETE") return "positive";
    if (this.status === "CANCELLED") return "negative";
    if (this.status === "CLAIMED") return "active";
    if (this.status === "EXPIRED") return "warning";
  }
});

Template.ticketTable.events({
  'click .delete': function(){
    Meteor.call('deleteTicket', this._id);
  }
});


text:
import {TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';

import {encodeStringToBase64} from '../../../lib/api_translation/primitive';
import {FlowState} from '../../../lib/models/flow';
import {newFlow} from '../../../lib/models/model_test_util';
import {initTestEnvironment} from '../../../testing';

import {PluginsModule} from './module';
import {TimelineDetails} from './timeline_details';

initTestEnvironment();

describe('timeline-details component', () => {
  beforeEach(waitForAsync(() => {
    TestBed
        .configureTestingModule({
          imports: [
            PluginsModule,
          ],
          teardown: {destroyAfterEach: false}
        })
        .compileComponents();
  }));

  it('should display a download button when the flow is finished', () => {
    const fixture = TestBed.createComponent(TimelineDetails);
    fixture.componentInstance.flow = newFlow({
      name: 'TimelineFlow',
      clientId: 'C.1234',
      flowId: 'ABCDEF',
      state: FlowState.FINISHED,
      args: {
        root: encodeStringToBase64('/'),
      },
    });
    fixture.detectChanges();

    const button = fixture.debugElement.query(
        By.css('.download.flow-details-summary-actions > a'));
    expect(button.nativeElement.innerText).toBe('Download body');

    const url = new URL(button.properties['href']);
    expect(url.pathname).toContain('C.1234');
    expect(url.pathname).toContain('ABCDEF');

    expect(button.properties['download']).toContain('.body');
    expect(button.properties['download']).toContain('1234');
    expect(button.properties['download']).toContain('ABCDEF');
  });

  it('should allow customizing output format of the body export', () => {
    const fixture = TestBed.createComponent(TimelineDetails);

    fixture.componentInstance.flow = newFlow({
      name: 'TimelineFlow',
      clientId: 'C.1234',
      flowId: 'ABCDEF',
      state: FlowState.FINISHED,
      args: {
        root: encodeStringToBase64('/'),
      },
    });
    fixture.detectChanges();

    fixture.componentInstance.bodyOptsForm.setValue({
      timestampSubsecondPrecision: false,
      inodeNtfsFileReferenceFormat: true,
      backslashEscape: true,
      carriageReturnEscape: true,
      nonPrintableEscape: true,
    });
    fixture.detectChanges();

    const button = fixture.debugElement.query(
        By.css('.download.flow-details-summary-actions > a'));

    const params = new URL(button.properties['href']).searchParams;
    expect(params.get('body_opts.timestamp_subsecond_precision')).toBe('0');
    expect(params.get('body_opts.inode_ntfs_file_reference_format')).toBe('1');
    expect(params.get('body_opts.backslash_escape')).toBe('1');
    expect(params.get('body_opts.carriage_return_escape')).toBe('1');
    expect(params.get('body_opts.non_printable_escape')).toBe('1');
  });

  it('should display the root path when the flow is still running', () => {
    const fixture = TestBed.createComponent(TimelineDetails);
    fixture.componentInstance.flow = newFlow({
      name: 'TimelineFlow',
      state: FlowState.RUNNING,
      args: {
        root: encodeStringToBase64('/foo/bar/baz'),
      },
    });
    fixture.detectChanges();

    expect(fixture.nativeElement.innerText).toContain('/foo/bar/baz');
  });
});


text:
using BenchmarkDotNet.Running;

namespace Pfim.Benchmarks
{
    class Program
    {
        static void Main(string[] args)
        {
            BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);
        }
    }
}


text:
from flask_wtf import Form
from wtforms import TextField, SelectField
from wtforms.validators import ValidationError, DataRequired, Length

from rpihelper.services.logic import SystemctlCommands, get_services

__all__ = (
    'ServicesForm',
)

class ServicesForm(Form):
    service = TextField('Service name', validators=(
        DataRequired(),
        Length(min=1, max=20),
    ))
    command = SelectField('Command', choices=(
        (SystemctlCommands.START, 'Start',),
        (SystemctlCommands.STOP, 'Stop',),
        (SystemctlCommands.RESTART, 'Restart',),
    ))

    def validate_service(form, field):
        services_names = [
            service['name'] for service in get_services()
        ]

        if field.data not in services_names:
            raise ValidationError('Unknown service name')


text:
local desc = fs.read(path.expand("$sd/../../dump.desc.json"))
local patch = fs.read(path.expand("$sd/../../dump.desc-patch.json"))
desc:Patch(patch)
local Enum = desc:EnumTypes()

-- Test XML without descriptors.
local d = fs.read(path.expand("$sd/decal.rbxmx")):Descend("Decal")
local p = d[sym.Properties]

T.Pass(rbxmk.propType(d, "AttributesSerialize") == "BinaryString", "xml instance AttributesSerialize type")
T.Pass(rbxmk.propType(d, "Color3") == "Color3", "xml instance Color3 type")
T.Pass(rbxmk.propType(d, "Face") == "token", "xml instance Face type")
T.Pass(rbxmk.propType(d, "Name") == "string", "xml instance Name type")
T.Pass(rbxmk.propType(d, "SourceAssetId") == "int64", "xml instance SourceAssetId type")
T.Pass(rbxmk.propType(d, "Tags") == "BinaryString", "xml instance Tags type")
T.Pass(rbxmk.propType(d, "Texture") == "Content", "xml instance Texture type")
T.Pass(rbxmk.propType(d, "Transparency") == "float", "xml instance Transparency type")

T.Pass(typeof(p.AttributesSerialize) == "string", "xml table AttributesSerialize type")
T.Pass(typeof(p.Color3) == "Color3", "xml table Color3 type")
T.Pass(typeof(p.Face) == "number", "xml table Face type")
T.Pass(typeof(p.Name) == "string", "xml table Name type")
T.Pass(typeof(p.SourceAssetId) == "number", "xml table SourceAssetId type")
T.Pass(typeof(p.Tags) == "string", "xml table Tags type")
T.Pass(typeof(p.Texture) == "string", "xml table Texture type")
T.Pass(typeof(p.Transparency) == "number", "xml table Transparency type")

T.Pass(p.AttributesSerialize == "", "xml AttributesSerialize value")
T.Pass(p.Color3 == Color3.new(1,1,1), "xml Color3 value")
T.Pass(p.Face == 1, "xml Face value")
T.Pass(p.Name == "Decal", "xml Name value")
T.Pass(p.SourceAssetId == -1, "xml SourceAssetId value")
T.Pass(p.Tags == "", "xml Tags value")
T.Pass(p.Texture == "rbxasset://textures/SpawnLocation.png", "xml Texture value")
T.Pass(p.Transparency == 0, "xml Transparency value")

-- Test XML with descriptors.
d[sym.Desc] = desc
local p = d[sym.Properties]

T.Pass(typeof(p.AttributesSerialize) == "string", "xml desc table AttributesSerialize type")
T.Pass(typeof(p.Color3) == "Color3", "xml desc table Color3 type")
T.Pass(typeof(p.Face) == "EnumItem", "xml desc table Face type")
T.Pass(typeof(p.Name) == "string", "xml desc table Name type")
T.Pass(typeof(p.SourceAssetId) == "number", "xml desc table SourceAssetId type")
T.Pass(typeof(p.Tags) == "string", "xml desc table Tags type")
T.Pass(typeof(p.Texture) == "string", "xml desc table Texture type")
T.Pass(typeof(p.Transparency) == "number", "xml desc table Transparency type")

T.Pass(p.AttributesSerialize == "", "xml desc AttributesSerialize value")
T.Pass(p.Color3 == Color3.new(1,1,1), "xml desc Color3 value")
T.Pass(p.Face == Enum.NormalId.Top, "xml desc Face value")
T.Pass(p.Name == "Decal", "xml desc Name value")
T.Pass(p.SourceAssetId == -1, "xml desc SourceAssetId value")
T.Pass(p.Tags == "", "xml desc Tags value")
T.Pass(p.Texture == "rbxasset://textures/SpawnLocation.png", "xml desc Texture value")
T.Pass(p.Transparency == 0, "xml desc Transparency value")

-- Test binary without descriptors.
local d = fs.read(path.expand("$sd/decal.rbxm")):Descend("Decal")
local p = d[sym.Properties]

-- Binary encodes string-likes as string type.
T.Pass(rbxmk.propType(d,"AttributesSerialize") == "string", "binary instance AttributesSerialize type")
T.Pass(rbxmk.propType(d,"Color3") == "Color3", "binary instance Color3 type")
T.Pass(rbxmk.propType(d,"Face") == "token", "binary instance Face type")
T.Pass(rbxmk.propType(d,"Name") == "string", "binary instance Name type")
T.Pass(rbxmk.propType(d,"SourceAssetId") == "int64", "binary instance SourceAssetId type")
T.Pass(rbxmk.propType(d,"Tags") == "string", "binary instance Tags type")
T.Pass(rbxmk.propType(d,"Texture") == "string", "binary instance Texture type")
T.Pass(rbxmk.propType(d,"Transparency") == "float", "binary instance Transparency type")

T.Pass(typeof(p.AttributesSerialize) == "string", "binary table AttributesSerialize type")
T.Pass(typeof(p.Color3) == "Color3", "binary table Color3 type")
T.Pass(typeof(p.Face) == "number", "binary table Face type")
T.Pass(typeof(p.Name) == "string", "binary table Name type")
T.Pass(typeof(p.SourceAssetId) == "number", "binary table SourceAssetId type")
T.Pass(typeof(p.Tags) == "string", "binary table Tags type")
T.Pass(typeof(p.Texture) == "string", "binary table Texture type")
T.Pass(typeof(p.Transparency) == "number", "binary table Transparency type")

T.Pass(p.AttributesSerialize == "", "binary AttributesSerialize value")
T.Pass(p.Color3 == Color3.new(1,1,1), "binary Color3 value")
T.Pass(p.Face == 1, "binary Face value")
T.Pass(p.Name == "Decal", "binary Name value")
T.Pass(p.SourceAssetId == -1, "binary SourceAssetId value")
T.Pass(p.Tags == "", "binary Tags value")
T.Pass(p.Texture == "rbxasset://textures/SpawnLocation.png", "binary Texture value")
T.Pass(p.Transparency == 0, "binary Transparency value")

-- Test binary with descriptors.
d[sym.Desc] = desc
local p = d[sym.Properties]
-- for k,v in pairs(p) do print(k,typeof(v),v) end

T.Pass(typeof(p.AttributesSerialize) == "string", "binary desc table AttributesSerialize type")
T.Pass(typeof(p.Color3) == "Color3", "binary desc table Color3 type")
T.Pass(typeof(p.Face) == "EnumItem", "binary desc table Face type")
T.Pass(typeof(p.Name) == "string", "binary desc table Name type")
T.Pass(typeof(p.SourceAssetId) == "number", "binary desc table SourceAssetId type")
T.Pass(typeof(p.Tags) == "string", "binary desc table Tags type")
T.Pass(typeof(p.Texture) == "string", "binary desc table Texture type")
T.Pass(typeof(p.Transparency) == "number", "binary desc table Transparency type")

T.Pass(p.AttributesSerialize == "", "binary desc AttributesSerialize value")
T.Pass(p.Color3 == Color3.new(1,1,1), "binary desc Color3 value")
T.Pass(p.Face == Enum.NormalId.Top, "binary desc Face value")
T.Pass(p.Name == "Decal", "binary desc Name value")
T.Pass(p.SourceAssetId == -1, "binary desc SourceAssetId value")
T.Pass(p.Tags == "", "binary desc Tags value")
T.Pass(p.Texture == "rbxasset://textures/SpawnLocation.png", "binary desc Texture value")
T.Pass(p.Transparency == 0, "binary desc Transparency value")