text:
  <mediawiki xml:lang="en">
    <page>
      <title>Page title</title>
      <restrictions>edit=sysop:move=sysop</restrictions>
      <revision>
        <timestamp>2001-01-15T13:15:00Z</timestamp>
        <contributor><username>Foobar</username></contributor>
        <comment>I have just one thing to say!</comment>
        <text>A bunch of [[text]] here.</text>
        <minor />
      </revision>
      <revision>
        <timestamp>2001-01-15T13:10:27Z</timestamp>
        <contributor><ip>10.0.0.2</ip></contributor>
        <comment>new!</comment>
        <text>An earlier [[revision]].</text>
      </revision>
    </page>

    <page>
      <title>Talk:Page title</title>
      <revision>
        <timestamp>2001-01-15T14:03:00Z</timestamp>
        <contributor><ip>10.0.0.2</ip></contributor>
        <comment>hey</comment>
        <text>WHYD YOU LOCK PAGE??!!! i was editing that jerk</text>
      </revision>
    </page>
  </mediawiki>


text:
<?php

declare(strict_types=1);

namespace Psi\Component\ContentType\Standard\View;

use Psi\Component\ContentType\View\TypeInterface;
use Psi\Component\ContentType\View\View;
use Psi\Component\ContentType\View\ViewFactory;
use Psi\Component\ContentType\View\ViewInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UrlType implements TypeInterface
{
    public function createView(ViewFactory $factory, $data, array $options): ViewInterface
    {
        if (null !== $data && !is_string($data)) {
            throw new \InvalidArgumentException(sprintf(
                'URL view only accepts string values! Got "%s"',
                is_object($data) ? get_class($data) : gettype($data)
            ));
        }

        return new UrlView($data);
    }

    public function configureOptions(OptionsResolver $options)
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
{{'PROJECT.PROJECTS' | translate}}

                <statistics-panel></statistics-panel>

                    <select (change)="doFilterProjects()" [(ngModel)]="selecteType">
                        <option value="0" [selected]="currentFilteredType === 0">{{projectTypes[0] | translate}}</option>
                        <option value="1">{{projectTypes[1] | translate}}</option>
                        <option value="2">{{projectTypes[2] | translate}}</option>
                    </select>

                <hbr-filter [withDivider]="true" filterPlaceholder='{{"PROJECT.FILTER_PLACEHOLDER" | translate}}'
                    [currentValue]="projectName"></hbr-filter>

                    <clr-icon shape="refresh"></clr-icon>

        <create-project (create)="createProject($event)" [quotaObj]="quotaObj" [isSystemAdmin]="isSystemAdmin"></create-project>
        <list-project (addProject)="openModal()"></list-project>


text:
package com.amazonaws.services.redshift.model;

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * Cross-region snapshot copy was temporarily disabled. Try your request
 * again.
 * </p>
 */
public class SnapshotCopyDisabledException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new SnapshotCopyDisabledException with the specified error
     * message.
     *
     * @param message Describes the error encountered.
     */
    public SnapshotCopyDisabledException(String message) {
        super(message);
    }

}


text:
package com.bitdubai.fermat_core.layer.dap_identity;

import com.bitdubai.fermat_api.Plugin;
import com.bitdubai.fermat_api.layer.CantStartLayerException;
import com.bitdubai.fermat_api.layer.PlatformLayer;
import com.bitdubai.fermat_core.layer.dap_identity.asset_issuer.AssetIssuerIdentitySubsystem;
import com.bitdubai.fermat_core.layer.dap_identity.asset_user.AssetUserIdentitySubsystem;
import com.bitdubai.fermat_core.layer.dap_identity.redeem_point.RedeemPointIdentitySubsystem;
import com.bitdubai.fermat_dap_api.layer.dap_identity.CantStartSubsystemException;
import com.bitdubai.fermat_dap_api.layer.dap_identity.DAPIdentitySubsystem;

/**
 * Created by Nerio on 10/09/15.
 */
public class DAPIdentityLayer implements PlatformLayer {

    private Plugin assetIssuerIdentity;

    private Plugin assetUserIdentity;

    private Plugin redeemPointIdentity;
    /**
     * Each layer is started and by that time has the chance to initialize its services.
     */
    @Override
    public void start() throws CantStartLayerException {

        assetUserIdentity = getPlugin(new AssetIssuerIdentitySubsystem());

        assetIssuerIdentity = getPlugin(new AssetUserIdentitySubsystem());

        redeemPointIdentity = getPlugin(new RedeemPointIdentitySubsystem());
    }

    private Plugin getPlugin(DAPIdentitySubsystem dapIdentitySubsystem) throws CantStartLayerException {
        try {
            dapIdentitySubsystem.start();
            return dapIdentitySubsystem.getPlugin();
        } catch (CantStartSubsystemException exception) {
            throw new CantStartLayerException();
        }
    }

    public Plugin getAssetIssuerIdentity() {
        return assetIssuerIdentity;
    }

    public Plugin getAssetUserIdentity() {return assetUserIdentity;}

    public Plugin getRedeemPointIdentity() {
        return redeemPointIdentity;
    }
}


text:
//META{"name":"kawaiiemotes"}*//

/*@cc_on
@if (@_jscript)
    // Offer to self-install for clueless users that try to run this directly.
    var shell = WScript.CreateObject("WScript.Shell");
    var fs = new ActiveXObject("Scripting.FileSystemObject");
    var pathPlugins = shell.ExpandEnvironmentStrings("%APPDATA%\\BetterDiscord\\plugins");
    var pathSelf = WScript.ScriptFullName;
    // Put the user at ease by addressing them in the first person
    shell.Popup("It looks like you mistakenly tried to run me directly. (don't do that!)", 0, "I'm a plugin for BetterDiscord", 0x30);
    if (fs.GetParentFolderName(pathSelf) === fs.GetAbsolutePathName(pathPlugins)) {
        shell.Popup("I'm in the correct folder already.\nJust reload Discord with Ctrl+R.", 0, "I'm already installed", 0x40);
    } else if (!fs.FolderExists(pathPlugins)) {
        shell.Popup("I can't find the BetterDiscord plugins folder.\nAre you sure it's even installed?", 0, "Can't install myself", 0x10);
    } else if (shell.Popup("Should I copy myself to BetterDiscord's plugins folder for you?", 0, "Do you need some help?", 0x34) === 6) {
        fs.CopyFile(pathSelf, fs.BuildPath(pathPlugins, fs.GetFileName(pathSelf)), true);
        // Show the user where to put plugins in the future
        shell.Exec("explorer " + pathPlugins);
        shell.Popup("I'm installed!\nJust reload Discord with Ctrl+R.", 0, "Successfully installed", 0x40);
    }
    WScript.Quit();
@else @*/

var kawaiiemotes = function () {};

(function () {
    "use strict";

    // Emote data
    function EmoteSet() {
        this.emoteMap = new Map();
        this.template = "";
        this.caseSensitive = true;
        this.emoteStyle = EmoteSet.emoteStyle.STANDARD;
        this.loaded = false;
    };
    // emoteStyle enum
    EmoteSet.emoteStyle = {
        STANDARD: 0, // Surrounded by ":"
        TWITCH: 1, // Composed of "word characters" (\w)
    };
    // template field names enum
    EmoteSet.templateField = {
        PATH: 0, // The unique path component for this emote name
        SIZE: 1, // emote size, usually a single digit between 1 and 4
    };
    EmoteSet.prototype.load = function(){};
    EmoteSet.prototype.getUrl = function (emoteName) {
        if (!this.caseSensitive) {
            emoteName = emoteName.toLowerCase();
        }
        var path = this.emoteMap.get(emoteName);
        if (path === undefined) {
            return undefined;
        }
        return this.template.replace(/{(\d+)}/g, function (match, field) {
            switch (Number(field)) {
                case EmoteSet.templateField.PATH:
                    return path;
                case EmoteSet.templateField.SIZE:
                    return "1";
                default:
                    return match;
            }
        });
    };
    // Create and return an emote element, or undefined if no match found
    EmoteSet.prototype.createEmote = function (emoteName, options) {
        options = $.extend({allowWide: false}, options);

        var emoteURL = this.getUrl(emoteName);
        if (emoteURL === undefined) {
            return undefined;
        }
        if (this.emoteStyle === EmoteSet.emoteStyle.STANDARD) {
            emoteName = ":"+emoteName+":";
        }
        var emote = $("<img>", {
            src: emoteURL,
            alt: emoteName,
            title: emoteName,
            "class": "emoji kawaii-parseemotes",
        }).attr("draggable", "false");

        // Show a fake favorite button
        emote.css("cursor", "pointer");
        emote.on("mouseover.kawaiiFavorite", function () {
            // Create and insert favorite button
            var fav = $("<div>").addClass("fav")
                .css("display", "block")
                .css("pointer-events", "none")
                .appendTo($(".tooltips"));

            // Position the button
            var position = emote.offset();
            position.top -= fav.height()/2;
            position.left += emote.width() - fav.width()/2;
            fav.offset(position);

            // Set a handler to destroy the button
            emote.on("mouseout.kawaiiFavorite", function () {
                // remove this handler
                emote.off("mouseout.kawaiiFavorite");
                fav.remove();
            });
        });

        emote.on("click.kawaiiFavorite", function () {
            quickEmoteMenu.favorite(emoteName, emoteURL);
        });
        if (options.allowWide) {
            emote.on("load.kawaiiWideEmote", function () {
                var wide = this.naturalWidth > this.naturalHeight;
                $(this).css("width", wide ? "auto" : "");
            });
        }
        return emote;
    };
    EmoteSet.prototype.search = function (query) {
        const score = function (name, query) {
            name = name.toLowerCase();
            query = query.toLowerCase();
            const d = name.length - query.length;
            const i = name.indexOf(query);
            if (i === -1) {
                return 0;
            }
            return 1 + (i+1)*(d-i+2);
        };
        return [...this.emoteMap.keys()]
            .map(e => [e, score(e, query)])
            .filter(e => e[1] !== 0);
    };

    function getCompletionsStandard(emoteSets, text) {
        const match = text.match(/(^|\s):(\w{2,})$/);
        if (match === null) {
            return {completions: [], matchText: null, matchStart: -1};
        }

        const completions = emoteSets
            .filter(s => s.emoteStyle === EmoteSet.emoteStyle.STANDARD)
            .map(s => s.search(match[2]).map(e => [[":"+e[0]+":", s.createEmote.bind(s, e[0])], e[1]]))
            .reduce((a,b) => a.concat(b), []);
        const matchText = ":"+match[2], matchStart = match.index + match[1].length;

        return {completions, matchText, matchStart};
    }

    function getCompletionsTwitch(emoteSets, text) {
        const match = text.match(/(^|\s)(\w{3,})$/);
        if (match === null) {
            return {completions: [], matchText: null, matchStart: -1};
        }

        const completions = emoteSets
            .filter(s => s.emoteStyle === EmoteSet.emoteStyle.TWITCH)
            .map(s => s.search(match[2])
                    .filter(e => $.inArray(e[0], bemotes) === -1)
                    .map(e => [[e[0], s.createEmote.bind(s, e[0])], e[1]])
                    )
            .reduce((a,b) => a.concat(b), []);
        const matchText = match[2], matchStart = match.index + match[1].length;

        return {completions, matchText, matchStart};
    }

    const emoteComparator = (function () {
        const compare = new Intl.Collator(undefined, {
            usage: "sort",
            sensitivity: "base",
            numeric: true,
        }).compare;

        return (a,b) => ((a[1]===b[1]) ? compare(a[0],b[0]) : (a[1]-b[1]));
    })();

    function getCompletions(emoteSets, text) {
        let {completions, matchText, matchStart} = getCompletionsStandard(emoteSets, text);
        if (matchStart === -1) {
            ({completions, matchText, matchStart} = getCompletionsTwitch(emoteSets, text));
        }

        completions = completions
            .sort(emoteComparator)
            .map(e => e[0]);

        return {completions, matchText, matchStart};
    }

    // Set up event handlers
    function startTabComplete(emoteSets, options={}) {
        // Cached information about possible completions
        // Conflicts should be avoidable, as this is cleared on focus loss
        let cached = {};

        let textarea;

        const {
            completionsMenu: showMenu=true,
            completionsDelay: delay=250,
            completionsWindowSize: windowSize=10,
            completionsPreScroll: preScroll=2
        } = options;

        if (!showMenu) {
            return;
        }

        const shouldCompleteStandard = RegExp.prototype.test.bind(/(?:^|\s):\w{2,}$/);

        const shouldCompleteTwitch = RegExp.prototype.test.bind(/(?:^|\s)\w{3,}$/);

        const shouldComplete = RegExp.prototype.test.bind(/(?:^|\s)(?:\w|:)\w{2,}$/);

        // Show possible completions
        let renderCompletions = _.debounce(function () {
            const channelTextarea = $(textarea).closest(".channelTextArea-1LDbYG > .inner-zqa7da");
            const oldAutocomplete = channelTextarea.children(".kawaii-autocomplete");

            const candidateText = textarea.value.slice(0, textarea.selectionEnd);
            if (!shouldCompleteTwitch(candidateText) || !prepareCompletions()) {
                oldAutocomplete.remove();
                return;
            }

            const {completions, matchText, selectedIndex, windowOffset: firstIndex} = cached;

            const matchList = completions.slice(firstIndex, firstIndex+windowSize);

            const autocomplete = $("<div>")
                .addClass("autocomplete-i9yVHs autocomplete-1vrmpx kawaii-autocomplete")
                .on("wheel.kawaii-complete", e => scrollCompletions(e, {locked: true}));
            // FIXME: clean up this mess of jQuery
            $("<div>", {"class": "autocompleteRowVertical-q1K4ky autocompleteRow-2OthDa"})
                .append($("<div>", {"class": "selector-2IcQBU"})
                    .append($("<div>", {text: "Emotes matching "}).append($("<strong>", {text: matchText}))
                        .addClass("contentTitle-2tG_sM primary400-hm0Rav weightBold-2yjlgw")))
                .appendTo(autocomplete);
            autocomplete
                .append(matchList.map((e,i) => {
                    let row = $("<div>", {"class": "autocompleteRowVertical-q1K4ky autocompleteRow-2OthDa"});
                    let selector = $("<div>", {"class": "selector-2IcQBU selectable-x8iAUj"})
                        .append($("<div>")
                            .addClass("flex-lFgbSz flex-1O1GKY horizontal-3Sq5iO horizontal-2VE-Fw flex-1O1GKY directionRow-3v3tfG justifyStart-2NDFzi alignCenter-1dQNNs noWrap-vaXJ4Y content-3JfFJh")
                            .css("flex", "1 1 auto")
                            .append(e[1]().toggleClass("emoji icon-17zDF5"))
                            .append($("<div>", {"class": "marginLeft8-1YseBe", text: e[0]})))
                        .appendTo(row);
                    if (i+firstIndex === selectedIndex) {
                        selector.addClass("selectorSelected-1_M1WV");
                    }
                    row.on("mouseenter.kawaii-complete", e => {
                        cached.selectedIndex = i+firstIndex;
                        row.siblings().children(".selectorSelected-1_M1WV").removeClass("selectorSelected-1_M1WV");
                        row.children().addClass("selectorSelected-1_M1WV");
                    }).on("mousedown.kawaii-complete", e => {
                        cached.selectedIndex = i+firstIndex;
                        insertSelectedCompletion();
                        // Prevent loss of focus
                        e.preventDefault();
                    });
                    return row;
                }));

            oldAutocomplete.remove();

            channelTextarea
                .append(autocomplete);
        }, delay);

        // Scroll through the "window" of completions
        function scrollWindow(delta, {locked=false, clamped=false} = {}) {
            const {completions, selectedIndex: prevSel, windowOffset} = cached;

            if (completions === undefined || completions.length === 0) {
                return;
            }

            // Change selected index
            const num = completions.length;
            let sel = prevSel + delta;
            if (clamped) {
                sel = _.clamp(sel, 0, num-1);
            } else {
                sel = (sel % num) + (sel<0 ? num : 0);
            }
            cached.selectedIndex = sel;

            // Clamp window position to bounds based on new selected index
            const boundLower = _.clamp(sel + preScroll - (windowSize-1), 0, num-windowSize);
            const boundUpper = _.clamp(sel - preScroll, 0, num-windowSize);
            cached.windowOffset = _.clamp(windowOffset + (locked ? delta : 0), boundLower, boundUpper);

            // Render immediately
            renderCompletions();
            renderCompletions.flush();
        }

        function prepareCompletions() {
            const candidateText = textarea.value.slice(0, textarea.selectionEnd);
            const {candidateText: lastText} = cached;

            if (lastText !== candidateText) {
                const {completions, matchText, matchStart} = getCompletions(emoteSets, candidateText);
                cached = {candidateText, completions, matchText, matchStart, selectedIndex: 0, windowOffset: 0};
            }

            const {completions} = cached;
            return (completions !== undefined && completions.length !== 0);
        }

        function destroyCompletions() {
            const channelTextarea = $(textarea).closest(".channelTextArea-1LDbYG > .inner-zqa7da");
            const oldAutocomplete = channelTextarea.children(".kawaii-autocomplete");
            oldAutocomplete.remove();
            cached = {};
            renderCompletions.cancel();
        }

        // Insert selected completion at cursor position
        function insertSelectedCompletion() {
            const {completions, matchStart, selectedIndex} = cached;

            if (completions === undefined) {
                return;
            }

            textarea.focus();
            // Set beginning of selection at start of partial emote text; end of selection end remains where it is
            textarea.selectionStart = matchStart;
            document.execCommand("insertText", false, completions[selectedIndex][0] + " ");

            destroyCompletions();
        }

        // Check for matches (overrides TextareaAutosize's onClick, onKeyPress, onKeyUp, maybeShowAutocomplete)
        function checkCompletions(e) {
            /* jshint validthis: true */
            textarea = this;

            const candidateText = textarea.value.slice(0, textarea.selectionEnd);
            const {candidateText: lastText} = cached;

            // If an emote match is impossible, don't override default behavior.
            // This allows other completion types (like usernames or channels) to work as usual.
            if (!shouldCompleteTwitch(candidateText)) {
                destroyCompletions();
                return;
            }

            // Don't override enter when there are no actual completions.
            // This allows message sending to work as usual.
            if (e.which === 13) {
                return;
            }

            // For any other key, always override, even when there are no actual completions.
            // This prevents Discord's emoji autocompletion from kicking in intermittently.
            e.stopPropagation();

            if (lastText !== candidateText) {
                renderCompletions();
            }
        }

        // Browse or insert matches (overrides ChannelTextArea's onKeyDown)
        function browseCompletions(e) {
            /* jshint validthis: true */
            textarea = this;

            const candidateText = textarea.value.slice(0, textarea.selectionEnd);
            if (!shouldCompleteTwitch(candidateText)) {
                return;
            }

            let delta = 0, options;

            switch (e.which) {
                // Tab
                case 9:

                    if (!prepareCompletions()) {
                        break;
                    }

                    // Prevent Discord's default behavior (send message)
                    e.stopPropagation();
                    // Prevent adding a tab or line break to text
                    e.preventDefault();

                    insertSelectedCompletion();
                    break;

                // Up
                case 38:
                    delta = -1;
                    break;

                // Down
                case 40:
                    delta = 1;
                    break;

                // Page Up
                case 33:
                    delta = -windowSize;
                    options = {locked: true, clamped: true};
                    break;

                // Page Down
                case 34:
                    delta = windowSize;
                    options = {locked: true, clamped: true};
                    break;
            }

            if (delta !== 0 && prepareCompletions()) {
                // Prevent Discord's default behavior
                e.stopPropagation();
                // Prevent cursor movement
                e.preventDefault();

                scrollWindow(delta, options);
            }
        }

        // Scroll matches
        function scrollCompletions(e, options) {
            /* jshint validthis: true */
            const delta = Math.sign(e.originalEvent.deltaY);
            scrollWindow(delta, options);
        }

        // Check for matches
        $(".app").on({
            "keyup.kawaii-complete keypress.kawaii-complete click.kawaii-complete": checkCompletions,
            "keydown.kawaii-complete": browseCompletions,
            "wheel.kawaii-complete": scrollCompletions,
            "blur.kawaii-complete": destroyCompletions,
        }, ".channelTextArea-1LDbYG textarea");
    }

    // Tear down event handlers and clean up
    function stopTabComplete() {
        $(".app").off(".kawaii-complete", ".channelTextArea-1LDbYG textarea");
    }

    // Filter function for "Twitch-style" emotes, to avoid collisions with common words
    // Check if at least 4 word characters
    function emoteFilter(name) {
        return /^\w{4,}$/.test(name);
    }

    // Global Twitch emotes (emoteset 0), filtered by emoteFilter
    var twitchEmotes = new EmoteSet();
    twitchEmotes.template = "https://static-cdn.jtvnw.net/emoticons/v1/{0}/{1}.0";
    twitchEmotes.emoteStyle = EmoteSet.emoteStyle.TWITCH;
    twitchEmotes.load = function (callbacks) {
        callbacks = $.extend({
            success: $.noop,
            error: $.noop,
        }, callbacks);
        if (this.loaded) {
            callbacks.success(this);
            return;
        }
        var self = this;
        // See: https://github.com/justintv/Twitch-API/blob/master/v3_resources/chat.md#get-chatemoticons
        $.ajax("https://api.twitch.tv/kraken/chat/emoticon_images?emotesets=0", {
            accepts: {json: "application/vnd.twitchtv.v3+json"},
            headers: {'Client-ID': 'a7pwjx1l6tr0ygjrzafhznzd4zgg9md'},
            dataType: "json",
            jsonp: false,
            cache: true,
            success: function (data) {
                var loaded = 0;
                var skipped = 0;
                data.emoticon_sets[0].forEach(function (emoticon) {
                    if (emoteFilter(emoticon.code)) {
                        self.emoteMap.set(emoticon.code, emoticon.id);
                        loaded++;
                    } else {
                        skipped++;
                    }
                });
                console.info("KawaiiEmotes:", "Twitch global emotes loaded:", loaded, "skipped:", skipped);
                self.loaded = true;
                callbacks.success(self);
            },
            error: function (xhr, textStatus, errorThrown) {
                console.warn("KawaiiEmotes:", "Twitch global emotes failed to load:", textStatus, "error:", errorThrown);
                callbacks.error(self);
            }
        });
    };

    // Twitch subscriber emotes, filtered by emoteFilter
    var twitchSubEmotes = new EmoteSet();
    twitchSubEmotes.template = "https://static-cdn.jtvnw.net/emoticons/v1/{0}/{1}.0";
    twitchSubEmotes.emoteStyle = EmoteSet.emoteStyle.TWITCH;
    twitchSubEmotes.load = function (callbacks) {
        callbacks = $.extend({
            success: $.noop,
            error: $.noop,
        }, callbacks);
        if (this.loaded) {
            callbacks.success(this);
            return;
        }
        var self = this;
        // See: https://github.com/justintv/Twitch-API/blob/master/v3_resources/chat.md#get-chatemoticons
        $.ajax("https://api.twitch.tv/kraken/chat/emoticon_images", {
            accepts: {json: "application/vnd.twitchtv.v3+json"},
            headers: {'Client-ID': 'a7pwjx1l6tr0ygjrzafhznzd4zgg9md'},
            dataType: "json",
            jsonp: false,
            cache: true,
            success: function (data) {
                var loaded = 0;
                var skipped = 0;
                data.emoticons.forEach(function (emoticon) {
                    if (emoticon.emoticon_set !== null && emoteFilter(emoticon.code)) {
                        self.emoteMap.set(emoticon.code, emoticon.id);
                        loaded++;
                    } else {
                        skipped++;
                    }
                });
                console.info("KawaiiEmotes:", "Twitch subscriber emotes loaded:", loaded, "skipped:", skipped);
                self.loaded = true;
                callbacks.success(self);
            },
            error: function (xhr, textStatus, errorThrown) {
                console.warn("KawaiiEmotes:", "Twitch subscriber emotes failed to load:", textStatus, "error:", errorThrown);
                callbacks.error(self);
            }
        });
    };

    // BetterTTV global emotes, filtered by emoteFilter
    var bttvEmotes = new EmoteSet();
    bttvEmotes.template = "https://cdn.betterttv.net/emote/{0}/{1}x";
    bttvEmotes.emoteStyle = EmoteSet.emoteStyle.TWITCH;
    bttvEmotes.load = function (callbacks) {
        callbacks = $.extend({
            success: $.noop,
            error: $.noop,
        }, callbacks);
        if (this.loaded) {
            callbacks.success(this);
            return;
        }
        var self = this;
        $.ajax("https://api.betterttv.net/2/emotes", {
            dataType: "json",
            jsonp: false,
            cache: true,
            success: function (data) {
                var loaded = 0;
                var skipped = 0;
                self.template = data.urlTemplate
                    .replace("{{id}}", "{0}")
                    .replace("{{image}}", "{1}x");
                data.emotes.forEach(function (emote) {
                    if (emoteFilter(emote.code)) {
                        self.emoteMap.set(emote.code, emote.id);
                        loaded++;
                    } else {
                        skipped++;
                    }
                });
                console.info("KawaiiEmotes:", "BTTV global emotes loaded:", loaded, "skipped:", skipped);
                self.loaded = true;
                callbacks.success(self);
            },
            error: function (xhr, textStatus, errorThrown) {
                console.warn("KawaiiEmotes:", "BTTV global emotes failed to load:", textStatus, "error:", errorThrown);
                callbacks.error(self);
            }
        });
    };

    // FrankerFaceZ global emotes, filtered by emoteFilter
    var ffzEmotes = new EmoteSet();
    ffzEmotes.template = "https://cdn.frankerfacez.com/emoticon/{0}/{1}";
    ffzEmotes.emoteStyle = EmoteSet.emoteStyle.TWITCH;
    ffzEmotes.load = function (callbacks) {
        callbacks = $.extend({
            success: $.noop,
            error: $.noop,
        }, callbacks);
        if (this.loaded) {
            callbacks.success(this);
            return;
        }
        var self = this;
        // See: https://www.frankerfacez.com/developers
        $.ajax("https://api.frankerfacez.com/v1/set/global", {
            dataType: "json",
            jsonp: false,
            cache: true,
            success: function (data) {
                var loaded = 0;
                var skipped = 0;
                data.default_sets.forEach(function (set) {
                    data.sets[set].emoticons.forEach(function (emoticon) {
                        if (emoteFilter(emoticon.name)) {
                            self.emoteMap.set(emoticon.name, emoticon.id);
                            loaded++;
                        } else {
                            skipped++;
                        }
                    });
                });
                console.info("KawaiiEmotes:", "FFZ global emotes loaded:", loaded, "skipped:", skipped);
                self.loaded = true;
                callbacks.success(self);
            },
            error: function (xhr, textStatus, errorThrown) {
                console.warn("KawaiiEmotes:", "FFZ global emotes failed to load:", textStatus, "error:", errorThrown);
                callbacks.error(self);
            }
        });
    };

    // BD's BTTV2 emote list, unfiltered
    // This is BD's massive set of (more or less) every shared emote from BTTV
    // TODO: Move downloading of this emote set from main thread to this one
    //       Or, at least make it asynchronous
    //       BD's loading should not block on fetching and parsing a 1MB+ JSON file from GitHub
    var bttvLegacyEmotes = new EmoteSet();
    bttvLegacyEmotes.template = "https://cdn.betterttv.net/emote/{0}/{1}x";
    bttvLegacyEmotes.emoteStyle = EmoteSet.emoteStyle.TWITCH;
    bttvLegacyEmotes.load = function (callbacks) {
        callbacks = $.extend({
            success: $.noop,
            error: $.noop,
        }, callbacks);
        if (this.loaded) {
            callbacks.success(this);
            return;
        }
        if (emotesBTTV2 === undefined) {
            console.warn("KawaiiEmotes:", "BetterDiscord legacy BTTV shared emotes failed to load:", "emotesBTTV2 is undefined");
            callbacks.error(this);
        }
        var self = this;
        (function (data) {
            var loaded = 0;
            var skipped = 0;
            Object.keys(data).forEach(function (name) {
                self.emoteMap.set(name, data[name]);
                loaded++;
            });
            console.info("KawaiiEmotes:", "BetterDiscord legacy BTTV shared emotes loaded:", loaded, "skipped:", skipped);
            self.loaded = true;
            callbacks.success(self);
        })(emotesBTTV2);
    };

    // BD's FFZ emote list, unfiltered
    // This is BD's massive set of (more or less) every public emote from FFZ
    // TODO: Move downloading of this emote set from main thread to this one
    //       Or, at least make it asynchronous
    //       BD's loading should not block on fetching and parsing a 1MB+ JSON file from GitHub
    var ffzLegacyEmotes = new EmoteSet();
    ffzLegacyEmotes.template = "https://cdn.frankerfacez.com/emoticon/{0}/{1}";
    ffzLegacyEmotes.emoteStyle = EmoteSet.emoteStyle.TWITCH;
    ffzLegacyEmotes.load = function (callbacks) {
        callbacks = $.extend({
            success: $.noop,
            error: $.noop,
        }, callbacks);
        if (this.loaded) {
            callbacks.success(this);
            return;
        }
        if (emotesFfz === undefined) {
            console.warn("KawaiiEmotes:", "BetterDiscord legacy FFZ public emotes failed to load:", "emotesFfz is undefined");
            callbacks.error(this);
        }
        var self = this;
        (function (data) {
            var loaded = 0;
            var skipped = 0;
            Object.keys(data).forEach(function (name) {
                self.emoteMap.set(name, data[name]);
                loaded++;
            });
            console.info("KawaiiEmotes:", "BetterDiscord legacy FFZ public emotes loaded:", loaded, "skipped:", skipped);
            self.loaded = true;
            callbacks.success(self);
        })(emotesFfz);
    };

    // End emote data

    // Settings panel helpers

    // Create and return a new top-level settings panel
    function topPanel() {
        var panel = $("<form>")
            .addClass("form")
            .css("width", "100%");

        return panel;
    }

    // Create and return a container for control groups
    function controlGroups() {
        return $("<div>").addClass("control-groups");
    }

    // Create and return a flexible control group
    // settings (object)
    //   label
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    function controlGroup(settings) {
        var group = $("<div>").addClass("control-group");

        if (typeof settings.label === "string") {
            group.append($("<label>").text(settings.label));
        } else if (settings.label !== undefined) {
            group.append($("<label>").append(settings.label));
        }

        return group;
    }

    // Create and return a group of checkboxes
    // settings (object)
    //   items (array)
    //     an array of settings objects to be passed to checkbox()
    //   callback (function(state))
    //     called with the current state, when it changes
    //     state is an array of boolean values
    function checkboxGroup(settings) {
        settings = $.extend({
            items: [],
            callback: $.noop,
        }, settings);

        var state = settings.items.map(item => item.checked === true);
        function onClick(i, itemState) {
            if (settings.items[i].callback !== undefined) {
                settings.items[i].callback(itemState);
            }
            state[i] = itemState;
            settings.callback(state);
        }

        var group = $("<ul>").addClass("checkbox-group");

        group.append(settings.items.map(function (item, i) {
            return checkbox($.extend({}, item, {
                callback: onClick.bind(undefined, i),
            }));
        }));

        return group;
    }

    // Create and return a checkbox
    // settings (object)
    //   label
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    //   help
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    //   checked (boolean)
    //   disabled (boolean)
    //   callback (function(state))
    //     called with the current state, when it changes
    //     state is a boolean
    function checkbox(settings) {
        settings = $.extend({
            checked: false,
            disabled: false,
            callback: $.noop,
        }, settings);

        var input = $("<input>").attr("type", "checkbox")
            .prop("checked", settings.checked)
            .prop("disabled", settings.disabled);

        var inner = $("<div>").addClass("checkbox-inner")
            .append(input)
            .append($("<span>"));

        var outer = $("<div>").addClass("checkbox").append(inner);

        if (settings.disabled) {
            outer.addClass("disabled");
        }

        if (typeof settings.label === "string") {
            outer.append($("<span>").text(settings.label));
        } else if (settings.label !== undefined) {
            outer.append($("<span>").append(settings.label));
        }

        outer.on("click.kawaiiSettings", function () {
            if (!input.prop("disabled")) {
                var checked = !input.prop("checked");
                input.prop("checked", checked);
                settings.callback(checked);
            }
        });

        var item = $("<li>").append(outer);

        var help;
        if (typeof settings.help === "string") {
            help = $("<div>").text(settings.help);
        } else if (settings.help !== undefined) {
            help = $("<div>").append(settings.help);
        }

        if (help !== undefined) {
            help.appendTo(item)
                .addClass("help-text")
                .css("margin-top", "-3px")
                .css("margin-left", "27px");
        }

        return item;
    }

    // Generate a random string of alphanumeric characters
    // length
    //   number of characters in output (default: 8)
    function randomString(length) {
        var n = (length !== undefined) ? length : 8;
        var c = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        var out = "";
        for (let i = 0; i < n; i++) {
            out += c[Math.floor(Math.random() * c.length)];
        }
        return out;
    }

    // Create and return a group of radio buttons
    // settings (object)
    //   items (array)
    //     an array of settings objects to be passed to checkbox()
    //   callback (function(state))
    //     called with the current state, when it changes
    //     state is the index of the selected element
    function radioGroup(settings) {
        settings = $.extend({
            items: [],
            callback: $.noop,
        }, settings);

        var name = "kawaiiRadio$" + randomString();

        var state = settings.items.findIndex(item => item.checked === true);
        function onClick(i, itemState) {
            if (!itemState) {
                return;
            }
            if (i !== state) {
                if (settings.items[state] !== undefined && settings.items[state].callback !== undefined) {
                    settings.items[state].callback(false);
                }
                if (settings.items[i].callback !== undefined) {
                    settings.items[i].callback(true);
                }
                state = i;
                settings.callback(state);
            }
        }

        var group = $("<ul>").addClass("radio-group");

        group.append(settings.items.map(function (item, i) {
            return radio($.extend({}, item, {
                name: name,
                callback: onClick.bind(undefined, i),
            }));
        }));

        return group;
    }

    // Create and return a radio button
    // settings (object)
    //   label
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    //   help
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    //   checked (boolean)
    //   disabled (boolean)
    //   name (string)
    //     name of the radio group this belongs to
    //   callback (function(state))
    //     called with the current state, when it changes
    //     state is a boolean
    function radio(settings) {
        settings = $.extend({
            checked: false,
            disabled: false,
            callback: $.noop,
        }, settings);

        var input = $("<input>").attr("type", "radio")
            .attr("name", settings.name)
            .prop("checked", settings.checked)
            .prop("disabled", settings.disabled);

        var inner = $("<div>").addClass("radio-inner")
            .append(input)
            .append($("<span>"));

        var outer = $("<div>").addClass("radio").append(inner);

        if (settings.disabled) {
            outer.addClass("disabled");
        }

        if (typeof settings.label === "string") {
            outer.append($("<span>").text(settings.label));
        } else if (settings.label !== undefined) {
            outer.append($("<span>").append(settings.label));
        }

        outer.on("click.kawaiiSettings", function () {
            if (!input.prop("disabled")) {
                var checked = true;
                input.prop("checked", checked);
                settings.callback(checked);
            }
        });

        var item = $("<li>").append(outer);

        var help;
        if (typeof settings.help === "string") {
            help = $("<div>").text(settings.help);
        } else if (settings.help !== undefined) {
            help = $("<div>").append(settings.help);
        }

        if (help !== undefined) {
            help.appendTo(item)
                .addClass("help-text")
                .css("margin-top", "-3px")
                .css("margin-left", "41px");
        }

        return item;
    }

    // End settings panel helpers

    function initJQueryPlugins($) {
        // jQuery Plugins

        // Make sure that these are set up after jQuery is available, but before we need any of them
        // Should be fine if it happens to be called more than once

        // Get or set the scroll distance from the bottom of an element
        // Usage identical to scrollTop()
        $.fn.scrollBottom = function (val) {
            var elem = this[0];
            if (val === undefined) {
                if (elem === undefined) {
                    return undefined;
                }
                return elem.scrollHeight - (this.scrollTop() + this.height());
            }
            if (elem === undefined) {
                return this;
            }
            return this.scrollTop(elem.scrollHeight - (val + this.height()));
        };

        // Get the set of text nodes contained within a set of elements
        $.fn.textNodes = function () {
            return this.map(function () {
                const textNodes = [];
                let textNodeWalker, currentNode;

                if ($(this).find("code").length > 0) {
                    // If there are any code blocks, rejecting that whole subtree is a bit faster
                    textNodeWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
                        acceptNode: function (node) {
                            if (node.nodeType === Node.TEXT_NODE) {
                                return NodeFilter.FILTER_ACCEPT;
                            }
                            if (node.nodeName.toLowerCase() === "code") {
                                return NodeFilter.FILTER_REJECT;
                            }
                            return NodeFilter.FILTER_SKIP;
                        }
                    });
                } else {
                    textNodeWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT);
                }

                while ((currentNode = textNodeWalker.nextNode()) !== null) {
                    textNodes.push(currentNode);
                }
                return textNodes;
            });
        };

        // Parse for standard emotes in message text
        $.fn.parseEmotesStandard = function (emoteSets, options) {
            if (emoteSets === undefined || emoteSets.length === 0) {
                return this;
            }

            this.textNodes().each(function () {
                var sub = [];
                // separate out potential emotes
                // all standard emotes are composed of characters in [a-zA-Z0-9_], i.e. \w between two colons, :
                // use a regex with a capture group, so that we can preserve separators
                var words = this.data.split(/(:[\w#*]+:)/g);
                // non-emoteable words, for building a new text node if necessary
                var nonEmote = [];
                // whether the text in this node has been modified
                var modified = false;

                for (var i = 0; i < words.length; i += 2) {
                    // words[i] is a separator
                    // words[i+1] is our potential emote, or undefined

                    // Keep the separator
                    nonEmote.push(words[i]);
                    if (words[i+1] === undefined) {
                        break;
                    }

                    var emote;
                    if (emoteSets.some(function (set) {
                        emote = set.createEmote(/^:([^:]+):$/.exec(words[i+1])[1], options);
                        return (emote !== undefined);
                    })) {
                        modified = true;
                        // Create a new text node from any previous text
                        sub.push(document.createTextNode(nonEmote.join("")));
                        // Clear out stored words
                        nonEmote = [];
                        // Add the emote element
                        sub.push(emote);
                    } else {
                        // Unrecognized as emote, keep the word
                        nonEmote.push(words[i+1]);
                    }
                }
                // If no emotes were found, leave this text node unchanged
                if (modified) {
                    // Replace this node's contents with remaining text
                    this.data = nonEmote.join("");
                }
                $(this).before(sub);
            });

            return this;
        };

        var emoteMods = new Set([
            "flip", "flap", "pulse",
            "spin", "spin2", "spin3",
            "1spin", "2spin", "3spin",
            "shake", "shake2", "shake3",
            "tr", "bl", "br",
        ]);

        // Parse for Twitch-style emotes in message text
        $.fn.parseEmotesTwitch = function (emoteSets, options) {
            if (emoteSets === undefined || emoteSets.length === 0) {
                return this;
            }

            var emoteModsEnabled = settingsCookie["bda-es-8"];

            // Find and replace Twitch-style emotes
            this.textNodes().each(function () {
                var sub = [];
                // separate out potential emotes
                // all twitch emotes (that we care about) are composed of characters in [a-zA-Z0-9_], i.e. \w
                // colons (:) are allowed when used for emote modifiers
                // use a regex with a capture group, so that we can preserve separators
                var words = this.data.split(/(\s+)/g);
                // non-emoteable words, for building a new text node if necessary
                var nonEmote = [];
                // whether the text in this node has been modified
                var modified = false;
                for (var i = 0; i < words.length; i += 2) {
                    // words[i] is our potential emote (+modifer)
                    // words[i+1] is a separator, or undefined
                    var res = /^([^:]*)(?::(.*))?$/.exec(words[i]);
                    // word is our potential emote
                    var word = res[1];
                    // modifier is an emote modifier, or undefined
                    var modifier = res[2];
                    var emote;
                    if (($.inArray(word, bemotes) == -1) && emoteSets.some(function (set) {
                        emote = set.createEmote(word, options);
                        return (emote !== undefined);
                    })) {
                        modified = true;
                        // Create a new text node from any previous text
                        sub.push(document.createTextNode(nonEmote.join("")));
                        // Clear out stored words
                        nonEmote = [];
                        // Apply any emote mods, if applicable
                        if (emoteModsEnabled && emoteMods.has(modifier)) {
                            emote.addClass("emote"+modifier);
                        }
                        // Add the emote element
                        sub.push(emote);
                    } else {
                        // Unrecognized as emote, keep the word
                        nonEmote.push(words[i]);
                    }
                    // Keep the separator
                    nonEmote.push(words[i+1]);
                }
                // If no emotes were found, leave this text node unchanged
                if (modified) {
                    // Replace this node's contents with remaining text
                    this.data = nonEmote.join("");
                }
                $(this).before(sub);
            });

            return this;
        };

        // Parse emotes (of any style) in message text
        $.fn.parseEmotes = function (emoteSets, options) {
            if (emoteSets === undefined || emoteSets.length === 0) {
                return this;
            }

            var standardSets = [];
            var twitchSets = [];
            emoteSets.forEach(function (set) {
                if (set.emoteStyle === EmoteSet.emoteStyle.STANDARD) {
                    standardSets.push(set);
                } else if (set.emoteStyle === EmoteSet.emoteStyle.TWITCH) {
                    twitchSets.push(set);
                }
            });

            this.parseEmotesStandard(standardSets, options);
            this.parseEmotesTwitch(twitchSets, options);

            return this;
        };

        // Jumboify emotes/emoji appropriately
        $.fn.jumboify = function (options) {
            options = $.extend({}, $.fn.jumboify.defaults, options);

            if (!options.forceJumbo) {
                // Properly jumboify emotes/emoji in messages with no other text
                this.has(".emoji").each(function () {
                    // Get the "edited" text, if any, regardless of how it's styled or localized
                    var edited = $(this).find(".edited").text();
                    // Get the remaining message text
                    var text = this.textContent.replace(edited, "").trim();
                    if (text.length === 0) {
                        $(this).find(".emoji").addClass("jumboable");
                    } else {
                        $(this).find(".emoji").removeClass("jumboable");
                    }
                });
            } else {
                // Everything is jumboified, similar to old behavior
                this.find(".emoji").addClass("jumboable");
            }

            return this;
        };

        $.fn.jumboify.defaults = {
            forceJumbo: false,
        };

        // Replace title text with fancy tooltips
        $.fn.fancyTooltip = function () {
            return this.filter("[title]").each(function () {
                var title = $(this).attr("title");
                $(this).addClass("kawaii-fancytooltip").removeAttr("title");
                $(this).on("mouseover.fancyTooltip", function () {
                    // Create and insert tooltip
                    var tooltip = $("<div>").append(title).addClass("tooltip tooltip-top tooltip-brand");
                    $(".tooltips").append(tooltip);

                    // Position the tooltip
                    var position = $(this).offset();
                    position.top -= 30;
                    position.left += $(this).width()/2 - tooltip.width()/2 - 10;
                    tooltip.offset(position);

                    // Set a handler to destroy the tooltip
                    $(this).on("mouseout.fancyTooltip", function () {
                        // remove this handler
                        $(this).off("mouseout.fancyTooltip");
                        tooltip.remove();
                    });
                });
            });
        };
    } // initJQueryPlugins

    // Helper function for finding all elements matching selector affected by a mutation
    function mutationFind(mutation, selector) {
        var target = $(mutation.target), addedNodes = $(mutation.addedNodes);
        var mutated = target.add(addedNodes).filter(selector);
        var descendants = addedNodes.find(selector);
        var ancestors = target.parents(selector);
        return mutated.add(descendants).add(ancestors);
    }

    // Helper function for finding all elements matching selector removed by a mutation
    function mutationFindRemoved(mutation, selector) {
        var removedNodes = $(mutation.removedNodes);
        var mutated = removedNodes.filter(selector);
        var descendants = removedNodes.find(selector);
        return mutated.add(descendants);
    }

    // Revert all emotes
    function revertEmotes() {
        // Swap every emote back to its original text
        $(".kawaii-parseemotes").each(function() {
            var emote = $(this);
            emote.replaceWith(document.createTextNode(emote.attr("alt")));
        });
    }

    // Parse the messages for given emote sets
    function parseEmoteSets(messages, sets) {
        // Figure out whether we're scrolled to the bottom
        var messagesContainer = $(".messages");
        var atBottom = messagesContainer.scrollBottom() < 0.5;

        // Process messages
        messages.parseEmotes(sets, {allowWide: settings.allowWide});
        if (settingsCookie["bda-es-6"]) {
            messages.find(".kawaii-parseemotes[title]").fancyTooltip();
        }
        messages.jumboify({forceJumbo: settings.forceJumbo});

        // Ensure we're still scrolled to the bottom if necessary
        if (atBottom) {
            messagesContainer.scrollBottom(0);
        }
    }

    const activeEmoteSets = [];

    // Settings updated, rebuild active emote sets and rescan for emotes if necessary
    function updateSettings() {
        const oldEmoteSets = activeEmoteSets.splice(0);

        if (settingsCookie["bda-es-7"]) {
            activeEmoteSets.push(twitchEmotes);
            activeEmoteSets.push(twitchSubEmotes);
        }

        if (settingsCookie["bda-es-1"]) {
            activeEmoteSets.push(ffzEmotes);
            activeEmoteSets.push(ffzLegacyEmotes);
        }

        if (settingsCookie["bda-es-2"]) {
            activeEmoteSets.push(bttvEmotes);
            activeEmoteSets.push(bttvLegacyEmotes);
        }

        var modified = false;
        if (activeEmoteSets.length !== oldEmoteSets.length) {
            modified = true;
        } else {
            for (var i = 0; i < activeEmoteSets.length; i++) {
                if (activeEmoteSets[i] !== oldEmoteSets[i]) {
                    modified = true;
                    break;
                }
            }
        }
        if (modified) {
            reload();
        }
    }

    function reload() {
        revertEmotes();
        var messages = $(".markup-2BOw-j, .message-content").not(":has(.message-content)");
        parseEmoteSets(messages, activeEmoteSets);
    }

    kawaiiemotes.prototype.observer = function (mutation) {
        // Get the set of messages affected by this mutation
        var messages = mutationFind(mutation, ".markup-2BOw-j, .message-content").not(":has(.message-content)");
        parseEmoteSets(messages, activeEmoteSets);

        // Clean up any remaining tooltips
        mutationFindRemoved(mutation, ".kawaii-fancytooltip").trigger("mouseout");
    };

    // Parse the whole document for a single emote set, if it is active
    function parseEmoteSetIfActive(set) {
        if (activeEmoteSets.indexOf(set) !== -1) {
            var messages = $(".markup-2BOw-j, .message-content").not(":has(.message-content)");
            parseEmoteSets(messages, [set]);
        }
    }

    // Settings
    //   forceJumbo
    //     false - imitate Discord's behavior: emotes only "jumboable" when on a line with no other text
    //     true  - similar to "classic" BD behavior: emotes and emoji are always "jumboable"
    //   allowWide
    //     false - all emotes are forced to a square aspect ratio
    //     true  - wide emotes may expand horizontally to meet their intended aspect ratio
    //   highDpi
    //     false - always use the base emote size
    //     true  - use srcset to specify high-DPI versions
    //   completionsMenu
    //     true  - show tab-completion menu for "Twitch-style" emotes
    //   completionsDelay
    //     delay (ms) after typing has stopped before searching for completions
    //   completionsWindowSize
    //     maximum number of completions to show, and number of items to scroll on Page Up/Down
    //   completionsPreScroll
    //     minimum number of nearby items to show next to selected item when scrolling

    var settings = {}, defaultSettings = {
        forceJumbo: false,
        allowWide: false,
        highDpi: false,
        completionsMenu: true,
    };

    // Load or store settings from localStorage
    function localSettings(settings) {
        if (settings === undefined) {
            var localSettings;

            try {
                localSettings = bdPluginStorage.get("kawaiiemotes", "settings");
            } catch (err) {
                console.warn("KawaiiEmotes:", "unable to load settings:", err);
                localSettings = null;
            }

            if (localSettings === null) {
                // try to fall back to localStorage
                try {
                    localSettings = JSON.parse(localStorage.kawaiiemotes);
                } catch (err) {
                    localSettings = {};
                }
                bdPluginStorage.set("kawaiiemotes", "settings", localSettings);
            }
            return $.extend({}, defaultSettings, localSettings);
        }

        try {
            bdPluginStorage.set("kawaiiemotes", "settings", settings);
        } catch (err) {
            console.warn("KawaiiEmotes:", "unable to save settings:", err);
        }
    }

    kawaiiemotes.prototype.load = function () {
    };

    kawaiiemotes.prototype.unload = function () {
    };

    kawaiiemotes.prototype.start = function () {
        initJQueryPlugins($);
        settings = localSettings();

        // Save these to be restored later
        EmoteModule.prototype.oldObsCallback = EmoteModule.prototype.obsCallback;
        settingsPanel.oldUpdateSettings = settingsPanel.updateSettings;
        // Disable this, because this plugin's mutation observer handles it
        EmoteModule.prototype.obsCallback = $.noop;
        // Hook into these to notify when settings are updated
        settingsPanel.updateSettings = function () {
            this.oldUpdateSettings();
            updateSettings();
        };

        updateSettings();

        // Load the emote sets if necessary, and parse the document as they load
        twitchEmotes.load({success: parseEmoteSetIfActive});
        twitchSubEmotes.load({success: parseEmoteSetIfActive});
        bttvEmotes.load({success: parseEmoteSetIfActive});
        bttvLegacyEmotes.load({success: parseEmoteSetIfActive});
        ffzEmotes.load({success: parseEmoteSetIfActive});
        ffzLegacyEmotes.load({success: parseEmoteSetIfActive});

        startTabComplete(activeEmoteSets, settings);
    };

    kawaiiemotes.prototype.stop = function () {
        // Restore these
        EmoteModule.prototype.obsCallback = EmoteModule.prototype.oldObsCallback;
        settingsPanel.updateSettings = settingsPanel.oldUpdateSettings;

        revertEmotes();

        stopTabComplete();

        localSettings(settings);
    };

    kawaiiemotes.prototype.getSettingsPanel = function () {
        var panel = topPanel();

        var completionControls = controlGroups().appendTo(panel);

        var completionMainControl = controlGroup({label: "Tab-completion"})
            .appendTo(completionControls)
            .append(checkboxGroup({
                callback: state => {
                    localSettings(settings);
                    stopTabComplete();
                    startTabComplete(activeEmoteSets, settings);
                },
                items: [
                    {
                        label: "Show tab-completion menu for BetterDiscord emotes.",
                        checked: settings.completionsMenu,
                        callback: state => { settings.completionsMenu = state; },
                    },
                ],
            }));

        var appearanceControls = controlGroups().appendTo(panel);

        var tweaksControl = controlGroup({label: "Appearance Tweaks (Experimental)"})
            .appendTo(appearanceControls)
            .append(checkboxGroup({
                callback: state => {
                    localSettings(settings);
                    reload();
                },
                items: [
                    {
                        label: "Always Jumboify emotes.",
                        help: "Emotes and emoji are always jumbo-sized, regardless of whether the message contains any other text.",
                        checked: settings.forceJumbo,
                        callback: state => { settings.forceJumbo = state; },
                    },
                    {
                        label: "Allow wide-format emotes.",
                        help: "Let FFZ's wide-format emotes blow up your line lengths.",
                        checked: settings.allowWide,
                        callback: state => { settings.allowWide = state; },
                    },
                    {
                        label: "Use High-DPI Emotes when available. (soon™)",
                        checked: settings.highDpi,
                        callback: state => { settings.highDpi = state; },
                        disabled: true,
                    },
                ],
            }));

        return panel[0];
    };

    kawaiiemotes.prototype.getName = function () {
        return "KawaiiEmotes";
    };

    kawaiiemotes.prototype.getDescription = function () {
        return "Better emote parsing for BetterDiscord";
    };

    kawaiiemotes.prototype.getVersion = function () {
        return "0.4.8";
    };

    kawaiiemotes.prototype.getAuthor = function () {
        return "noodlebox";
    };
})();

/*@end @*/


text:
from .models import Subscription, Item, Analysis, AnalysisItem
from .crawler import getItems
import msgSender

def crawlItems(subId, keywords, priceLow, priceHigh):
    totalNum, items = getItems(keywords.encode('gbk'), priceLow, priceHigh)
    analysis = createAnalysis(subId, totalNum)
    flag = False
    for item in items:
        if saveCrawlItem(item, analysis.id) and not judgeIsBuying(item['title'], item['description']):
            flag = True
    if flag:
        sub = Subscription.objects.get(id=subId)
        sub.recentAnalysisID = analysis.id
        sub.recentNotificationDT = analysis.createdDT
        sub.save()
        msgSender.sendMsg(analysis.id)

def saveCrawlItem(item, analysisId):
    flag = False
    if not Item.objects.filter(taobaoId=int(item['taobaoId'])):
        flag = True
        resultItem = Item.objects.create(
            title = item['title'],
            description = item['description'],
            price = item['price'],
            link = item['link'],
            imgLink = item['imgLink'],
            taobaoId = int(item['taobaoId'])
        )
        resultItem.isBuying = judgeIsBuying(resultItem.title, resultItem.description)
        resultItem.save()
        saveAnalysisItem(analysisId, resultItem.id)
    return flag

def saveAnalysisItem(analysisId, itemId):
    analysisItem = AnalysisItem.objects.create(
        analysisID = Analysis.objects.get(id=analysisId),
        itemID = Item.objects.get(id=itemId)
    )
    analysisItem.save()
    return analysisItem

def createAnalysis(subId, totalNum):
    subscription = Subscription.objects.get(id=subId)
    analysis = Analysis.objects.create(subscriptionID=subscription, totalNum=totalNum)
    analysis.save()
    return analysis

def judgeIsBuying(title, desc):
    isBuyingTitle = (u"求购" in title or u"收" in title)
    isBuyingDesc = (u"求购" in desc or u"收" in desc)
    return isBuyingTitle or isBuyingDesc


text:
<?php
$this->breadcrumbs = array(
    'Quản lý Quảng cáo',
);
?>

            <a href="<?php echo Yii::app()->createAbsoluteUrl($parentUrl . '/create'); ?>" role="button" class="white" data-toggle="modal"  title="Add new page">

        Quản lý Quảng cáo

                 Hình
                 Tiêu đề
                 Mô tả
                 Link url
                 Trang hiển thị
                 Ngày tạo
                 Trạng thái

        <?php
        if(isset($data)):
            foreach ($data as $key => $value):
        ?>

            <img src="<?php if(!$value['photo']) echo Yii::app()->theme->baseUrl .'/backend/img/no-image.png'; else echo Yii::app()->baseUrl.'/timthumb.php?src=' . Yii::app()->baseUrl .'/images/'. $value['photo'] .'&h=100&w=100';?>">
            <a href="<?php echo Yii::app()->createAbsoluteUrl('admin/ads/update', array('id' => $value->id)); ?>"><?php echo $value->title ?>
            <?php echo strip_tags($value['description'])?>

                <?php echo $value['link_url'];?>

                <?php
                    $tags = explode(',', $value->page);
                    for($i=0;$i<count($tags);$i++) {
                        $ads_menu = MyFunctionCustom::getParentMenuById([$tags[$i]]);
                        if($ads_menu['parent_id']){
                            echo ''.$ads_menu['parent']['name'] .'/'. $ads_menu['name'] .'';
                        }else{
                            echo ''.$ads_menu['name'].'';
                        }
                        if($i<count($tags)-1)
                            echo ' ';
                    }
                ?>

            <?php echo date("d-m-Y", $value['created_date'])?>

                <?php
                if($value->disabled):
                    echo ''.MyFunctionCustom::$status[$value->disabled].'';
                else:
                    echo ''.MyFunctionCustom::$status[$value->disabled].'';
                endif;?>

                    <a class="green" href="<?php echo Yii::app()->createAbsoluteUrl('admin/ads/update', array('id' => $value->id)); ?>">

                    <a class="red" href="<?php echo Yii::app()->createAbsoluteUrl('admin/ads/delete', array('id' => $value->id)); ?>">

                        <button class="btn btn-minier btn-yellow dropdown-toggle" data-toggle="dropdown">

                        </button>

                                <a href="<?php echo Yii::app()->createAbsoluteUrl('admin/ads/update', array('id' => $value->id)); ?>" class="tooltip-success" data-rel="tooltip" title="Edit">

                                <a href="<?php echo Yii::app()->createAbsoluteUrl('admin/ads/delete', array('id' => $value->id)); ?>" class="tooltip-info" data-rel="tooltip" title="Delete">

        <?php
        endforeach;
        endif;?>


text:
package com.google.android.apps.iosched.gcm.server;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A servlet that pushes a GCM message to all registered devices. This servlet creates multicast
 * entities consisting of 1000 devices each, and creates tasks to send individual GCM messages to
 * each device in the multicast.
 *
 * This servlet must be authenticated against with an administrator's Google account, ideally a
 * shared role account.
 */
public class SendMessageToAllServlet extends BaseServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        Queue queue = QueueFactory.getQueue("MulticastMessagesQueue");
        String announcement = req.getParameter("announcement");
        if (announcement == null) {
            announcement = "";
        }

        List<String> devices = Datastore.getDevices();

        // must split in chunks of 1000 devices (GCM limit)
        int total = devices.size();
        List<String> partialDevices = new ArrayList<String>(total);
        int counter = 0;
        for (String device : devices) {
            counter++;
            partialDevices.add(device);
            int partialSize = partialDevices.size();
            if (partialSize == Datastore.MULTICAST_SIZE || counter == total) {
                String multicastKey =
                        Datastore.createMulticast(partialDevices, announcement);
                logger.fine("Queuing " + partialSize + " devices on multicast " +
                        multicastKey);
                TaskOptions taskOptions = TaskOptions.Builder
                        .withUrl("/send")
                        .param("multicastKey", multicastKey)
                        .method(Method.POST);
                queue.add(taskOptions);
                partialDevices.clear();
            }
        }
        logger.fine("Queued message to " + counter + " devices");
        resp.sendRedirect("/success.html");
    }
}


text:
'use strict';
import * as models from './models';

export interface Message {

    id?: number;

    body?: string;

    time?: string;

    origin?: string;

    isAutoMessage?: boolean;

    deliveryStatus?: string;

    deliveryTime?: string;

    deliveryFailureReason?: string;

    isRead?: boolean;
}


text:
class GenPowerLawRandomNetworkMapFunction : public MapFunction {
public:
  GenPowerLawRandomNetworkMapFunction(uint64_t _numVertices,
                                      uint64_t _maxVertexDegree,
                                      uint64_t _minVertexDegree,
                                      uint64_t _mypeerid,
                                      uint64_t _numPeers);

  void map(KeyValuePair& kvPair, KVPairWriterInterface& writer);

private:
  const uint64_t numVertices; // of the graph to be generated
  const uint64_t maxVertexDegree;
  const uint64_t minVertexDegree;

  const uint64_t mypeerid;
  const uint64_t numPeers;

};

#endif // MAPRED_GEN_POWER_LAW_RANDOM_NETWORK_MAP_FUNCTION_H


text:
#include <stdbool.h>
#include <complex.h>
#include <math.h>

#include "num/multind.h"
#include "num/init.h"
#include "num/flpmath.h"

#include "misc/mmio.h"
#include "misc/misc.h"
#include "misc/opts.h"

#ifndef DIMS
#define DIMS 16
#endif

static const char usage_str[] = "bitmask <input> <output>";
static const char help_str[] = "Compute variance along selected dimensions specified by the {bitmask}";

int main_var(int argc, char* argv[])
{
	mini_cmdline(&argc, argv, 3, usage_str, help_str);

	num_init();

	long flags = atoi(argv[1]);

	long idims[DIMS];
	long odims[DIMS];

	complex float* in = load_cfl(argv[2], DIMS, idims);

	md_select_dims(DIMS, ~flags, odims, idims);

	complex float* out = create_cfl(argv[3], DIMS, odims);

	md_zvar(DIMS, idims, flags, out, in);

	unmap_cfl(DIMS, idims, in);
	unmap_cfl(DIMS, odims, out);

	return 0;
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="robots" content="index, follow, all" />
    <title>Devise\Users\Groups\GroupManager | Devise</title>

            <link rel="stylesheet" type="text/css" href="../../../css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="../../../css/bootstrap-theme.min.css">
        <link rel="stylesheet" type="text/css" href="../../../css/sami.css">

                <form id="search-form" action="../../../search.html" method="GET">

            <input name="search"
                   class="typeahead form-control"
                   type="search"
                   placeholder="Search">
        </form>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements">
                    Toggle navigation

                </button>
                Devise

Classes

Namespaces

Interfaces

Traits

Index

Search

class

Devise

Users

Groups

GroupManager

GroupManager

    class
    GroupManager

Class GroupManager manages the creating,
updating, and removing of groups.

Properties

                                                                                array

                $errors
                Errors are kept in an array and can be
used later if validation fails and we want to
know why

                $messages
                Validation messages

Methods

                    __construct(DvsGroup $Group, Framework $Framework)

Construct a new Group manager

                    array

                    createRules()

Create validation rules

                    DvsGroup

                    createGroup(array $input)

Create a new Group

                    array

                    updateRules(integer $id, array $input)

Update validation rules

                    DvsGroup

                    updateGroup(integer $id, array $input)

Update a new Group

                    DvsGroup

                    destroyGroup(integer $id)

Delete a Group

Details

at line 45

    __construct(DvsGroup $Group, Framework $Framework)

Construct a new Group manager

Parameters

                DvsGroup
                $Group

                Framework
                $Framework

at line 56

                            array
    createRules()

Create validation rules

Return Value

            array

at line 69

                            DvsGroup
    createGroup(array $input)

Create a new Group

Parameters

                array
                $input

Return Value

            DvsGroup
            $Group

at line 94

                            array
    updateRules(integer $id, array $input)

Update validation rules

Parameters

                integer
                $id

                array
                $input

Return Value

            array

at line 108

                            DvsGroup
    updateGroup(integer $id, array $input)

Update a new Group

Parameters

                integer
                $id

                array
                $input

Return Value

            DvsGroup
            $Group

at line 132

                            DvsGroup
    destroyGroup(integer $id)

Delete a Group

Parameters

                integer
                $id

Return Value

            DvsGroup
            $Group

        Generated by Sami, the API Documentation Generator.


text:
class DepartmentValueError(Exception):
    """Raised when department is an empty string."""
    def __init__(self, message):
        self.message = message

class PersonValueError(Exception):
    """Raised when person is an empty string."""
    def __init__(self, message):
        self.message = message

class QualifierValueError(Exception):
    """Raised when qualifier is an empty string."""
    def __init__(self, message):
        self.message = message

class KeyValueError(Exception):
    """Raised when there is no corresponding file to the specified key."""
    def __init__(self, message):
        self.message = message

class BucketValueError(Exception):
    """Raised when bucket name is empty is empty string or incorrect."""
    def __init__(self, message):
        self.message = message

class S3ValueError(Exception):
    """Raised when credentials are incorrect."""
    def __init__(self, message):
        self.message = message

class SocketValueError(Exception):
    """Raise when host parameter is incorrect."""
    def __init__(self, message):
        self.message = message

class GlobalValueError(Exception):
    """Raise when host parameter is incorrect."""
    def __init__(self, message):
        self.message = message


text:
/*global require, console*/

'use strict';

require('dotenv').load();

var sql = require('mssql');
var config = require('./config');
var csv = require('csv');
var fs = require('fs');
var async = require('async');
var util = require('util');

var connection = new sql.Connection(config, function(err) {
	if (err) {
		console.log(err);
	} else {
    	var request = new sql.Request(connection);

    	request.query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FacilityResults'", function(err, result) {
        	if (err) {
				console.log('MSSQL Error.');
				console.log(err);
        	} else {
        		console.log('Success');
				console.dir(result);
    		}
    		connection.close();
    	});
	}
});

sql.on('error', function(err) {
	console.log('MSSQL Error.');
	console.log(err);
});


text:
    <button ng-click="start()" class="btn btn-default"> sort</button>
    <button ng-click="reset()" class="btn btn-default"> reset</button>

Sort done


text:
""" A nose plugin to shunt rebuilding the database all the time """
import os
import logging

log = logging.getLogger('nose.plugins.aqdb_plugin')
#Assume that the caller will already have nose available
import nose

#Set this environment variable to trigger the no_rebuild effect
ENVIRONMENT_VARNAME = 'AQDB_NOREBUILD'

class DontRebuildPlugin(nose.plugins.Plugin):
    """ Custom plugin to shunt rebuilding the database during iterative
        development cycles of aquilon components. """

    def options(self, parser, env):
        parser.add_option('--no-rebuild',
                          action='store_true',
                          dest='no_rebuild',
                          default=False,
                          help="Don't rebuild the database")

    def configure(self, options, conf):
        #if environment variable is set, don't enable and exit
        #(ignore the plugin if the variable already exists)
        if ENVIRONMENT_VARNAME in os.environ.keys():
            log.info('found %s in the environment, skipping db rebuild ' % (
                ENVIRONMENT_VARNAME))
            return
        if options.no_rebuild:
            self.enabled = True
            os.environ[ENVIRONMENT_VARNAME] = 'enabled'
            log.debug("Plugin says don't rebuild the database")
        else:
            log.debug("Plugin says to rebuild the database")

    def begin(self):
        log.debug("DontRebuildPlugin.begin()")

    def reset(self):
        log.debug("DontRebuildPlugin.end()")
        os.environ[ENVIRONMENT_VARNAME] = ''

#if __name__ == '__main__':
#TESTING:
#    from nose.plugins.plugintest import run_buffered as run
#    import unittest
#    suite=unittest.TestSuite([])
#    argv=['-v', '--no-rebuild']
#    nose.plugins.plugintest.run(argv=argv,
#                                suite=suite, plugins=[DontRebuildPlugin()])
#RUNNING:
#    nose.main(addplugins=[DontRebuildPlugin()])


text:
<?php
/**
 * Created by PhpStorm.
 * User: LeoSorgetz
 * Date: 01/11/2016
 * Time: 01:11
 */
//var_dump($cedente);
//var_dump($cidades);
?>

Alterar Cedente

    <form action="<?= site_url('cedentes/update') ?>" method="post" class="form-group">
        <input type="hidden" name="cedente[id_cedente]" value="<?= $cedente[0]['id_cedente'] ?>">

            Codigo do Cedente:
            <input type="text" class="form-control" value="<?= $cedente[0]['cod_cedente'] ?>"
                   name="cedente[cod_cedente]" placeholder="Codigo do Cedente.."
                   required>

            Numero da agencia:
            <input type="text" class="form-control" value="<?= $cedente[0]['num_agencia'] ?>"
                   name="cedente[num_agencia]" placeholder="Numero da agencia.."
                   required>

            Numero da operação:
            <input type="text" class="form-control" value="<?= $cedente[0]['num_operacao'] ?>"
                   name="cedente[num_operacao]" placeholder="Numero da operação.."
                   required>

            Numero da conta corrente:
            <input type="text" class="form-control" name="cedente[num_conta_corrente]"
                   value="<?= $cedente[0]['num_conta_corrente'] ?>"
                   placeholder="Numero da conta corrente.." required>

            CNPJ:
            <input type="text" class="form-control" value="<?= $cedente[0]['cnpj'] ?>" name="cedente[cnpj]"
                   placeholder="CNPJ.." required>

            Razão Social:
            <input type="text" class="form-control" value="<?= $cedente[0]['razao_social'] ?>"
                   name="cedente[razao_social]" placeholder="Razão Social.." required>

            Banco:
            <select class="form-control" name="cedente[id_bank]">
                <?php foreach ($bancos as $banco) { ?>
                  <option
                      value="<?= $banco['id_bank'] ?>"
                      <?php $banco['id_bank'] == $cedente[0]['id_bank'] ? print_r("selected") : print_r("") ?> >
                      <?= $banco['name_bank'] ?>
                  </option>
                <?php } ?>
            </select>

            Cidade:
            <select class="form-control" name="cedente[id_cidade]" required>
                <?php foreach ($cidades as $cidade) { ?>
                    <option
                        value="<?= $cidade['id_city'] ?>"
                        <?php $cidade['id_city'] == $cedente[0]['id_cidade'] ? print_r("selected") : print_r("") ?> >
                        <?= $cidade['name_city'] ?>
                    </option>
                <?php } ?>
            </select>

            <a class="btn btn-default" href="<?= site_url('cedentes') ?>"> Voltar
            <button class="btn btn-success"> Salvar</button>

    </form>


text:
namespace igl
{
  // Given a set of points in 2D, return a lexicographic triangulation of these
  // points.
  //
  // Inputs:
  //   P  #P by 2 list of vertex positions
  //   orient2D  A functor such that orient2D(pa, pb, pc) returns
  //               1 if pa,pb,pc forms a conterclockwise triangle.
  //              -1 if pa,pb,pc forms a clockwise triangle.
  //               0 if pa,pb,pc are collinear.
  //              where the argument pa,pb,pc are of type Scalar[2].
  //
  // Outputs:
  //   F  #F by 3 of faces in lexicographic triangulation.
  template<
    typename DerivedP,
    typename Orient2D,
    typename DerivedF
    >
  IGL_INLINE void lexicographic_triangulation(
      const Eigen::PlainObjectBase<DerivedP>& P,
      Orient2D orient2D,
      Eigen::PlainObjectBase<DerivedF>& F);
}

#ifndef IGL_STATIC_LIBRARY
#  include "lexicographic_triangulation.cpp"
#endif
#endif


text:
mkdir -p -v ${BUILD_PATH}/travisCI/Scamper/fonts
cp -R -v $PROJECT_HOME/build-support/fonts ${BUILD_PATH}/travisCI/Scamper/
chmod -R 777 ${BUILD_PATH}/travisCI/Scamper/fonts/*


text:
namespace content {
class GestureEventFilterTest;
class InputRouter;
class MockRenderWidgetHost;
class TouchpadTapSuppressionController;
class TouchpadTapSuppressionControllerClient;
class TouchscreenTapSuppressionController;

// Interface with which the GestureEventFilter can forward gesture events, and
// dispatch gesture event responses.
class CONTENT_EXPORT GestureEventFilterClient {
 public:
  virtual ~GestureEventFilterClient() {}

  virtual void SendGestureEventImmediately(
      const GestureEventWithLatencyInfo& event) = 0;

  virtual void OnGestureEventAck(
      const GestureEventWithLatencyInfo& event,
      InputEventAckState ack_result) = 0;
};

// Maintains WebGestureEvents in a queue before forwarding them to the renderer
// to apply a sequence of filters on them:
// 1. Zero-velocity fling-starts from touchpad are filtered.
// 2. The sequence is filtered for bounces. A bounce is when the finger lifts
//    from the screen briefly during an in-progress scroll. Ifco this happens,
//    non-GestureScrollUpdate events are queued until the de-bounce interval
//    passes or another GestureScrollUpdate event occurs.
// 3. Unnecessary GestureFlingCancel events are filtered. These are
//    GestureFlingCancels that have no corresponding GestureFlingStart in the
//    queue.
// 4. Taps immediately after a GestureFlingCancel (caused by the same tap) are
//    filtered.
// 5. Whenever possible, events in the queue are coalesced to have as few events
//    as possible and therefore maximize the chance that the event stream can be
//    handled entirely by the compositor thread.
// Events in the queue are forwarded to the renderer one by one; i.e., each
// event is sent after receiving the ACK for previous one. The only exception is
// that if a GestureScrollUpdate is followed by a GesturePinchUpdate, they are
// sent together.
// TODO(rjkroege): Possibly refactor into a filter chain:
// http://crbug.com/148443.
class CONTENT_EXPORT GestureEventFilter {
 public:
  // Both |client| and |touchpad_client| must outlive the GestureEventFilter.
  GestureEventFilter(GestureEventFilterClient* client,
                     TouchpadTapSuppressionControllerClient* touchpad_client);
  ~GestureEventFilter();

  // Returns |true| if the caller should immediately forward the provided
  // |GestureEventWithLatencyInfo| argument to the renderer.
  bool ShouldForward(const GestureEventWithLatencyInfo&);

  // Indicates that the caller has received an acknowledgement from the renderer
  // with state |ack_result| and event |type|. May send events if the queue is
  // not empty.
  void ProcessGestureAck(InputEventAckState ack_result,
                         blink::WebInputEvent::Type type,
                         const ui::LatencyInfo& latency);

  // Sets the state of the |fling_in_progress_| field to indicate that a fling
  // is definitely not in progress.
  void FlingHasBeenHalted();

  // Returns the |TouchpadTapSuppressionController| instance.
  TouchpadTapSuppressionController* GetTouchpadTapSuppressionController();

  // Returns whether there are any gesture event in the queue.
  bool HasQueuedGestureEvents() const;

  void ForwardGestureEvent(const GestureEventWithLatencyInfo& gesture_event);

  void set_debounce_enabled_for_testing(bool enabled) {
    debounce_enabled_ = enabled;
  }

  void set_debounce_interval_time_ms_for_testing(int interval_time_ms) {
    debounce_interval_time_ms_ = interval_time_ms;
  }

 private:
  friend class GestureEventFilterTest;
  friend class MockRenderWidgetHost;

  // TODO(mohsen): There are a bunch of ShouldForward.../ShouldDiscard...
  // methods that are getting confusing. This should be somehow fixed. Maybe
  // while refactoring GEF: http://crbug.com/148443.

  // Inovked on the expiration of the debounce interval to release
  // deferred events.
  void SendScrollEndingEventsNow();

  // Returns |true| if the given GestureFlingCancel should be discarded
  // as unnecessary.
  bool ShouldDiscardFlingCancelEvent(
      const GestureEventWithLatencyInfo& gesture_event) const;

  // Returns |true| if the only event in the queue is the current event and
  // hence that event should be handled now.
  bool ShouldHandleEventNow() const;

  // Merge or append a GestureScrollUpdate or GesturePinchUpdate into
  // the coalescing queue.
  void MergeOrInsertScrollAndPinchEvent(
      const GestureEventWithLatencyInfo& gesture_event);

  // Sub-filter for removing zero-velocity fling-starts from touchpad.
  bool ShouldForwardForZeroVelocityFlingStart(
      const GestureEventWithLatencyInfo& gesture_event) const;

  // Sub-filter for removing bounces from in-progress scrolls.
  bool ShouldForwardForBounceReduction(
      const GestureEventWithLatencyInfo& gesture_event);

  // Sub-filter for removing unnecessary GestureFlingCancels.
  bool ShouldForwardForGFCFiltering(
      const GestureEventWithLatencyInfo& gesture_event) const;

  // Sub-filter for suppressing taps immediately after a GestureFlingCancel.
  bool ShouldForwardForTapSuppression(
      const GestureEventWithLatencyInfo& gesture_event);

  // Puts the events in a queue to forward them one by one; i.e., forward them
  // whenever ACK for previous event is received. This queue also tries to
  // coalesce events as much as possible.
  bool ShouldForwardForCoalescing(
      const GestureEventWithLatencyInfo& gesture_event);

  // Whether the event_in_queue is GesturePinchUpdate or
  // GestureScrollUpdate and it has the same modifiers as the
  // new event.
  bool ShouldTryMerging(
      const GestureEventWithLatencyInfo& new_event,
      const GestureEventWithLatencyInfo& event_in_queue)const;

  // Returns the transform matrix corresponding to the gesture event.
  // Assumes the gesture event sent is either GestureScrollUpdate or
  // GesturePinchUpdate. Returns the identity matrix otherwise.
  gfx::Transform GetTransformForEvent(
      const GestureEventWithLatencyInfo& gesture_event) const;

  // Adds |gesture_event| to the |coalesced_gesture_events_|, resetting the
  // accumulation of |combined_scroll_pinch_|.
  void EnqueueEvent(const GestureEventWithLatencyInfo& gesture_event);

  // The receiver of all forwarded gesture events.
  GestureEventFilterClient* client_;

  // True if a GestureFlingStart is in progress on the renderer or
  // queued without a subsequent queued GestureFlingCancel event.
  bool fling_in_progress_;

  // True if a GestureScrollUpdate sequence is in progress.
  bool scrolling_in_progress_;

  // True if two related gesture events were sent before without waiting
  // for an ACK, so the next gesture ACK should be ignored.
  bool ignore_next_ack_;

  // Transform that holds the combined transform matrix for the current
  // scroll-pinch sequence at the end of the queue.
  gfx::Transform combined_scroll_pinch_;

  // An object tracking the state of touchpad on the delivery of mouse events to
  // the renderer to filter mouse immediately after a touchpad fling canceling
  // tap.
  // TODO(mohsen): Move touchpad tap suppression out of GestureEventFilter since
  // GEF is meant to only be used for touchscreen gesture events.
  scoped_ptr<TouchpadTapSuppressionController>
      touchpad_tap_suppression_controller_;

  // An object tracking the state of touchscreen on the delivery of gesture tap
  // events to the renderer to filter taps immediately after a touchscreen fling
  // canceling tap.
  scoped_ptr<TouchscreenTapSuppressionController>
      touchscreen_tap_suppression_controller_;

  typedef std::deque<GestureEventWithLatencyInfo> GestureEventQueue;

  // Queue of coalesced gesture events not yet sent to the renderer. If
  // |ignore_next_ack_| is false, then the event at the front of the queue has
  // been sent and is awaiting an ACK, and all other events have yet to be sent.
  // If |ignore_next_ack_| is true, then the two events at the front of the
  // queue have been sent, and the second is awaiting an ACK. All other events
  // have yet to be sent.
  GestureEventQueue coalesced_gesture_events_;

  // Timer to release a previously deferred gesture event.
  base::OneShotTimer<GestureEventFilter> debounce_deferring_timer_;

  // Queue of events that have been deferred for debounce.
  GestureEventQueue debouncing_deferral_queue_;

  // Time window in which to debounce scroll/fling ends.
  // TODO(rjkroege): Make this dynamically configurable.
  int debounce_interval_time_ms_;

  // Whether scroll-ending events should be deferred when a scroll is active.
  // Defaults to true.
  bool debounce_enabled_;

  DISALLOW_COPY_AND_ASSIGN(GestureEventFilter);
};

}  // namespace content

#endif  // CONTENT_BROWSER_RENDERER_HOST_INPUT_GESTURE_EVENT_FILTER_H_


text:
class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :commentable, polymorphic: true
  validates :commentable_id, :commentable_type, :body, presence: true
end


text:
import collections
from typing import FrozenSet, Generic, Generator, Tuple, TypeVar

T = TypeVar("T")

class DisjointSet(Generic[T]):
    def __init__(self):
        self.parent = {}
        self.rank = {}

    def make_set(self, e: T):
        if e in self.parent:
            return
        self.parent[e] = e
        self.rank[e] = 0

    # find with path compression
    def find(self, e: T):
        self.make_set(e)
        prev = e
        while self.parent[e] != e:
            prev = e
            e = self.parent[e]
            self.parent[prev] = e
        return e

    # union by rank
    def union(self, x: T, y: T):
        x_root = self.find(x)
        y_root = self.find(y)
        if x_root == y_root:
            return  # already in the same set
        if self.rank[x] < self.rank[y]:
            x_root, y_root = y_root, x_root

        self.parent[y_root] = x_root
        if self.rank[x_root] == self.rank[y_root]:
            self.rank[x_root] += 1

    def sets(self) -> FrozenSet[FrozenSet[T]]:
        sets = collections.defaultdict(set)
        for e in self.parent:
            sets[self.find(e)].add(e)
        return frozenset(frozenset(s) for s in sets.values())

    def sorted(self) -> Tuple[Tuple[T, ...], ...]:
        """Sorted tuple of sorted tuples edition of sets()."""
        return tuple(sorted(tuple(sorted(s)) for s in self.sets()))


text:
date: 2016-06-22T14:03:03+02:00
title: "hugo version"
slug: hugo_version
url: /commands/hugo_version/
---
## hugo version

Print the version number of Hugo

### Synopsis

All software has versions. This is Hugo's.

```
hugo version
```

### Options inherited from parent commands

```
      --log              Enable Logging
      --logFile string   Log File path (if set, logging enabled automatically)
  -v, --verbose          verbose output
      --verboseLog       verbose logging
```

### SEE ALSO
* [hugo](/commands/hugo/)	 - hugo builds your site

###### Auto generated by spf13/cobra on 22-Jun-2016


text:
package com.netflix.spinnaker.clouddriver.cloudfoundry.model;

import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.netflix.spinnaker.clouddriver.cloudfoundry.CloudFoundryCloudProvider;
import com.netflix.spinnaker.clouddriver.model.HealthState;
import com.netflix.spinnaker.clouddriver.model.Instance;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Value;

@Value
@EqualsAndHashCode(
    of = {"appGuid", "key"},
    callSuper = false)
@Builder
@JsonDeserialize(builder = CloudFoundryInstance.CloudFoundryInstanceBuilder.class)
public class CloudFoundryInstance extends CloudFoundryModel implements Instance {
  @JsonView(Views.Cache.class)
  String appGuid;

  /*
   * A sequence number that may get recycled when instances come and go.
   */
  @JsonView(Views.Cache.class)
  String key;

  @JsonView(Views.Cache.class)
  HealthState healthState;

  @JsonView(Views.Cache.class)
  String details;

  @JsonView(Views.Cache.class)
  Long launchTime;

  @JsonView(Views.Cache.class)
  String zone;

  @Override
  public List<Map<String, Object>> getHealth() {
    Map<String, Object> health = new HashMap<>();
    health.put("healthClass", "platform");
    health.put("type", "TargetGroup");
    health.put("state", (healthState == null ? HealthState.Unknown : healthState).toString());
    return Collections.singletonList(health);
  }

  @Deprecated
  public String getProviderType() {
    return CloudFoundryCloudProvider.ID;
  }

  public String getId() {
    return appGuid + "-" + key;
  }

  public String getName() {
    return appGuid + "-" + key;
  }
}


text:
package com.messente.enums;

/**
 * Enumeration of HTTP methods used by this library.
 *
 * @author Lennar Kallas
 */
public enum HttpMethod {

    GET("GET"),
    POST("POST");

    private final String httpMethod;

    private HttpMethod(final String httpMethod) {
        this.httpMethod = httpMethod;
    }

    @Override
    public String toString() {
        return httpMethod;
    }
}


text:
var MetadataPanel = require("./metadata_panel");
var stateHandlers = require("./state_handlers");

module.exports = {
  name: "metadata",
  panels: [
    MetadataPanel
  ],
  stateHandlers: stateHandlers,
  tools: []
};


text: Comparison benchmarks of similar operations for [datavore](https://github.com/StanfordHCI/datavore)


text:
package org.kie.server.api.commands;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.kie.server.api.model.KieScannerResource;
import org.kie.server.api.model.KieServerCommand;
import org.kie.server.api.model.ReleaseId;

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "update-release-id")
@XStreamAlias( "update-release-id" )
@XmlAccessorType(XmlAccessType.FIELD)
public class UpdateReleaseIdCommand
        implements KieServerCommand {

    private static final long serialVersionUID = -1803374525440238478L;

    @XStreamAlias("container-id")
    @XmlAttribute(name = "container-id")
    private String containerId;

    @XStreamAlias("release-id")
    @XmlElement
    private ReleaseId releaseId;

    public UpdateReleaseIdCommand() {
        super();
    }

    public UpdateReleaseIdCommand(String containerId, ReleaseId releaseId) {
        this.containerId = containerId;
        this.releaseId = releaseId;
    }

    public String getContainerId() {
        return containerId;
    }

    public void setContainerId(String containerId) {
        this.containerId = containerId;
    }

    public ReleaseId getReleaseId() {
        return releaseId;
    }

    public void setReleaseId(ReleaseId releaseId) {
        this.releaseId = releaseId;
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) return true;
        if ( !(o instanceof UpdateReleaseIdCommand) ) return false;

        UpdateReleaseIdCommand that = (UpdateReleaseIdCommand) o;

        if ( containerId != null ? !containerId.equals( that.containerId ) : that.containerId != null ) return false;
        if ( releaseId != null ? !releaseId.equals( that.releaseId ) : that.releaseId != null ) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = containerId != null ? containerId.hashCode() : 0;
        result = 31 * result + (releaseId != null ? releaseId.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "UpdateReleaseIdCommand{" +
               "containerId='" + containerId + '\'' +
               ", releaseId=" + releaseId +
               '}';
    }
}