text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Pantheon.Common;
using Pantheon.Core;
using Pantheon.Core.Logging;
using Pantheon.Core.MessageRouting;
using Pantheon.Server.Config;
using Pantheon.Server.Config.Xml;
using Pantheon.Server.Exceptions;
using Pantheon.Server.ServiceLoader;

namespace Pantheon.Server
{
    internal static class Program
    {
        public static EventLogger EventLog;
        private static ServiceContainer _ServiceContainer;

        internal static void Main(string[] args)
        {
            string configFile = "Pantheon.xml";
            Console.Title = "Pantheon";
            Configuration document;

            AssemblyResolver.Enable();
            LoadModules();

            if (!File.Exists(configFile))
            {
                GenerateDefaultConfig(configFile);

                Console.WriteLine("Generated default config at {0}.  Press any key to exit.", configFile);
                Console.ReadKey(true);
                return;
            }
            document = LoadConfigFile();

            string name;

            ConfigurationModule services, messageDirectorElement;
            LoadConfiguration(document, out name, out services, out messageDirectorElement);

            SetConsoleTitle(name, "Connecting to Cluster");

            MessageDirector messageDirector = CreateMessageDirector(messageDirectorElement);

            var top = new NodeMessageDirector(messageDirector.MessageDirector);

            _ServiceContainer = new ServiceContainer(new MessageRouter(new NodeMessageDirector(top)));
            LogFile.Initialize(new MessageRouter(new NodeMessageDirector(top)));

            List<PantheonService> serviceRunners = LoadServices(services);

            StartServices(serviceRunners, top);

            if (!EventLog.IsConnected)
            {
                if (!EventLog.DiscoverServer())
                {
                    Console.WriteLine("|---------------------ERROR---------------------|");
                    Console.WriteLine("| No EventLogger found on Pantheon Shard.       |");
                    Console.WriteLine("| To add an event logger, insert the following  |");
                    Console.WriteLine("| directive into your <Services /> node.        |");
                    Console.WriteLine("|       |----------------------------|          |");
                    Console.WriteLine("|       | <Service>                  |          |");
                    Console.WriteLine("|       |   <Type>EventLogger</Type> |          |");
                    Console.WriteLine("|       |   <Channel>100</Channel>   |          |");
                    Console.WriteLine("|       | </Service>                 |          |");
                    Console.WriteLine("|       |----------------------------|          |");
                    Console.WriteLine("|                                               |");
                    Console.WriteLine("|-----------------------------------------------|");
                    while (Console.ReadKey(true).Key != ConsoleKey.Escape) ;
                    return;
                }
            }
            Task.Run(() =>
            {
                while (Console.ReadKey(true).Key != ConsoleKey.Escape) ;
                messageDirector.Stop();
            });
            RunServices(name, serviceRunners);
            if (!messageDirector.IsLocal)
            {
                SetConsoleTitle(name, "Connected");
            }
            else
            {
                SetConsoleTitle(name, "Message Director");
            }
            messageDirector.Run();
        }

        private static MessageDirector CreateMessageDirector(ConfigurationModule messageDirectorConfig)
        {
            MessageDirector messageDirector = new MessageDirector();
            try
            {
                messageDirector.Load(messageDirectorConfig);
                messageDirector.Start();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.ReadKey(true);
                Environment.Exit(1);
            }
            Task.Delay(500).Wait();

            if (!messageDirector.NetworkManager.IsConnected)
            {
                Console.WriteLine("Connection failed.");
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey(true);
                Environment.Exit(1);
            }
            Console.WriteLine("Press ESC to exit.");
            return messageDirector;
        }

        private static void GenerateDefaultConfig(string configFile)
        {
            var root = new ConfigurationModule("PantheonServer",
                                 new ConfigurationModule("Name", "Core Services").Attribute());

            root.Add(new ConfigurationModule("MessageDirector",
                         new ConfigurationModule("IsLocal", true),
                         new ConfigurationModule("UseTcp", false),
                         new ConfigurationModule("Address", IPAddress.Loopback),
                         new ConfigurationModule("Port", 9090)));

            root.Add(PantheonServiceLoader.GenerateDefaultServices());

            XmlConfiguration document = new XmlConfiguration(root);

            document.Save(configFile);
        }

        private static Configuration LoadConfigFile()
        {
            Configuration document = null;
            try
            {
                document = new XmlConfiguration(XDocument.Load("Pantheon.xml"));
            }
            catch (XmlException e)
            {
                Console.WriteLine("There was an error in your XML syntax:");
                Console.WriteLine(e.Message);
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey(true);
                Environment.Exit(1);
            }
            catch (Exception e)
            {
                Console.WriteLine("There was an error while parsing your Pantheon.xml:");
                Console.WriteLine(e);
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey(true);
                Environment.Exit(1);
            }

            return document;
        }

        private static void LoadConfiguration(Configuration document, out string name,
            out ConfigurationModule services, out ConfigurationModule messageDirectorElement)
        {
            ConfigurationModule server = document.Root;
            if (server == null)
            {
                throw new ServerConfigException("missing PantheonServer element.");
            }
            ConfigurationModule xname = server.Child("Name");
            name = "Undefined";
            if (xname != null)
            {
                name = xname.RawValue;
            }

            var logFile = server.Child("LogFile");

            if (logFile != null && logFile.Child("Enabled").Boolean())
            {
                LogFile.SetLogOutput(Path.Combine("LogFile", DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".log"));
            }

            services = server.Child("Services");
            if (services == null)
            {
                throw new ServerConfigException("missing PantheonServer.Services element.");
            }

            messageDirectorElement = server.Child("MessageDirector");
            if (messageDirectorElement == null)
            {
                throw new ServerConfigException("missing PantheonServer.MessageDirector element.");
            }
        }

        private static void LoadModules()
        {
            PantheonServiceLoader.LoadAssembly(Assembly.GetExecutingAssembly());

            if (!Directory.Exists("ServerModules"))
            {
                Directory.CreateDirectory("ServerModules");
            }

            foreach (string file in Directory.GetFiles("ServerModules"))
            {
                if (!file.EndsWith(".dll"))
                {
                    continue;
                }
                PantheonServiceLoader.LoadAssembly(file);
            }

            PantheonInitializer.InitializeAll();
        }

        private static List<PantheonService> LoadServices(ConfigurationModule services)
        {
            _ServiceContainer.LoadServices(services);

            var serviceRunners = _ServiceContainer.Services;

            return serviceRunners;
        }

        private static void RunServices(string name, List<PantheonService> serviceRunners)
        {
            foreach (var service in serviceRunners)
            {
                Task.Run(() =>
                {
                    try
                    {
                        service.Run();
                    }
                    catch (Exception e)
                    {
                        EventLog.Log(LogLevel.Critical, "Service {0} on {1} crashed.", service.Name, name);
                        EventLog.LogCritical(e);
                    }
                });
            }
        }

        private static void SetConsoleTitle(string name, string message)
        {
            Console.Title = string.Format("Pantheon Server - {0} ({1})", name, message);
        }

        private static void StartServices(List<PantheonService> serviceRunners, NodeMessageDirector top)
        {
            ServiceManager.EnableServiceDirectory(new MessageRouter(new NodeMessageDirector(top)));

            EventLog = new EventLogger(new MessageRouter(top.AddMessageDirector()));
            EventLog.SetLoggerName("MD");
            EventLog.DiscoverServer();

            foreach (var service in serviceRunners)
            {
                service.MessageDirector = new NodeMessageDirector(top);
                try
                {
                    service.Start();
                }
                catch (Exception e)
                {
                    const string format = "Failed to start {0} service due to a {1}";
                    if (EventLog.IsConnected)
                    {
                        EventLog.Log(LogLevel.Critical, format, service.Name, e.GetType().Name);
                        EventLog.Log(e);
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(format, service.Name, e.GetType().Name);
                        Console.WriteLine(e);
                        Console.ForegroundColor = ConsoleColor.Gray;
                    }
                }
            }
        }
    }
}


text:
/**
 * A simple class to display a button.
 *
 * There are various different styles of Button you can create by using the {@link #icon},
 * {@link #iconCls}, {@link #iconAlign}, {@link #ui}, and {@link #text}
 * configurations.
 *
 * ## Simple Button
 *
 * Here is a Button in it's simplest form:
 *
 *     @example miniphone
 *     var button = Ext.create('Ext.Button', {
 *         text: 'Button'
 *     });
 *     Ext.Viewport.add({ xtype: 'container', padding: 10, items: [button] });
 *
 * ## Icons
 *
 * You can also create a Button with just an icon using the {@link #iconCls} configuration:
 *
 *     @example miniphone
 *     var button = Ext.create('Ext.Button', {
 *         iconCls: 'refresh'
 *     });
 *     Ext.Viewport.add({ xtype: 'container', padding: 10, items: [button] });
 *
 * Sencha provides the "Font" and "PNG" icons packs from http://wwww.pictos.cc.
 * Use icons with the {@link Global_CSS#icon icon} mixin in your Sass.
 *
 * ## Badges
 *
 * Buttons can also have a badge on them, by using the {@link #badgeText} configuration:
 *
 *     @example
 *     Ext.create('Ext.Container', {
 *         fullscreen: true,
 *         padding: 10,
 *         items: {
 *             xtype: 'button',
 *             text: 'My Button',
 *             badgeText: '2'
 *         }
 *     });
 *
 * ## UI
 *
 * Buttons also come with a range of different default UIs. Here are the included UIs
 * available (if {@link #$include-button-uis $include-button-uis} is set to `true`):
 *
 * - **normal** - a basic gray button
 * - **back** - a back button
 * - **forward** - a forward button
 * - **round** - a round button
 * - **action** - shaded using the {@link Global_CSS#$active-color $active-color} (dark blue by default)
 * - **decline** - shaded using the {@link Global_CSS#$alert-color $alert-color} (red by default)
 * - **confirm** - shaded using the {@link Global_CSS#$confirm-color $confirm-color} (green by default)
 *
 * You can also append `-round` to each of the last three UI's to give it a round shape:
 *
 * - **action-round**
 * - **decline-round**
 * - **confirm-round**
 *
 * And setting them is very simple:
 *
 *     var uiButton = Ext.create('Ext.Button', {
 *         text: 'My Button',
 *         ui: 'action'
 *     });
 *
 * And how they look:
 *
 *     @example miniphone preview
 *     Ext.create('Ext.Container', {
 *         fullscreen: true,
 *         padding: 4,
 *         defaults: {
 *             xtype: 'button',
 *             margin: 5
 *         },
 *         layout: {
 *             type: 'vbox',
 *             align: 'center'
 *         },
 *         items: [
 *             { ui: 'normal', text: 'normal' },
 *             { ui: 'round', text: 'round' },
 *             { ui: 'action', text: 'action' },
 *             { ui: 'decline', text: 'decline' },
 *             { ui: 'confirm', text: 'confirm' }
 *         ]
 *     });
 *
 * Note that the default {@link #ui} is **normal**.
 *
 * You can also use the {@link #sencha-button-ui sencha-button-ui} CSS Mixin to create your own UIs.
 *
 * ## Example
 *
 * This example shows a bunch of icons on the screen in two toolbars. When you click on the center
 * button, it switches the {@link #iconCls} on every button on the page.
 *
 *     @example preview
 *     Ext.createWidget('container', {
 *         fullscreen: true,
 *         layout: {
 *             type: 'vbox',
 *             pack:'center',
 *             align: 'center'
 *         },
 *         items: [
 *             {
 *                 xtype: 'button',
 *                 text: 'Change iconCls',
 *                 handler: function() {
 *                     // classes for all the icons to loop through.
 *                     var availableIconCls = [
 *                         'action', 'add', 'arrow_down', 'arrow_left',
 *                         'arrow_right', 'arrow_up', 'compose', 'delete',
 *                         'organize', 'refresh', 'reply', 'search',
 *                         'settings', 'star', 'trash', 'maps', 'locate',
 *                         'home'
 *                     ];
 *                     // get the text of this button,
 *                     // so we know which button we don't want to change
 *                     var text = this.getText();
 *
 *                     // use ComponentQuery to find all buttons on the page
 *                     // and loop through all of them
 *                     Ext.Array.forEach(Ext.ComponentQuery.query('button'), function(button) {
 *                         // if the button is the change iconCls button, continue
 *                         if (button.getText() === text) {
 *                             return;
 *                         }
 *
 *                         // get the index of the new available iconCls
 *                         var index = availableIconCls.indexOf(button.getIconCls()) + 1;
 *
 *                         // update the iconCls of the button with the next iconCls, if one exists.
 *                         // if not, use the first one
 *                         button.setIconCls(availableIconCls[(index === availableIconCls.length) ? 0 : index]);
 *                     });
 *                 }
 *             },
 *             {
 *                 xtype: 'toolbar',
 *                 docked: 'top',
 *                 items: [
 *                     { xtype: 'spacer' },
 *                     { iconCls: 'action' },
 *                     { iconCls: 'add' },
 *                     { iconCls: 'arrow_down' },
 *                     { iconCls: 'arrow_left' },
 *                     { iconCls: 'arrow_up' },
 *                     { iconCls: 'compose' },
 *                     { iconCls: 'delete' },
 *                     { iconCls: 'organize' },
 *                     { iconCls: 'refresh' },
 *                     { xtype: 'spacer' }
 *                 ]
 *             },
 *             {
 *                 xtype: 'toolbar',
 *                 docked: 'bottom',
 *                 ui: 'light',
 *                 items: [
 *                     { xtype: 'spacer' },
 *                     { iconCls: 'reply' },
 *                     { iconCls: 'search' },
 *                     { iconCls: 'settings' },
 *                     { iconCls: 'star' },
 *                     { iconCls: 'trash' },
 *                     { iconCls: 'maps' },
 *                     { iconCls: 'locate' },
 *                     { iconCls: 'home' },
 *                     { xtype: 'spacer' }
 *                 ]
 *             }
 *         ]
 *     });
 *
 */
Ext.define('Ext.Button', {
    extend: 'Ext.Component',

    xtype: 'button',

    isButton: true,

    /**
     * @event tap
     * @preventable doTap
     * Fires whenever a button is tapped.
     * @param {Ext.Button} this The item added to the Container.
     * @param {Ext.EventObject} e The event object.
     */

    /**
     * @event release
     * @preventable doRelease
     * Fires whenever the button is released.
     * @param {Ext.Button} this The item added to the Container.
     * @param {Ext.EventObject} e The event object.
     */

    cachedConfig: {
        /**
         * @cfg {String} pressedCls
         * The CSS class to add to the Button when it is pressed.
         * @accessor
         */
        pressedCls: Ext.baseCSSPrefix + 'button-pressing',

        /**
         * @cfg {String} badgeCls
         * The CSS class to add to the Button's badge, if it has one.  Badges appear as small numbers, letters, or icons that sit on top of your button.  For instance, a small red number indicating how many updates are available.
         * @accessor
         */
        badgeCls: Ext.baseCSSPrefix + 'badge',

        /**
         * @cfg {String} hasBadgeCls
         * The CSS class to add to the Button if it has a badge (note that this goes on the
         * Button element itself, not on the badge element).
         * @private
         * @accessor
         */
        hasBadgeCls: Ext.baseCSSPrefix + 'hasbadge',

        /**
         * @cfg {String} labelCls
         * The CSS class to add to the field's label element.
         * @accessor
         */
        labelCls: Ext.baseCSSPrefix + 'button-label',

        /**
         * @cfg {String} iconCls
         * Optional CSS class to add to the icon element. This is useful if you want to use a CSS
         * background image to create your Button icon.
         * @accessor
         */
        iconCls: null
    },

    config: {
        /**
         * @cfg {String} badgeText
         * Optional badge text.  Badges appear as small numbers, letters, or icons that sit on top of your button.  For instance, a small red number indicating how many updates are available.
         * @accessor
         */
        badgeText: null,

        /**
         * @cfg {String} text
         * The Button text.
         * @accessor
         */
        text: null,

        /**
         * @cfg {String} icon
         * Url to the icon image to use if you want an icon to appear on your button.
         * @accessor
         */
        icon: false,

        /**
         * @cfg {String} iconAlign
         * The position within the Button to render the icon Options are: `top`, `right`, `bottom`, `left` and `center` (when you have
         * no {@link #text} set).
         * @accessor
         */
        iconAlign: 'left',

        /**
         * @cfg {Number/Boolean} pressedDelay
         * The amount of delay between the `tapstart` and the moment we add the `pressedCls` (in milliseconds).
         * Settings this to `true` defaults to 100ms.
         */
        pressedDelay: 0,

        /**
         * @cfg {Function} handler
         * The handler function to run when the Button is tapped on.
         * @accessor
         */
        handler: null,

        /**
         * @cfg {Object} scope
         * The scope to fire the configured {@link #handler} in.
         * @accessor
         */
        scope: null,

        /**
         * @cfg {String} autoEvent
         * Optional event name that will be fired instead of `tap` when the Button is tapped on.
         * @accessor
         */
        autoEvent: null,

        /**
         * @cfg {String} ui
         * The ui style to render this button with. The valid default options are:
         *
         * - `null` - a basic gray button (default).
         * - `'back'` - a back button.
         * - `'forward'` - a forward button.
         * - `'round'` - a round button.
         * - `'plain'`
         * - `'action'` - shaded using the {@link Global_CSS#$active-color $active-color} (dark blue by default).
         * - `'decline'` - shaded using the {@link Global_CSS#$alert-color $alert-color} (red by default).
         * - `'confirm'` - shaded using the {@link Global_CSS#$confirm-color $confirm-color} (green by default).
         *
         * You can also append `-round` to each of the last three UI's to give it a round shape:
         *
         * - **action-round**
         * - **decline-round**
         * - **confirm-round**
         *
         * @accessor
         */
        ui: null,

        /**
         * @cfg {String} html The HTML to put in this button.
         *
         * If you want to just add text, please use the {@link #text} configuration.
         */

        /**
         * @cfg
         * @inheritdoc
         */
        baseCls: Ext.baseCSSPrefix + 'button'
    },

    defaultBindProperty: 'text',

    template: [
        {
            tag: 'span',
            reference: 'badgeElement',
            hidden: true
        },
        {
            tag: 'span',
            className: Ext.baseCSSPrefix + 'button-icon',
            reference: 'iconElement'
        },
        {
            tag: 'span',
            reference: 'textElement',
            hidden: true
        }
    ],

    initialize: function() {
        this.callParent();

        this.element.on({
            scope      : this,
            tap        : 'onTap',
            touchstart : 'onPress',
            touchend   : 'onRelease'
        });
    },

    /**
     * @private
     */
    updateBadgeText: function(badgeText) {
        var element = this.element,
            badgeElement = this.badgeElement;

        if (badgeText) {
            badgeElement.show();
            badgeElement.setText(badgeText);
        }
        else {
            badgeElement.hide();
        }

        element[(badgeText) ? 'addCls' : 'removeCls'](this.getHasBadgeCls());
    },

    /**
     * @private
     */
    updateText: function(text) {
        var textElement = this.textElement;

        if (textElement) {
            if (text) {
                textElement.show();
                textElement.setHtml(text);
            } else {
                textElement.hide();
            }

            this.refreshIconAlign();
        }
    },

    /**
     * @private
     */
    updateHtml: function(html) {
        var textElement = this.textElement;

        if (html) {
            textElement.show();
            textElement.setHtml(html);
        }
        else {
            textElement.hide();
        }
    },

    /**
     * @private
     */
    updateBadgeCls: function(badgeCls, oldBadgeCls) {
        this.badgeElement.replaceCls(oldBadgeCls, badgeCls);
    },

    /**
     * @private
     */
    updateHasBadgeCls: function(hasBadgeCls, oldHasBadgeCls) {
        var element = this.element;

        if (element.hasCls(oldHasBadgeCls)) {
            element.replaceCls(oldHasBadgeCls, hasBadgeCls);
        }
    },

    /**
     * @private
     */
    updateLabelCls: function(labelCls, oldLabelCls) {
        this.textElement.replaceCls(oldLabelCls, labelCls);
    },

    /**
     * @private
     */
    updatePressedCls: function(pressedCls, oldPressedCls) {
        var element = this.element;

        if (element.hasCls(oldPressedCls)) {
            element.replaceCls(oldPressedCls, pressedCls);
        }
    },

    /**
     * @private
     */
    updateIcon: function(icon) {
        var me = this,
            element = me.iconElement;

        if (icon) {
            me.showIconElement();
            element.setStyle('background-image', 'url(' + icon + ')');
            me.refreshIconAlign();
        } else {
            element.setStyle('background-image', '');
            if (!me.getIconCls()) {
                me.hideIconElement();
            }
        }
    },

    /**
     * @private
     */
    updateIconCls: function(iconCls, oldIconCls) {
        var me = this,
            element = me.iconElement;

        if (iconCls) {
            me.showIconElement();
            element.replaceCls(oldIconCls, iconCls);
            me.refreshIconAlign();
        } else {
			element.removeCls(oldIconCls);
            if (!me.getIcon()) {
                me.hideIconElement();
            }
        }
    },

    /**
     * @private
     */
    updateIconAlign: function(alignment, oldAlignment) {
        var element = this.element,
            baseCls = Ext.baseCSSPrefix + 'iconalign-';

        if (!this.getText()) {
            alignment = "center";
        }

        element.removeCls(baseCls + "center");
        element.removeCls(baseCls + oldAlignment);
        if (this.getIcon() || this.getIconCls()) {
            element.addCls(baseCls + alignment);
        }
    },

    refreshIconAlign: function() {
        this.updateIconAlign(this.getIconAlign());
    },

    applyAutoEvent: function(autoEvent) {
        var me = this;

        if (typeof autoEvent == 'string') {
            autoEvent = {
                name : autoEvent,
                scope: me.scope || me
            };
        }

        return autoEvent;
    },

    /**
     * @private
     */
    updateAutoEvent: function(autoEvent) {
        var name  = autoEvent.name,
            scope = autoEvent.scope;

        this.setHandler(function() {
            scope.fireEvent(name, scope, this);
        });

        this.setScope(scope);
    },

    /**
     * Used by `icon` and `iconCls` configurations to hide the icon element.
     * @private
     */
    hideIconElement: function() {
        this.iconElement.removeCls(Ext.baseCSSPrefix + 'shown');
        this.iconElement.addCls(Ext.baseCSSPrefix + 'hidden');
    },

    /**
     * Used by `icon` and `iconCls` configurations to show the icon element.
     * @private
     */
    showIconElement: function() {
        this.iconElement.removeCls(Ext.baseCSSPrefix + 'hidden');
        this.iconElement.addCls(Ext.baseCSSPrefix + 'shown');
    },

    /**
     * We override this to check for '{ui}-back'. This is because if you have a UI of back, you need to actually add two class names.
     * The ui class, and the back class:
     *
     * `ui: 'action-back'` would turn into:
     *
     * `class="x-button-action x-button-back"`
     *
     * But `ui: 'action'` would turn into:
     *
     * `class="x-button-action"`
     *
     * So we just split it up into an array and add both of them as a UI, when it has `back`.
     * @private
     */
    applyUi: function(config) {
        if (config && Ext.isString(config)) {
            var array  = config.split('-');
            if (array && (array[1] == "back" || array[1] == "forward")) {
                return array;
            }
        }

        return config;
    },

    getUi: function() {
        //Now that the UI can sometimes be an array, we need to check if it an array and return the proper value.
        var ui = this._ui;
        if (Ext.isArray(ui)) {
            return ui.join('-');
        }
        return ui;
    },

    applyPressedDelay: function(delay) {
        if (Ext.isNumber(delay)) {
            return delay;
        }
        return (delay) ? 100 : 0;
    },

    /**
     * @private
     */
    onPress: function() {
        var me = this,
            element = me.element,
            pressedDelay = me.getPressedDelay(),
            pressedCls = me.getPressedCls();

        if (!me.getDisabled()) {
            if (pressedDelay > 0) {
                me.pressedTimeout = Ext.defer(function() {
                    delete me.pressedTimeout;
                    if (element) {
                        element.addCls(pressedCls);
                    }
                }, pressedDelay);
            }
            else {
                element.addCls(pressedCls);
            }
        }
    },

    /**
     * @private
     */
    onRelease: function(e) {
        this.fireAction('release', [this, e], 'doRelease');
    },

    /**
     * @private
     */
    doRelease: function(me, e) {
        if (!me.getDisabled()) {
            if (me.hasOwnProperty('pressedTimeout')) {
                clearTimeout(me.pressedTimeout);
                delete me.pressedTimeout;
            }
            else {
                me.element.removeCls(me.getPressedCls());
            }
        }
    },

    /**
     * @private
     */
    onTap: function(e) {
        if (this.getDisabled()) {
            return false;
        }

        this.fireAction('tap', [this, e], 'doTap');
    },

    /**
     * @private
     */
    doTap: function(me, e) {
        var handler = me.getHandler();

        if (!handler) {
            return;
        }

        //this is done so if you hide the button in the handler, the tap event will not fire on the new element
        //where the button was.
        if (e && e.preventDefault) {
            e.preventDefault();
        }

        Ext.callback(handler, me.getScope(), [me, e], 0, me);
    }
});

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2015 Danilo Reinert
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>io.reinert.requestor</groupId>
    <artifactId>requestor-project</artifactId>
    <version>1.3.0-SNAPSHOT</version>
  </parent>

  <packaging>pom</packaging>

  <groupId>io.reinert.requestor</groupId>
  <artifactId>requestor-parent</artifactId>

  <modules>
    <module>core</module>
    <module>impl</module>
    <module>ext</module>
  </modules>

  <build>
    <plugins>
      <!-- Skip GWTTests during JUnit tests -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven-surefire-plugin.version}</version>
        <configuration>
          <includes>
            <include>**/*TestSuite.java</include>
          </includes>
          <excludes>
            <exclude>**/*GwtTest*.java</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>

    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>gwt-maven-plugin</artifactId>
          <version>${gwt-maven-plugin.version}</version>
          <configuration>
            <extraJvmArgs>-Xss16M -Xms256M -Xmx2048M ${gwt.extraJvmArgs}</extraJvmArgs>
            <htmlunit>Chrome</htmlunit>
            <includes>**/*GwtTestSuite.java</includes>
            <testTimeOut>180</testTimeOut>
<!--            <logLevel>DEBUG</logLevel>-->
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

  <profiles>
    <profile>
      <id>project</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-checkstyle-plugin</artifactId>
            <version>${maven-checkstyle-plugin.version}</version>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>


text:
* Add support for 10.0.0

## 9.2.1

* Updated TOC files for 9.2.5, 3.4.0, 2.5.4, and 1.14.3.

## 9.2.0

* Updated TOC files for 9.2.0, 2.5.3, and 1.14.2.
* Packaged the addon using multiple TOC files

## 9.1.1

* Updated TOC files

## 9.1.0

* Updated TOC files for 9.1.0

## 9.0.4

* Add Burning Crusade Classic support

## 9.0.3

* If you create a macro with a name that starts with #, tullaRange will now use spell cost checks to determine if the ability is usable (thanks merijn)
* Updated TOCs for various wow versions

## 9.0.2

* Updated TOC for 9.0.2

## 9.0.1

* Fix a nil value exception when moving pet actions

## 9.0.0

* Updated for World of Warcraft 9.0.1 - Shadowlands

## 8.3.2

* Added support for pet action buttons. You can disable this via `/run tullaRange:SetEnablePetActions(false)`
* Replaced the attack flash animation with a smoother one. You can disable this via `/run tullaRange:SetEnableFlashAnimations(false)`

## 8.3.1

* Increase performance a bit by only updating attack actions and actions with a range

## 8.3.0

* Update for WoW 8.3.0

## 8.2.7

* Use a C_Timer.After handler for updates

## 8.2.6

* Update classic TOC for 1.13.2
* Update packager to use github actions

## 8.2.5

* Updated TOC for 8.2.5

## 8.2.2

* Added classic build

## 8.2.1

* Automated releases

## 8.2.0

* Updated TOC for 8.2.0
* Verified the addon works with classic
* Cleaned up code a tiny bit


text:
require 'rails/generators/active_record'

module Seoable
  module Generators
    class InstallGenerator < Rails::Generators::Base
      include ::Rails::Generators::Migration

      source_root File.expand_path('../templates', __FILE__)

      desc 'Installs Seoable and generates the necessary migrations'

      def create_migrations
        migration_template 'create_seo_details.rb',
                           'db/migrate/create_seo_details.rb'
      end

      def create_initializer
        copy_file 'initializers/seoable.rb', 'config/initializers/seoable.rb'
      end

      def self.next_migration_number(dirname)
        ActiveRecord::Generators::Base.next_migration_number(dirname)
      end
    end
  end
end


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

describe("Ext.Element.insertion", function() {
    var proto = Ext.Element.prototype,
        el, testEl,
        span, testSpanEl,
        child1, child2, child3;

    beforeEach(function() {
        testEl = Ext.getBody().createChild({
            id: 'ExtElementHelper',
            children: [
                {id: 'child1'},
                {id: 'child2'},
                {id: 'child3'}
            ]
        });

        testSpanEl = Ext.getBody().createChild({
            id  : 'ExtElementSpanHelper',
            tag : 'span'
        });

        el    = new Ext.Element(Ext.getDom(testEl));
        span = new Ext.Element(Ext.getDom(testSpanEl));

        child1 = Ext.get('child1');
        child2 = Ext.get('child2');
        child3 = Ext.get('child3');
    });

    afterEach(function() {
        testEl.remove();
        testSpanEl.remove();
    });
    describe("appendChild", function() {
        it("should append the child", function() {
            expect(el.contains(span)).toBeFalsy();

            el.appendChild(span);

            expect(el.contains(span)).toBeTruthy();
        });
    });

    describe("appendTo", function() {
        it("should append the el to the specified el", function() {
            expect(span.contains(el)).toBeFalsy();

            el.appendTo(span);

            expect(span.contains(el)).toBeTruthy();
        });
    });

    describe("insertBefore", function() {
        it("should insert the el before the specified el", function() {
            var nodes = Ext.getDom(child1).parentNode.childNodes,
                array = Ext.toArray(nodes);

            expect(Ext.Array.indexOf(array, Ext.getDom(child2))).toEqual(1);

            child2.insertBefore(child1);

            nodes = Ext.getDom(child1).parentNode.childNodes;
            array = Ext.toArray(nodes);

            expect(Ext.Array.indexOf(array, Ext.getDom(child2))).toEqual(0);
        });
    });

    describe("insertAfter", function() {
        it("should insert the el after the specified el", function() {
            var nodes = Ext.getDom(child1).parentNode.childNodes,
                array = Ext.toArray(nodes);

            expect(Ext.Array.indexOf(array, Ext.getDom(child2))).toEqual(1);

            child2.insertAfter(child3);

            nodes = Ext.getDom(child1).parentNode.childNodes;
            array = Ext.toArray(nodes);

            expect(Ext.Array.indexOf(array, Ext.getDom(child2))).toEqual(2);
        });
    });

    describe("insertFirst", function() {
        it("should insert the el into the specified el", function() {
            var nodes = Ext.getDom(child2).childNodes;
            expect(nodes.length).toEqual(0);

            child2.insertFirst(child1);

            nodes = Ext.getDom(child2).childNodes;
            expect(nodes.length).toEqual(1);
        });
    });

    describe("insertSibling", function() {
        describe("when array", function() {
            describe("after", function() {
                it("should create each of the elements and add them to the el parent", function() {
                    var nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(3);

                    child1.insertSibling([
                        {id: 'sibling1'},
                        {id: 'sibling2'}
                    ], 'after');

                    nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(5);
                });
            });

            describe("before", function() {
                it("should create each of the elements and add them to the el parent", function() {
                    var nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(3);

                    child1.insertSibling([
                        {id: 'sibling1'},
                        {id: 'sibling2'}
                    ], 'before');

                    nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(5);
                });
            });
        });

        describe("when Ext.Element", function() {
            describe("after", function() {
                it("should move the element next to the el", function() {
                    var nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(3);

                    child1.insertSibling(span, 'after');

                    nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(4);
                });
            });

            describe("before", function() {
                it("should move the element next to the el", function() {
                    var nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(3);

                    child1.insertSibling(span, 'before');

                    nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(4);
                });
            });
        });

        describe("other", function() {
            describe("after", function() {
                it("should move the element next to the el", function() {
                    var nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(3);

                    child1.insertSibling({
                        id: 'sibling1'
                    }, 'after');

                    nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(4);
                });

                it("should move the element next to the el", function() {
                    var nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(3);

                    child3.insertSibling({
                        id: 'sibling1'
                    }, 'after');

                    nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(4);
                });
            });

            describe("before", function() {
                it("should move the element next to the el", function() {
                    var nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(3);

                    child1.insertSibling({
                        id: 'sibling1'
                    }, 'before');

                    nodes = Ext.getDom(el).childNodes;
                    expect(nodes.length).toEqual(4);
                });

                describe("return dom", function() {
                    it("should move the element next to the el", function() {
                        var nodes = Ext.getDom(el).childNodes,
                            dom;

                        expect(nodes.length).toEqual(3);

                        dom = child1.insertSibling({
                            id: 'sibling1'
                        }, 'before', true);

                        nodes = Ext.getDom(el).childNodes;
                        expect(nodes.length).toEqual(4);
                        expect(dom).toBeDefined();
                    });
                });
            });
        });
    });

    describe("replace", function() {
        it("should replace the passed element with this element", function() {
            var nodes = Ext.getDom(el).childNodes;
            expect(nodes.length).toEqual(3);

            child1.replace(child2);

            nodes = Ext.getDom(el).childNodes;
            expect(nodes.length).toEqual(2);
        });
    });

    describe("replaceWith", function() {
        it("should replace this element with the passed element", function() {
            var nodes = Ext.getDom(el).childNodes;
            expect(nodes.length).toEqual(3);

            child1.replaceWith({tag: "div", cls: "childtestdiv"});

            expect(child1.hasCls("childtestdiv"));

            nodes = Ext.getDom(el).childNodes;
            expect(nodes.length).toEqual(3);
        });
    });

    describe("createChild", function() {
        it("should create a child", function() {
            var nodes = Ext.getDom(el).childNodes;
            expect(nodes.length).toEqual(3);

            el.createChild({id: 'child4'});

            nodes = Ext.getDom(el).childNodes;
            expect(nodes.length).toEqual(4);
        });

        it("should create a child before an el", function() {
            var nodes = Ext.getDom(el).childNodes,
                array = Ext.toArray(nodes);

            expect(nodes.length).toEqual(3);
            expect(Ext.Array.indexOf(array, Ext.getDom(child2))).toEqual(1);

            el.createChild({id: 'child4'}, child2);

            nodes = Ext.getDom(el).childNodes;
            array = Ext.toArray(nodes);

            expect(nodes.length).toEqual(4);
            expect(Ext.Array.indexOf(array, Ext.getDom(child2))).toEqual(2);
        });
    });

    describe("wrap", function() {
        it("should wrap the element", function() {
            var parent = Ext.getDom(child1).parentNode;

            child1.wrap({
                cls: 'wrapper'
            });

            expect(Ext.getDom(child1).parentNode.parentNode).toEqual(parent);
            expect(Ext.getDom(child1).parentNode.className).toEqual('wrapper');
        });

        it("return the el", function() {
            var node = child1.wrap({
                cls: 'wrapper'
            });

            expect(Ext.isElement(node)).toBeFalsy();
        });

        it("return the dom", function() {
            var node = child1.wrap({
                cls: 'wrapper'
            }, true);

            expect(Ext.isElement(node)).toBeTruthy();
        });
    });

    describe("insertHtml", function() {
        describe("beforeBegin", function() {
            it("should insert the html", function() {
                expect(Ext.getDom(el).childNodes.length).toEqual(3);

                child1.insertHtml('beforeBegin', '

');

                expect(Ext.getDom(el).childNodes.length).toEqual(4);
            });
        });

        describe("afterBegin", function() {
            it("should insert the html", function() {
                expect(Ext.getDom(child1).childNodes.length).toEqual(0);

                child1.insertHtml('afterBegin', '

');

                expect(Ext.getDom(child1).childNodes.length).toEqual(1);
            });
        });

        describe("beforeEnd", function() {
            it("should insert the html", function() {
                expect(Ext.getDom(child1).childNodes.length).toEqual(0);

                child1.insertHtml('beforeEnd', '

');

                expect(Ext.getDom(child1).childNodes.length).toEqual(1);
            });
        });

        describe("afterEnd", function() {
            it("should insert the html", function() {
                expect(Ext.getDom(el).childNodes.length).toEqual(3);

                child1.insertHtml('afterEnd', '

');

                expect(Ext.getDom(el).childNodes.length).toEqual(4);
            });
        });

        it("should return a dom", function() {
            var node = child1.insertHtml('afterEnd', '

');

            expect(Ext.isElement(node)).toBeTruthy();
        });

        it("should return an el", function() {
            var node = child1.insertHtml('afterEnd', '

', true);

            expect(Ext.isElement(node)).toBeFalsy();
        });
    });
}, "/src/dom/Element.insertion.js");


text:
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using MvcTemplate.Components.Security;
using MvcTemplate.Data.Core;
using MvcTemplate.Objects;
using MvcTemplate.Services;
using MvcTemplate.Tests.Data;
using NSubstitute;
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using Xunit;

namespace MvcTemplate.Tests.Unit.Services
{
    public class AccountServiceTests : IDisposable
    {
        private AccountService service;
        private TestingContext context;
        private Account account;
        private IHasher hasher;

        public AccountServiceTests()
        {
            context = new TestingContext();
            hasher = Substitute.For<IHasher>();
            hasher.HashPassword(Arg.Any<String>()).Returns(info => info.Arg<String>() + "Hashed");

            context.DropData();
            SetUpData();

            service = new AccountService(new UnitOfWork(context), hasher);
            service.CurrentAccountId = account.Id;
        }
        public void Dispose()
        {
            service.Dispose();
            context.Dispose();
        }

        #region Get<TView>(Int32 id)

        [Fact]
        public void Get_ReturnsViewById()
        {
            AccountView actual = service.Get<AccountView>(account.Id);
            AccountView expected = Mapper.Map<AccountView>(account);

            Assert.Equal(expected.CreationDate, actual.CreationDate);
            Assert.Equal(expected.RoleTitle, actual.RoleTitle);
            Assert.Equal(expected.IsLocked, actual.IsLocked);
            Assert.Equal(expected.Username, actual.Username);
            Assert.Equal(expected.Email, actual.Email);
            Assert.Equal(expected.Id, actual.Id);
        }

        #endregion

        #region GetViews()

        [Fact]
        public void GetViews_ReturnsAccountViews()
        {
            AccountView[] actual = service.GetViews().ToArray();
            AccountView[] expected = context
                .Set<Account>()
                .ProjectTo<AccountView>()
                .OrderByDescending(view => view.Id)
                .ToArray();

            for (Int32 i = 0; i < expected.Length || i < actual.Length; i++)
            {
                Assert.Equal(expected[i].CreationDate, actual[i].CreationDate);
                Assert.Equal(expected[i].RoleTitle, actual[i].RoleTitle);
                Assert.Equal(expected[i].IsLocked, actual[i].IsLocked);
                Assert.Equal(expected[i].Username, actual[i].Username);
                Assert.Equal(expected[i].Email, actual[i].Email);
                Assert.Equal(expected[i].Id, actual[i].Id);
            }
        }

        #endregion

        #region IsLoggedIn(IPrincipal user)

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void IsLoggedIn_ReturnsIsAuthenticated(Boolean isAuthenticated)
        {
            IPrincipal user = Substitute.For<IPrincipal>();
            user.Identity.IsAuthenticated.Returns(isAuthenticated);

            Boolean actual = service.IsLoggedIn(user);
            Boolean expected = isAuthenticated;

            Assert.Equal(expected, actual);
        }

        #endregion

        #region IsActive(Int32 id)

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void IsActive_ReturnsAccountState(Boolean isLocked)
        {
            account.IsLocked = isLocked;
            context.Update(account);
            context.SaveChanges();

            Boolean actual = service.IsActive(account.Id);
            Boolean expected = !isLocked;

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void IsActive_NoAccount_ReturnsFalse()
        {
            Assert.False(service.IsActive(0));
        }

        #endregion

        #region Recover(AccountRecoveryView view)

        [Fact]
        public void Recover_NoEmail_ReturnsNull()
        {
            AccountRecoveryView view = ObjectFactory.CreateAccountRecoveryView();
            view.Email = "not@existing.email";

            Assert.Null(service.Recover(view));
        }

        [Fact]
        public void Recover_Information()
        {
            AccountRecoveryView view = ObjectFactory.CreateAccountRecoveryView();
            account.RecoveryTokenExpirationDate = DateTime.Now.AddMinutes(30);
            String oldToken = account.RecoveryToken;
            view.Email = view.Email.ToUpper();

            account.RecoveryToken = service.Recover(view);

            Account actual = context.Set<Account>().AsNoTracking().Single();
            Account expected = account;

            Assert.InRange(actual.RecoveryTokenExpirationDate.Value.Ticks,
                expected.RecoveryTokenExpirationDate.Value.Ticks - TimeSpan.TicksPerSecond,
                expected.RecoveryTokenExpirationDate.Value.Ticks + TimeSpan.TicksPerSecond);
            Assert.Equal(expected.RecoveryToken, actual.RecoveryToken);
            Assert.Equal(expected.CreationDate, actual.CreationDate);
            Assert.Equal(expected.IsLocked, actual.IsLocked);
            Assert.Equal(expected.Passhash, actual.Passhash);
            Assert.Equal(expected.Username, actual.Username);
            Assert.NotEqual(oldToken, actual.RecoveryToken);
            Assert.Equal(expected.RoleId, actual.RoleId);
            Assert.Equal(expected.Email, actual.Email);
            Assert.Equal(expected.Id, actual.Id);
            Assert.NotNull(actual.RecoveryToken);
        }

        #endregion

        #region Reset(AccountResetView view)

        [Fact]
        public void Reset_Account()
        {
            AccountResetView view = ObjectFactory.CreateAccountResetView();
            account.Passhash = hasher.HashPassword(view.NewPassword);
            account.RecoveryTokenExpirationDate = null;
            account.RecoveryToken = null;

            service.Reset(view);

            Account actual = context.Set<Account>().AsNoTracking().Single();
            Account expected = account;

            Assert.Equal(expected.RecoveryTokenExpirationDate, actual.RecoveryTokenExpirationDate);
            Assert.Equal(expected.RecoveryToken, actual.RecoveryToken);
            Assert.Equal(expected.CreationDate, actual.CreationDate);
            Assert.Equal(expected.IsLocked, actual.IsLocked);
            Assert.Equal(expected.Passhash, actual.Passhash);
            Assert.Equal(expected.Username, actual.Username);
            Assert.Equal(expected.RoleId, actual.RoleId);
            Assert.Equal(expected.Email, actual.Email);
            Assert.Equal(expected.Id, actual.Id);
        }

        #endregion

        #region Create(AccountCreateView view)

        [Fact]
        public void Create_Account()
        {
            AccountCreateView view = ObjectFactory.CreateAccountCreateView(1);
            view.Email = view.Email.ToUpper();
            view.RoleId = account.RoleId;

            service.Create(view);

            Account actual = context.Set<Account>().AsNoTracking().Single(model => model.Id != account.Id);
            AccountCreateView expected = view;

            Assert.Equal(hasher.HashPassword(expected.Password), actual.Passhash);
            Assert.Equal(expected.CreationDate, actual.CreationDate);
            Assert.Equal(expected.Email.ToLower(), actual.Email);
            Assert.Equal(expected.Username, actual.Username);
            Assert.Null(actual.RecoveryTokenExpirationDate);
            Assert.Equal(expected.RoleId, actual.RoleId);
            Assert.Null(actual.RecoveryToken);
            Assert.False(actual.IsLocked);
        }

        #endregion

        #region Edit(AccountEditView view)

        [Fact]
        public void Edit_Account()
        {
            AccountEditView view = ObjectFactory.CreateAccountEditView(account.Id);
            view.IsLocked = account.IsLocked = !account.IsLocked;
            view.Email = (account.Email += "s").ToUpper();
            view.Username = account.Username += "Test";
            view.RoleId = account.RoleId = null;

            service.Edit(view);

            Account actual = context.Set<Account>().AsNoTracking().Single();
            Account expected = account;

            Assert.Equal(expected.RecoveryTokenExpirationDate, actual.RecoveryTokenExpirationDate);
            Assert.Equal(expected.RecoveryToken, actual.RecoveryToken);
            Assert.Equal(expected.CreationDate, actual.CreationDate);
            Assert.Equal(expected.IsLocked, actual.IsLocked);
            Assert.Equal(expected.Username, actual.Username);
            Assert.Equal(expected.Passhash, actual.Passhash);
            Assert.Equal(expected.RoleId, actual.RoleId);
            Assert.Equal(expected.Email, actual.Email);
            Assert.Equal(expected.Id, actual.Id);
        }

        #endregion

        #region Edit(ProfileEditView view)

        [Fact]
        public void Edit_Profile()
        {
            ProfileEditView view = ObjectFactory.CreateProfileEditView();
            account.Passhash = hasher.HashPassword(view.NewPassword);
            view.Username = account.Username += "Test";
            view.Email = account.Email += "Test";

            service.Edit(view);

            Account actual = context.Set<Account>().AsNoTracking().Single();
            Account expected = account;

            Assert.Equal(expected.RecoveryTokenExpirationDate, actual.RecoveryTokenExpirationDate);
            Assert.Equal(expected.RecoveryToken, actual.RecoveryToken);
            Assert.Equal(expected.CreationDate, actual.CreationDate);
            Assert.Equal(expected.Email.ToLower(), actual.Email);
            Assert.Equal(expected.IsLocked, actual.IsLocked);
            Assert.Equal(expected.Username, actual.Username);
            Assert.Equal(expected.Passhash, actual.Passhash);
            Assert.Equal(expected.RoleId, actual.RoleId);
            Assert.Equal(expected.Id, actual.Id);
        }

        [Theory]
        [InlineData("")]
        [InlineData(null)]
        [InlineData("   ")]
        public void Edit_NullOrEmptyNewPassword_DoesNotEditPassword(String newPassword)
        {
            ProfileEditView view = ObjectFactory.CreateProfileEditView();
            view.NewPassword = newPassword;

            service.Edit(view);

            String actual = context.Set<Account>().AsNoTracking().Single().Passhash;
            String expected = account.Passhash;

            Assert.Equal(expected, actual);
        }

        #endregion

        #region Delete(Int32 id)

        [Fact]
        public void Delete_Account()
        {
            service.Delete(account.Id);

            Assert.Empty(context.Set<Account>());
        }

        #endregion

        #region Login(HttpContext context, String username)

        [Fact]
        public void Login_Account()
        {
            HttpContext context = Substitute.For<HttpContext>();
            context.RequestServices.GetService(typeof(IAuthenticationService)).Returns(Substitute.For<IAuthenticationService>());

            service.Login(context, account.Username.ToUpper());

            context.Received().SignInAsync("Cookies", Arg.Is<ClaimsPrincipal>(principal =>
                principal.Claims.Single().Subject.Name == account.Id.ToString() &&
                principal.Claims.Single().Subject.NameClaimType == "name" &&
                principal.Claims.Single().Subject.RoleClaimType == "role" &&
                principal.Identity.AuthenticationType == "local" &&
                principal.Identity.Name == account.Id.ToString() &&
                principal.Identity.IsAuthenticated));
        }

        #endregion

        #region Logout(HttpContext context)

        [Fact]
        public void Logout_Account()
        {
            HttpContext context = Substitute.For<HttpContext>();
            context.RequestServices.GetService(typeof(IAuthenticationService)).Returns(Substitute.For<IAuthenticationService>());

            service.Logout(context);

            context.Received().SignOutAsync("Cookies");
        }

        #endregion

        #region Test helpers

        private void SetUpData()
        {
            account = ObjectFactory.CreateAccount();

            context.Add(account);
            context.SaveChanges();
        }

        #endregion
    }
}


text:
package org.apache.hadoop.hbase.util;

import static org.junit.Assert.*;

import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.testclassification.MiscTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.hbase.thirdparty.com.google.common.collect.Lists;

@Category({ MiscTests.class, SmallTests.class })
public class TestSortedList {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestSortedList.class);

  static class StringComparator implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {
      return o1.compareTo(o2);
    }
  }

  @Test
  public void testSorting() throws Exception {
    SortedList<String> list = new SortedList<>(new StringComparator());
    list.add("c");
    list.add("d");
    list.add("a");
    list.add("b");

    assertEquals(4, list.size());
    assertArrayEquals(new String[] { "a", "b", "c", "d" }, list.toArray(new String[4]));

    list.add("c");
    assertEquals(5, list.size());
    assertArrayEquals(new String[] { "a", "b", "c", "c", "d" }, list.toArray(new String[5]));

    // Test that removal from head or middle maintains sort
    list.remove("b");
    assertEquals(4, list.size());
    assertArrayEquals(new String[] { "a", "c", "c", "d" }, list.toArray(new String[4]));
    list.remove("c");
    assertEquals(3, list.size());
    assertArrayEquals(new String[] { "a", "c", "d" }, list.toArray(new String[3]));
    list.remove("a");
    assertEquals(2, list.size());
    assertArrayEquals(new String[] { "c", "d" }, list.toArray(new String[2]));
  }

  @Test
  public void testReadOnlyIterators() throws Exception {
    SortedList<String> list =
      new SortedList<>(Lists.newArrayList("a", "b", "c", "d", "e"), new StringComparator());

    Iterator<String> i = list.iterator();
    i.next();
    try {
      i.remove();
      fail("Iterator should have thrown an exception");
    } catch (UnsupportedOperationException e) {
      // ok
    }

    ListIterator<String> li = list.listIterator();
    li.next();
    try {
      li.add("a");
      fail("Iterator should have thrown an exception");
    } catch (UnsupportedOperationException e) {
      // ok
    }
    try {
      li.set("b");
      fail("Iterator should have thrown an exception");
    } catch (UnsupportedOperationException e) {
      // ok
    }
    try {
      li.remove();
      fail("Iterator should have thrown an exception");
    } catch (UnsupportedOperationException e) {
      // ok
    }
  }

  @Test
  public void testIteratorIsolation() throws Exception {
    SortedList<String> list =
      new SortedList<>(Lists.newArrayList("a", "b", "c", "d", "e"), new StringComparator());

    // isolation of remove()
    Iterator<String> iter = list.iterator();
    list.remove("c");
    boolean found = false;
    while (iter.hasNext() && !found) {
      found = "c".equals(iter.next());
    }
    assertTrue(found);

    iter = list.iterator();
    found = false;
    while (iter.hasNext() && !found) {
      found = "c".equals(iter.next());
    }
    assertFalse(found);

    // isolation of add()
    iter = list.iterator();
    list.add("f");
    found = false;
    while (iter.hasNext() && !found) {
      String next = iter.next();
      found = "f".equals(next);
    }
    assertFalse(found);

    // isolation of addAll()
    iter = list.iterator();
    list.addAll(Lists.newArrayList("g", "h", "i"));
    found = false;
    while (iter.hasNext() && !found) {
      String next = iter.next();
      found = "g".equals(next) || "h".equals(next) || "i".equals(next);
    }
    assertFalse(found);

    // isolation of clear()
    iter = list.iterator();
    list.clear();
    assertEquals(0, list.size());
    int size = 0;
    while (iter.hasNext()) {
      iter.next();
      size++;
    }
    assertTrue(size > 0);
  }

  @Test
  public void testRandomAccessIsolation() throws Exception {
    SortedList<String> list =
      new SortedList<>(Lists.newArrayList("a", "b", "c"), new StringComparator());
    List<String> innerList = list.get();
    assertEquals("a", innerList.get(0));
    assertEquals("b", innerList.get(1));
    list.clear();
    assertEquals("c", innerList.get(2));
  }
}


text:
const fixtures = require('webtorrent-fixtures')
const test = require('tape')
const WebTorrent = require('../')

test('client.add: magnet uri, utf-8 string', function (t) {
  t.plan(6)

  const client = new WebTorrent({ dht: false, tracker: false, lsd: false })

  client.on('error', function (err) { t.fail(err) })
  client.on('warning', function (err) { t.fail(err) })

  const torrent = client.add(fixtures.leaves.magnetURI)
  t.equal(client.torrents.length, 1)

  torrent.on('infoHash', function () {
    t.equal(torrent.infoHash, fixtures.leaves.parsedTorrent.infoHash)
    t.equal(torrent.magnetURI, fixtures.leaves.magnetURI)

    client.remove(fixtures.leaves.magnetURI, function (err) { t.error(err, 'torrent destroyed') })
    t.equal(client.torrents.length, 0)

    client.destroy(function (err) { t.error(err, 'client destroyed') })
  })
})

test('client.add: torrent file, buffer', function (t) {
  t.plan(6)

  const client = new WebTorrent({ dht: false, tracker: false, lsd: false })

  client.on('error', function (err) { t.fail(err) })
  client.on('warning', function (err) { t.fail(err) })

  const torrent = client.add(fixtures.leaves.torrent)
  t.equal(client.torrents.length, 1)

  torrent.on('infoHash', function () {
    t.equal(torrent.infoHash, fixtures.leaves.parsedTorrent.infoHash)
    t.equal(torrent.magnetURI, fixtures.leaves.magnetURI)

    client.remove(fixtures.leaves.torrent, function (err) { t.error(err, 'torrent destroyed') })
    t.equal(client.torrents.length, 0)

    client.destroy(function (err) { t.error(err, 'client destroyed') })
  })
})

test('client.add: info hash, hex string', function (t) {
  t.plan(6)

  const client = new WebTorrent({ dht: false, tracker: false, lsd: false })

  client.on('error', function (err) { t.fail(err) })
  client.on('warning', function (err) { t.fail(err) })

  const torrent = client.add(fixtures.leaves.parsedTorrent.infoHash)
  t.equal(client.torrents.length, 1)

  torrent.on('infoHash', function () {
    t.equal(torrent.infoHash, fixtures.leaves.parsedTorrent.infoHash)
    t.equal(torrent.magnetURI, 'magnet:?xt=urn:btih:' + fixtures.leaves.parsedTorrent.infoHash)

    client.remove(fixtures.leaves.parsedTorrent.infoHash, function (err) { t.error(err, 'torrent destroyed') })
    t.equal(client.torrents.length, 0)

    client.destroy(function (err) { t.error(err, 'client destroyed') })
  })
})

test('client.add: info hash, buffer', function (t) {
  t.plan(6)

  const client = new WebTorrent({ dht: false, tracker: false, lsd: false })

  client.on('error', function (err) { t.fail(err) })
  client.on('warning', function (err) { t.fail(err) })

  const torrent = client.add(fixtures.leaves.parsedTorrent.infoHashBuffer)
  t.equal(client.torrents.length, 1)

  torrent.on('infoHash', function () {
    t.equal(torrent.infoHash, fixtures.leaves.parsedTorrent.infoHash)
    t.ok(torrent.magnetURI.indexOf('magnet:?xt=urn:btih:' + fixtures.leaves.parsedTorrent.infoHash) === 0)

    client.remove(Buffer.from(fixtures.leaves.parsedTorrent.infoHash, 'hex'), function (err) { t.error(err, 'torrent destroyed') })
    t.equal(client.torrents.length, 0)

    client.destroy(function (err) { t.error(err, 'client destroyed') })
  })
})

test('client.add: parsed torrent, from `parse-torrent`', function (t) {
  t.plan(6)

  const client = new WebTorrent({ dht: false, tracker: false, lsd: false })

  client.on('error', function (err) { t.fail(err) })
  client.on('warning', function (err) { t.fail(err) })

  const torrent = client.add(fixtures.leaves.parsedTorrent)
  t.equal(client.torrents.length, 1)

  torrent.on('infoHash', function () {
    t.equal(torrent.infoHash, fixtures.leaves.parsedTorrent.infoHash)
    t.equal(torrent.magnetURI, fixtures.leaves.magnetURI)

    client.remove(fixtures.leaves.parsedTorrent, function (err) { t.error(err, 'torrent destroyed') })
    t.equal(client.torrents.length, 0)

    client.destroy(function (err) { t.error(err, 'client destroyed') })
  })
})

test('client.add: parsed torrent, with string type announce property', function (t) {
  t.plan(7)

  const client = new WebTorrent({ dht: false, tracker: false, lsd: false })

  client.on('error', function (err) { t.fail(err) })
  client.on('warning', function (err) { t.fail(err) })

  const parsedTorrent = Object.assign({}, fixtures.leaves.parsedTorrent)
  parsedTorrent.announce = 'http://tracker.local:80'

  const torrent = client.add(parsedTorrent)
  t.equal(client.torrents.length, 1)

  torrent.on('infoHash', function () {
    t.equal(torrent.infoHash, fixtures.leaves.parsedTorrent.infoHash)

    const expectedMagnetURI = fixtures.leaves.magnetURI +
      '&tr=' + encodeURIComponent('http://tracker.local:80')
    t.equal(torrent.magnetURI, expectedMagnetURI)

    // `torrent.announce` must always be an array
    t.deepEqual(torrent.announce, ['http://tracker.local:80'])

    client.remove(fixtures.leaves.parsedTorrent, function (err) { t.error(err, 'torrent destroyed') })
    t.equal(client.torrents.length, 0)

    client.destroy(function (err) { t.error(err, 'client destroyed') })
  })
})

test('client.add: parsed torrent, with array type announce property', function (t) {
  t.plan(7)

  const client = new WebTorrent({ dht: false, tracker: false, lsd: false })

  client.on('error', function (err) { t.fail(err) })
  client.on('warning', function (err) { t.fail(err) })

  const parsedTorrent = Object.assign({}, fixtures.leaves.parsedTorrent)
  parsedTorrent.announce = ['http://tracker.local:80', 'http://tracker.local:81']

  const torrent = client.add(parsedTorrent)
  t.equal(client.torrents.length, 1)

  torrent.on('infoHash', function () {
    t.equal(torrent.infoHash, fixtures.leaves.parsedTorrent.infoHash)

    const expectedMagnetURI = fixtures.leaves.magnetURI +
      '&tr=' + encodeURIComponent('http://tracker.local:80') +
      '&tr=' + encodeURIComponent('http://tracker.local:81')
    t.equal(torrent.magnetURI, expectedMagnetURI)

    t.deepEqual(torrent.announce, ['http://tracker.local:80', 'http://tracker.local:81'])

    client.remove(fixtures.leaves.parsedTorrent, function (err) { t.error(err, 'torrent destroyed') })
    t.equal(client.torrents.length, 0)

    client.destroy(function (err) { t.error(err, 'client destroyed') })
  })
})

test('client.add: invalid torrent id: empty string', function (t) {
  t.plan(3)

  const client = new WebTorrent({ dht: false, tracker: false, lsd: false })

  client.on('error', function (err) {
    t.ok(err instanceof Error)
    t.ok(err.message.indexOf('Invalid torrent identifier') >= 0)

    client.destroy(function (err) { t.error(err, 'client destroyed') })
  })
  client.on('warning', function (err) { t.fail(err) })

  client.add('')
})

test('client.add: invalid torrent id: short buffer', function (t) {
  t.plan(3)

  const client = new WebTorrent({ dht: false, tracker: false, lsd: false })

  client.on('error', function (err) {
    t.ok(err instanceof Error)
    t.ok(err.message.indexOf('Invalid torrent identifier') >= 0)

    client.destroy(function (err) { t.error(err, 'client destroyed') })
  })
  client.on('warning', function (err) { t.fail(err) })

  client.add(Buffer.from('abc'))
})


text:
// Copyright (c) 2013-2020 Rob Norris and Contributors
// This software is licensed under the MIT License (MIT).
// For more information see LICENSE or https://opensource.org/licenses/MIT

package doobie
package hikari

import java.util.Properties
import java.util.concurrent.{ScheduledExecutorService, ThreadFactory}

import cats.effect.implicits._
import cats.effect.kernel.{ Async, Resource, Sync }
import com.zaxxer.hikari.metrics.MetricsTrackerFactory
import com.zaxxer.hikari.{HikariConfig, HikariDataSource}
import javax.sql.DataSource

import scala.concurrent.ExecutionContext

object HikariTransactor {

  /** Construct a `HikariTransactor` from an existing `HikariDatasource`. */
  @SuppressWarnings(Array("org.wartremover.warts.Overloading"))
  def apply[M[_]: Async](
    hikariDataSource : HikariDataSource,
    connectEC:         ExecutionContext
  ): HikariTransactor[M] =
    Transactor.fromDataSource[M](hikariDataSource, connectEC)

  /** Resource yielding an unconfigured `HikariTransactor`. */
  def initial[M[_]: Async](
    connectEC: ExecutionContext
  ): Resource[M, HikariTransactor[M]] = {
    Resource.fromAutoCloseable(Sync[M].delay(new HikariDataSource))
      .map(Transactor.fromDataSource[M](_, connectEC))
  }

  /** Resource yielding a new `HikariTransactor` configured with the given Config.
   * Unless you have a good reason, consider using `fromConfig` which creates the `connectEC` for you.
   */
  def fromConfigCustomEc[M[_]: Async](
    config: Config,
    connectEC: ExecutionContext,
    dataSource: Option[DataSource] = None,
    dataSourceProperties: Option[Properties] = None,
    healthCheckProperties: Option[Properties] = None,
    healthCheckRegistry: Option[Object] = None,
    metricRegistry: Option[Object] = None,
    metricsTrackerFactory: Option[MetricsTrackerFactory] = None,
    scheduledExecutor: Option[ScheduledExecutorService] = None,
    threadFactory: Option[ThreadFactory] = None,
  ): Resource[M, HikariTransactor[M]] = {
    Resource
      .liftK(
        Config.makeHikariConfig(
          config,
          dataSource,
          dataSourceProperties,
          healthCheckProperties,
          healthCheckRegistry,
          metricRegistry,
          metricsTrackerFactory,
          scheduledExecutor,
          threadFactory
        )
      )
      .flatMap(fromHikariConfig(_, connectEC))
  }

  /** Resource yielding a new `HikariTransactor` configured with the given Config.
   * The `connectEC` is created automatically, with the same size as the Hikari pool.
   */
  def fromConfig[M[_]: Async](
      config: Config,
      dataSource: Option[DataSource] = None,
      dataSourceProperties: Option[Properties] = None,
      healthCheckProperties: Option[Properties] = None,
      healthCheckRegistry: Option[Object] = None,
      metricRegistry: Option[Object] = None,
      metricsTrackerFactory: Option[MetricsTrackerFactory] = None,
      scheduledExecutor: Option[ScheduledExecutorService] = None,
      threadFactory: Option[ThreadFactory] = None,
    ): Resource[M, HikariTransactor[M]] = {
    Resource
      .liftK(
        Config.makeHikariConfig(
          config,
          dataSource,
          dataSourceProperties,
          healthCheckProperties,
          healthCheckRegistry,
          metricRegistry,
          metricsTrackerFactory,
          scheduledExecutor,
          threadFactory
        )
      )
      .flatMap(fromHikariConfig(_))
  }

  /** Resource yielding a new `HikariTransactor` configured with the given HikariConfig.
   * Unless you have a good reason, consider using the overload without explicit `connectEC`, it will be created automatically for you.
   */
  def fromHikariConfig[M[_]: Async](
    hikariConfig: HikariConfig,
    connectEC: ExecutionContext
  ): Resource[M, HikariTransactor[M]] = Resource
    .fromAutoCloseable(Sync[M].delay(new HikariDataSource(hikariConfig)))
    .map(Transactor.fromDataSource[M](_, connectEC))

  /** Resource yielding a new `HikariTransactor` configured with the given HikariConfig.
   * The `connectEC` is created automatically, with the same size as the Hikari pool.
   */
  def fromHikariConfig[M[_]: Async](hikariConfig: HikariConfig): Resource[M, HikariTransactor[M]] =
  for {
    // to populate unset fields with default values, like `maximumPoolSize`
    _ <- Sync[M].delay(hikariConfig.validate()).toResource
    // Note that the number of JDBC connections is usually limited by the underlying JDBC pool.
    // You may therefore want to limit your connection pool to the same size as the underlying JDBC pool
    // as any additional threads are guaranteed to be blocked.
    // https://tpolecat.github.io/doobie/docs/14-Managing-Connections.html#about-threading
    connectEC <- ExecutionContexts.fixedThreadPool(hikariConfig.getMaximumPoolSize)
    result <- fromHikariConfig(hikariConfig, connectEC)
  } yield result

  /** Resource yielding a new `HikariTransactor` configured with the given info.
   * Consider using `fromConfig` for better configurability.
   */
  def newHikariTransactor[M[_]: Async](
    driverClassName: String,
    url:             String,
    user:            String,
    pass:            String,
    connectEC:       ExecutionContext
  ): Resource[M, HikariTransactor[M]] =
    for {
      _ <- Resource.eval(Async[M].delay(Class.forName(driverClassName)))
      t <- initial[M](connectEC)
      _ <- Resource.eval {
            t.configure { ds =>
              Async[M].delay {
                ds setJdbcUrl  url
                ds setUsername user
                ds setPassword pass
              }
            }
          }
    } yield t

}


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package fsu.tictactoe;

public final class R {
    public static final class anim {
        public static final int fworks=0x7f040000;
    }
    public static final class attr {
    }
    public static final class drawable {
        public static final int anim1=0x7f020000;
        public static final int anim2=0x7f020001;
        public static final int anim3=0x7f020002;
        public static final int anim4=0x7f020003;
        public static final int anim5=0x7f020004;
        public static final int anim6=0x7f020005;
        public static final int anim7=0x7f020006;
        public static final int anim8=0x7f020007;
        public static final int bg=0x7f020008;
        public static final int icon=0x7f020009;
        public static final int o0=0x7f02000a;
        public static final int o1=0x7f02000b;
        public static final int o2=0x7f02000c;
        public static final int o3=0x7f02000d;
        public static final int o4=0x7f02000e;
        public static final int o5=0x7f02000f;
        public static final int o6=0x7f020010;
        public static final int o7=0x7f020011;
        public static final int x0=0x7f020012;
        public static final int x1=0x7f020013;
        public static final int x2=0x7f020014;
        public static final int x3=0x7f020015;
        public static final int x4=0x7f020016;
        public static final int x5=0x7f020017;
        public static final int x6=0x7f020018;
        public static final int x7=0x7f020019;
    }
    public static final class id {
        public static final int Button01=0x7f060015;
        public static final int EditText01=0x7f060014;
        public static final int ImageButton01=0x7f060001;
        public static final int ImageButton02=0x7f060002;
        public static final int ImageButton03=0x7f060003;
        public static final int ImageButton04=0x7f060005;
        public static final int ImageButton05=0x7f060006;
        public static final int ImageButton06=0x7f060007;
        public static final int ImageButton07=0x7f060009;
        public static final int ImageButton08=0x7f06000a;
        public static final int ImageButton09=0x7f06000b;
        public static final int ImageView01=0x7f060016;
        public static final int LinearLayout01=0x7f060000;
        public static final int LinearLayout02=0x7f060004;
        public static final int LinearLayout03=0x7f060008;
        public static final int ScrollView01=0x7f06000d;
        public static final int StatList=0x7f06000e;
        public static final int TextView01=0x7f06000c;
        public static final int TextView02=0x7f060013;
        public static final int pvc=0x7f060010;
        public static final int pvp=0x7f06000f;
        public static final int quit=0x7f060012;
        public static final int vs=0x7f060011;
    }
    public static final class layout {
        public static final int game=0x7f030000;
        public static final int highscore=0x7f030001;
        public static final int main=0x7f030002;
        public static final int name_dialog=0x7f030003;
        public static final int win=0x7f030004;
    }
    public static final class string {
        public static final int app_name=0x7f050001;
        public static final int hello=0x7f050000;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package summarizer.receiver;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import summarizer.receiver.MotifImpl;

/**
 *
 * @author AVF
 */
public class MotifImplTest {

    public MotifImplTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {

    }

    @After
    public void tearDown() {
    }

    /**
     * Test of moyenne method, of class MotifImpl.
     */
    @Test
    public void testMoyenne() {
        Collection<Float> collectFloat = new ArrayList<>();
            collectFloat.add(12.5f);
            collectFloat.add(15.25f);
            collectFloat.add(19.10f);
            collectFloat.add(21.8f);
            collectFloat.add(14.33f);
            collectFloat.add(44.1f);
            collectFloat.add(17.0f);

        System.out.println("MotifImpl.moyenne :");

        MotifImpl myMotifImpl = new MotifImpl();
        float expResult = 20.5828F;
        float result = myMotifImpl.moyenne(collectFloat);
        assertEquals(expResult, result, 0.009);

    }

    /**
     * Test of pourcentage method, of class MotifImpl.
     */

    @Test
    public void testPourcentage() {
        //Collection<String> collectPourcentage = new ArrayList<>(Arrays.asList("Lima","Santiago","Quito","Lima","Santiago","Lima"));

        Collection<String> collectPourcentage = new ArrayList<>();
            collectPourcentage.add("Lima");
            collectPourcentage.add("Santiago");
            collectPourcentage.add("Quito");
            collectPourcentage.add("Lima");
            collectPourcentage.add("Santiago");
            collectPourcentage.add("Lima");

        HashMap<String, Float> expResult = new HashMap<>();
            expResult.put("Lima", 50.0f);
            expResult.put("Santiago", 33.333336f);
            expResult.put("Quito", 16.666668f);

        System.out.println("MotifImpl.pourcentage :");

        MotifImpl myMotifImpl = new MotifImpl();
        Map<String, Float> result = myMotifImpl.pourcentage(collectPourcentage);
        assertEquals(expResult, result);

    }

    /**
     * Test of max method, of class MotifImpl.
     */
    @Test
    public void testMax() {

        Collection<Float> collectFloat = new ArrayList<>();
            collectFloat.add(1.0f);
            collectFloat.add(2.4f);
            collectFloat.add(3.8f);
            collectFloat.add(8.0f);
            collectFloat.add(14.1f);
            collectFloat.add(25.9f);
            collectFloat.add(44.0f);

        System.out.println("MotifImpl.max : ");

        MotifImpl myMotifImpl = new MotifImpl();
        float expResult = 44.0F;
        float result = myMotifImpl.max(collectFloat);
        assertEquals(expResult, result, 0.0);

    }

    /**
     * Test of min method, of class MotifImpl.
     */
    @Test
    public void testMin() {
        Collection<Float> collectFloat = new ArrayList<>();
            collectFloat.add(1.0f);
            collectFloat.add(2.4f);
            collectFloat.add(3.8f);
            collectFloat.add(8.0f);
            collectFloat.add(14.1f);
            collectFloat.add(25.9f);
            collectFloat.add(44.0f);

        System.out.println("MotifImpl.min : ");

        MotifImpl myData = new MotifImpl();
        float expResult = 1.0F;
        float result = myData.min(collectFloat);
        assertEquals(expResult, result, 0.0);

    }

    /**
     * Test of ecartType method, of class MotifImpl.
     */
    @Test
    public void testEcartType() {

        Collection<Float> collectFloat = new ArrayList<>();
            collectFloat.add(1.0f);
            collectFloat.add(2.4f);
            collectFloat.add(3.8f);
            collectFloat.add(8.0f);
            collectFloat.add(14.1f);
            collectFloat.add(25.9f);
            collectFloat.add(444.0f);

        System.out.println("MotifImpl.ecartType :");
        MotifImpl myMotifImpl = new MotifImpl();
        float expResult = 53.241f;
        float result = myMotifImpl.ecartType(collectFloat);
        assertEquals(expResult, result, 0.05);

    }

}


text:
'use strict';

var is = require( '../../../is' );
var util = require( '../../../util' );

var BaseRenderer = function( options ){ this.init( options ); };
var BR = BaseRenderer;
var BRp = BR.prototype;

BRp.clientFunctions = [ 'redrawHint', 'render', 'renderTo', 'matchCanvasSize', 'nodeShapeImpl', 'arrowShapeImpl' ];

BRp.init = function( options ){
  var r = this;

  r.options = options;

  r.cy = options.cy;

  r.container = options.cy.container();

  r.selection = [ undefined, undefined, undefined, undefined, 0]; // Coordinates for selection box, plus enabled flag

  r.bezierProjPcts = [ 0.05, 0.225, 0.4, 0.5, 0.6, 0.775, 0.95 ];

  //--Pointer-related data
  r.hoverData = {down: null, last: null,
      downTime: null, triggerMode: null,
      dragging: false,
      initialPan: [ null, null ], capture: false};

  r.dragData = {possibleDragElements: []};

  r.touchData = {
    start: null, capture: false,

    // These 3 fields related to tap, taphold events
    startPosition: [ null, null, null, null, null, null ],
    singleTouchStartTime: null,
    singleTouchMoved: true,

    now: [ null, null, null, null, null, null ],
    earlier: [ null, null, null, null, null, null ]
  };

  r.redraws = 0;
  r.showFps = options.showFps;

  r.hideEdgesOnViewport = options.hideEdgesOnViewport;
  r.hideLabelsOnViewport = options.hideLabelsOnViewport;
  r.textureOnViewport = options.textureOnViewport;
  r.wheelSensitivity = options.wheelSensitivity;
  r.motionBlurEnabled = options.motionBlur; // on by default
  r.forcedPixelRatio = options.pixelRatio;
  r.motionBlur = options.motionBlur; // for initial kick off
  r.motionBlurOpacity = options.motionBlurOpacity;
  r.motionBlurTransparency = 1 - r.motionBlurOpacity;
  r.motionBlurPxRatio = 1;
  r.mbPxRBlurry = 1; //0.8;
  r.minMbLowQualFrames = 4;
  r.fullQualityMb = false;
  r.clearedForMotionBlur = [];
  r.desktopTapThreshold = options.desktopTapThreshold;
  r.desktopTapThreshold2 = options.desktopTapThreshold * options.desktopTapThreshold;
  r.touchTapThreshold = options.touchTapThreshold;
  r.touchTapThreshold2 = options.touchTapThreshold * options.touchTapThreshold;
  r.tapholdDuration = 500;

  r.bindings = [];
  r.beforeRenderCallbacks = [];
  r.beforeRenderPriorities = { // higher priority execs before lower one
    animations:   400,
    eleCalcs:     300,
    eleTxrDeq:    200,
    lyrTxrDeq:    100
  };

  r.registerNodeShapes();
  r.registerArrowShapes();
  r.registerCalculationListeners();
  r.load();
};

BRp.notify = function( params ){
  var types;
  var r = this;

  // the renderer can't be notified after it's destroyed
  if( this.destroyed ){ return; }

  if( is.array( params.type ) ){
    types = params.type;

  } else {
    types = [ params.type ];
  }

  var has = {};
  for( var i = 0; i < types.length; i++ ){
    var type = types[ i ];

    has[ type ] = true;
  } // for

  if( has['destroy'] ){
    r.destroy();
    return;
  }

  if( has['add'] || has['remove'] || has['load'] || has['style'] ){
    r.updateCachedZSortedEles();
  }

  if( has['viewport'] ){
    r.redrawHint( 'select', true );
  }

  if( has['load'] || has['resize'] ){
    r.invalidateContainerClientCoordsCache();
    r.matchCanvasSize( r.container );
  }

  r.redrawHint( 'eles', true );
  r.redrawHint( 'drag', true );

  this.startRenderLoop();

  this.redraw();
};

BRp.destroy = function(){
  var r = this;

  r.destroyed = true;

  r.cy.stopAnimationLoop();

  for( var i = 0; i < r.bindings.length; i++ ){
    var binding = r.bindings[ i ];
    var b = binding;
    var tgt = b.target;

    ( tgt.off || tgt.removeEventListener ).apply( tgt, b.args );
  }

  r.bindings = [];
  r.beforeRenderCallbacks = [];
  r.onUpdateEleCalcsFns = [];

  if( r.removeObserver ){
    r.removeObserver.disconnect();
  }

  if( r.styleObserver ){
    r.styleObserver.disconnect();
  }

  if( r.labelCalcDiv ){
    try {
      document.body.removeChild( r.labelCalcDiv ); // eslint-disable-line no-undef
    } catch( e ){
      // ie10 issue #1014
    }
  }
};

[
  require( './arrow-shapes' ),
  require( './coord-ele-math' ),
  require( './images' ),
  require( './load-listeners' ),
  require( './node-shapes' ),
  require( './redraw' )
].forEach( function( props ){
  util.extend( BRp, props );
} );

module.exports = BR;


text:
import React from 'react';
import { ThemeProvider, lightTheme } from '@strapi/design-system';
import { QueryClientProvider, QueryClient } from 'react-query';
import { render as renderTL, screen, waitFor } from '@testing-library/react';
import { useRBAC, useQueryParams } from '@strapi/helper-plugin';
import { MemoryRouter } from 'react-router-dom';
import { rest } from 'msw';
import { AssetDialog } from '..';
import en from '../../../translations/en.json';
import server from './server';
import { assetResultMock } from './asset.mock';

jest.mock('@strapi/helper-plugin', () => ({
  ...jest.requireActual('@strapi/helper-plugin'),
  useRBAC: jest.fn(),
  useNotification: jest.fn(() => jest.fn()),
  useQueryParams: jest.fn(),
}));

jest.mock('../../../utils/getTrad', () => x => x);

jest.mock('react-intl', () => ({
  FormattedMessage: ({ id }) => id,
  useIntl: () => ({ formatMessage: jest.fn(({ id }) => en[id] || id) }),
}));

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
    },
  },
});

const renderML = (props = { onClose: jest.fn(), multiple: false, initiallySelectedAssets: [] }) =>
  renderTL(
    <QueryClientProvider client={queryClient}>
      <ThemeProvider theme={lightTheme}>
        <MemoryRouter>
          <AssetDialog {...props} />
        </MemoryRouter>
      </ThemeProvider>
    </QueryClientProvider>
  );

describe('AssetDialog', () => {
  beforeAll(() => server.listen());

  beforeEach(() => {
    useRBAC.mockReturnValue({
      isLoading: false,
      allowedActions: {
        canRead: true,
        canCreate: true,
        canUpdate: true,
        canCopyLink: true,
        canDownload: true,
      },
    });

    useQueryParams.mockReturnValue([{ rawQuery: 'some-url' }, jest.fn()]);
  });

  afterEach(() => {
    server.resetHandlers();
    jest.clearAllMocks();
  });

  afterAll(() => server.close());

  describe('loading state', () => {
    it('shows a loader when resolving the permissions', () => {
      useRBAC.mockReturnValue({ isLoading: true, allowedActions: {} });

      renderML();

      expect(screen.getByRole('dialog').getAttribute('aria-busy')).toBe('true');
      expect(screen.getByText('Loading the asset list.')).toBeInTheDocument();
    });

    it('shows a loader when resolving the assets', () => {
      renderML();

      expect(screen.getByRole('dialog').getAttribute('aria-busy')).toBe('true');
      expect(screen.getByText('Loading the asset list.')).toBeInTheDocument();
    });
  });

  describe('content', () => {
    describe('empty state', () => {
      it('shows an empty state when there are no assets and the user is allowed to read', async () => {
        renderML();

        await waitFor(() =>
          expect(screen.getByText('Upload your first assets...')).toBeInTheDocument()
        );

        expect(screen.getByRole('dialog').getAttribute('aria-busy')).toBe(null);
      });

      it('shows a specific empty state when the user is not allowed to see the content', async () => {
        useRBAC.mockReturnValue({
          isLoading: false,
          allowedActions: {
            canRead: false,
          },
        });

        renderML();

        await waitFor(() =>
          expect(
            screen.getByText(`app.components.EmptyStateLayout.content-permissions`)
          ).toBeInTheDocument()
        );

        expect(screen.getByRole('dialog').getAttribute('aria-busy')).toBe(null);
      });

      it('shows a specific empty state when the user can read but not create', async () => {
        useRBAC.mockReturnValue({
          isLoading: false,
          allowedActions: {
            canRead: true,
            canCreate: false,
          },
        });

        renderML();

        await waitFor(() =>
          expect(screen.getByText(`The asset list is empty.`)).toBeInTheDocument()
        );
        await waitFor(() =>
          expect(screen.queryByText('Upload your first assets...')).not.toBeInTheDocument()
        );

        expect(screen.getByRole('dialog').getAttribute('aria-busy')).toBe(null);
      });
    });

    describe('content resolved', () => {
      beforeEach(() => {
        server.use(rest.get('*/upload/files*', (req, res, ctx) => res(ctx.json(assetResultMock))));
      });

      it('shows an asset when the data resolves', async () => {
        renderML();

        await waitFor(() => expect(screen.getByText('3874873.jpg')).toBeInTheDocument());

        expect(
          screen.getByText((_, element) => element.textContent === 'jpg - 400✕400')
        ).toBeInTheDocument();
        expect(screen.getByText('Image')).toBeInTheDocument();
        expect(screen.getByLabelText('Edit')).toBeInTheDocument();
      });
    });
  });
});