text:
namespace Mosa.Tool.Debugger
{
	partial class MainForm
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			WeifenLuo.WinFormsUI.Docking.DockPanelSkin dockPanelSkin1 = new WeifenLuo.WinFormsUI.Docking.DockPanelSkin();
			WeifenLuo.WinFormsUI.Docking.AutoHideStripSkin autoHideStripSkin1 = new WeifenLuo.WinFormsUI.Docking.AutoHideStripSkin();
			WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient();
			WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient1 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
			WeifenLuo.WinFormsUI.Docking.DockPaneStripSkin dockPaneStripSkin1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripSkin();
			WeifenLuo.WinFormsUI.Docking.DockPaneStripGradient dockPaneStripGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripGradient();
			WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient2 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
			WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient2 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient();
			WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient3 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
			WeifenLuo.WinFormsUI.Docking.DockPaneStripToolWindowGradient dockPaneStripToolWindowGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripToolWindowGradient();
			WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient4 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
			WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient5 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
			WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient3 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient();
			WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient6 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
			WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient7 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
			this.dockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel();
			this.toolStrip1 = new System.Windows.Forms.ToolStrip();
			this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
			this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
			this.toolStripButton4 = new System.Windows.Forms.ToolStripButton();
			this.toolStripButton2 = new System.Windows.Forms.ToolStripButton();
			this.statusStrip1 = new System.Windows.Forms.StatusStrip();
			this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
			this.toolStrip1.SuspendLayout();
			this.statusStrip1.SuspendLayout();
			this.SuspendLayout();
			//
			// dockPanel
			//
			this.dockPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
			this.dockPanel.DockBackColor = System.Drawing.SystemColors.AppWorkspace;
			this.dockPanel.DockBottomPortion = 150D;
			this.dockPanel.DockLeftPortion = 240D;
			this.dockPanel.DockRightPortion = 240D;
			this.dockPanel.DockTopPortion = 150D;
			this.dockPanel.DocumentStyle = WeifenLuo.WinFormsUI.Docking.DocumentStyle.DockingWindow;
			this.dockPanel.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World, ((byte)(0)));
			this.dockPanel.Location = new System.Drawing.Point(0, 28);
			this.dockPanel.Name = "dockPanel";
			this.dockPanel.RightToLeftLayout = true;
			this.dockPanel.Size = new System.Drawing.Size(465, 348);
			dockPanelGradient1.EndColor = System.Drawing.SystemColors.ControlLight;
			dockPanelGradient1.StartColor = System.Drawing.SystemColors.ControlLight;
			autoHideStripSkin1.DockStripGradient = dockPanelGradient1;
			tabGradient1.EndColor = System.Drawing.SystemColors.Control;
			tabGradient1.StartColor = System.Drawing.SystemColors.Control;
			tabGradient1.TextColor = System.Drawing.SystemColors.ControlDarkDark;
			autoHideStripSkin1.TabGradient = tabGradient1;
			autoHideStripSkin1.TextFont = new System.Drawing.Font("Segoe UI", 9F);
			dockPanelSkin1.AutoHideStripSkin = autoHideStripSkin1;
			tabGradient2.EndColor = System.Drawing.SystemColors.ControlLightLight;
			tabGradient2.StartColor = System.Drawing.SystemColors.ControlLightLight;
			tabGradient2.TextColor = System.Drawing.SystemColors.ControlText;
			dockPaneStripGradient1.ActiveTabGradient = tabGradient2;
			dockPanelGradient2.EndColor = System.Drawing.SystemColors.Control;
			dockPanelGradient2.StartColor = System.Drawing.SystemColors.Control;
			dockPaneStripGradient1.DockStripGradient = dockPanelGradient2;
			tabGradient3.EndColor = System.Drawing.SystemColors.ControlLight;
			tabGradient3.StartColor = System.Drawing.SystemColors.ControlLight;
			tabGradient3.TextColor = System.Drawing.SystemColors.ControlText;
			dockPaneStripGradient1.InactiveTabGradient = tabGradient3;
			dockPaneStripSkin1.DocumentGradient = dockPaneStripGradient1;
			dockPaneStripSkin1.TextFont = new System.Drawing.Font("Segoe UI", 9F);
			tabGradient4.EndColor = System.Drawing.SystemColors.ActiveCaption;
			tabGradient4.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
			tabGradient4.StartColor = System.Drawing.SystemColors.GradientActiveCaption;
			tabGradient4.TextColor = System.Drawing.SystemColors.ActiveCaptionText;
			dockPaneStripToolWindowGradient1.ActiveCaptionGradient = tabGradient4;
			tabGradient5.EndColor = System.Drawing.SystemColors.Control;
			tabGradient5.StartColor = System.Drawing.SystemColors.Control;
			tabGradient5.TextColor = System.Drawing.SystemColors.ControlText;
			dockPaneStripToolWindowGradient1.ActiveTabGradient = tabGradient5;
			dockPanelGradient3.EndColor = System.Drawing.SystemColors.ControlLight;
			dockPanelGradient3.StartColor = System.Drawing.SystemColors.ControlLight;
			dockPaneStripToolWindowGradient1.DockStripGradient = dockPanelGradient3;
			tabGradient6.EndColor = System.Drawing.SystemColors.InactiveCaption;
			tabGradient6.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
			tabGradient6.StartColor = System.Drawing.SystemColors.GradientInactiveCaption;
			tabGradient6.TextColor = System.Drawing.SystemColors.InactiveCaptionText;
			dockPaneStripToolWindowGradient1.InactiveCaptionGradient = tabGradient6;
			tabGradient7.EndColor = System.Drawing.Color.Transparent;
			tabGradient7.StartColor = System.Drawing.Color.Transparent;
			tabGradient7.TextColor = System.Drawing.SystemColors.ControlDarkDark;
			dockPaneStripToolWindowGradient1.InactiveTabGradient = tabGradient7;
			dockPaneStripSkin1.ToolWindowGradient = dockPaneStripToolWindowGradient1;
			dockPanelSkin1.DockPaneStripSkin = dockPaneStripSkin1;
			this.dockPanel.Skin = dockPanelSkin1;
			this.dockPanel.TabIndex = 0;
			//
			// toolStrip1
			//
			this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripButton1,
            this.toolStripSeparator1,
            this.toolStripButton4,
            this.toolStripButton2});
			this.toolStrip1.Location = new System.Drawing.Point(0, 0);
			this.toolStrip1.Name = "toolStrip1";
			this.toolStrip1.Size = new System.Drawing.Size(465, 25);
			this.toolStrip1.TabIndex = 28;
			this.toolStrip1.Text = "toolStrip1";
			//
			// toolStripButton1
			//
			this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
			this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.toolStripButton1.Name = "toolStripButton1";
			this.toolStripButton1.Size = new System.Drawing.Size(67, 22);
			this.toolStripButton1.Text = "Connect";
			this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click);
			//
			// toolStripSeparator1
			//
			this.toolStripSeparator1.Name = "toolStripSeparator1";
			this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
			//
			// toolStripButton4
			//
			this.toolStripButton4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton4.Image")));
			this.toolStripButton4.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.toolStripButton4.Name = "toolStripButton4";
			this.toolStripButton4.Size = new System.Drawing.Size(47, 22);
			this.toolStripButton4.Text = "Ping";
			this.toolStripButton4.Click += new System.EventHandler(this.toolStripButton4_Click);
			//
			// toolStripButton2
			//
			this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image")));
			this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.toolStripButton2.Name = "toolStripButton2";
			this.toolStripButton2.Size = new System.Drawing.Size(90, 22);
			this.toolStripButton2.Text = "View Memory";
			this.toolStripButton2.Click += new System.EventHandler(this.toolStripButton2_Click);
			//
			// statusStrip1
			//
			this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripStatusLabel1});
			this.statusStrip1.Location = new System.Drawing.Point(0, 379);
			this.statusStrip1.Name = "statusStrip1";
			this.statusStrip1.Size = new System.Drawing.Size(465, 22);
			this.statusStrip1.TabIndex = 29;
			this.statusStrip1.Text = "statusStrip1";
			//
			// toolStripStatusLabel1
			//
			this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
			this.toolStripStatusLabel1.Size = new System.Drawing.Size(42, 17);
			this.toolStripStatusLabel1.Text = "Ready!";
			//
			// MainForm
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(465, 401);
			this.Controls.Add(this.statusStrip1);
			this.Controls.Add(this.toolStrip1);
			this.Controls.Add(this.dockPanel);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Name = "MainForm";
			this.Text = "Mosa Debugger v1.4";
			this.Load += new System.EventHandler(this.MainForm_Load);
			this.toolStrip1.ResumeLayout(false);
			this.toolStrip1.PerformLayout();
			this.statusStrip1.ResumeLayout(false);
			this.statusStrip1.PerformLayout();
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel;
		private System.Windows.Forms.ToolStrip toolStrip1;
		private System.Windows.Forms.ToolStripButton toolStripButton1;
		private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
		private System.Windows.Forms.ToolStripButton toolStripButton4;
		private System.Windows.Forms.ToolStripButton toolStripButton2;
		private System.Windows.Forms.StatusStrip statusStrip1;
		private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
	}
}


text:
<?php

/**
 * Require Auth_OpenID::arrayGet().
 */
require_once "Auth/OpenID.php";

class Auth_OpenID_Parse {

    /**
     * Specify some flags for use with regex matching.
     */
    var $_re_flags = "si";

    /**
     * Stuff to remove before we start looking for tags
     */
    var $_removed_re =
           "<!--.*?-->|<!\[CDATA\[.*?\]\]>|<script\b(?!:)[^>]*>.*?<\/script>";

    /**
     * Starts with the tag name at a word boundary, where the tag name
     * is not a namespace
     */
    var $_tag_expr = "<%s\b(?!:)([^>]*?)(?:\/>|>(.*)(?:<\/?%s\s*>|\Z))";

    var $_attr_find = '\b(\w+)=("[^"]*"|\'[^\']*\'|[^\'"\s\/<>]+)';

    var $_open_tag_expr = "<%s\b";
    var $_close_tag_expr = "<((\/%s\b)|(%s[^>\/]*\/))>";

    function Auth_OpenID_Parse()
    {
        $this->_link_find = sprintf("/<link\b(?!:)([^>]*)(?!<)>/%s",
                                    $this->_re_flags);

        $this->_entity_replacements = array(
                                            'amp' => '&',
                                            'lt' => '<',
                                            'gt' => '>',
                                            'quot' => '"'
                                            );

        $this->_attr_find = sprintf("/%s/%s",
                                    $this->_attr_find,
                                    $this->_re_flags);

        $this->_removed_re = sprintf("/%s/%s",
                                     $this->_removed_re,
                                     $this->_re_flags);

        $this->_ent_replace =
            sprintf("&(%s);", implode("|",
                                      $this->_entity_replacements));
    }

    /**
     * Returns a regular expression that will match a given tag in an
     * SGML string.
     */
    function tagMatcher($tag_name, $close_tags = null)
    {
        $expr = $this->_tag_expr;

        if ($close_tags) {
            $options = implode("|", array_merge(array($tag_name), $close_tags));
            $closer = sprintf("(?:%s)", $options);
        } else {
            $closer = $tag_name;
        }

        $expr = sprintf($expr, $tag_name, $closer);
        return sprintf("/%s/%s", $expr, $this->_re_flags);
    }

    function openTag($tag_name)
    {
        $expr = sprintf($this->_open_tag_expr, $tag_name);
        return sprintf("/%s/%s", $expr, $this->_re_flags);
    }

    function closeTag($tag_name)
    {
        $expr = sprintf($this->_close_tag_expr, $tag_name, $tag_name);
        return sprintf("/%s/%s", $expr, $this->_re_flags);
    }

    function htmlBegin($s)
    {
        $matches = array();
        $result = preg_match($this->openTag('html'), $s,
                             $matches, PREG_OFFSET_CAPTURE);
        if ($result === false || !$matches) {
            return false;
        }
        // Return the offset of the first match.
        return $matches[0][1];
    }

    function htmlEnd($s)
    {
        $matches = array();
        $result = preg_match($this->closeTag('html'), $s,
                             $matches, PREG_OFFSET_CAPTURE);
        if ($result === false || !$matches) {
            return false;
        }
        // Return the offset of the first match.
        return $matches[count($matches) - 1][1];
    }

    function headFind()
    {
        return $this->tagMatcher('head', array('body', 'html'));
    }

    function replaceEntities($str)
    {
        foreach ($this->_entity_replacements as $old => $new) {
            $str = preg_replace(sprintf("/&%s;/", $old), $new, $str);
        }
        return $str;
    }

    function removeQuotes($str)
    {
        $matches = array();
        $double = '/^"(.*)"$/';
        $single = "/^\'(.*)\'$/";

        if (preg_match($double, $str, $matches)) {
            return $matches[1];
        } else if (preg_match($single, $str, $matches)) {
            return $matches[1];
        } else {
            return $str;
        }
    }

    function match($regexp, $text, &$match)
    {
        if (!is_callable('mb_ereg_search_init')) {
            return preg_match($regexp, $text, $match);
        }

        $regexp = substr($regexp, 1, strlen($regexp) - 2 - strlen($this->_re_flags));
        mb_ereg_search_init($text);
        if (!mb_ereg_search($regexp)) {
            return false;
        }
        $match = mb_ereg_search_getregs();
        return true;
    }

    /**
     * Find all link tags in a string representing a HTML document and
     * return a list of their attributes.
     *
     * @todo This is quite ineffective and may fail with the default
     *       pcre.backtrack_limit of 100000 in PHP 5.2, if $html is big.
     *       It should rather use stripos (in PHP5) or strpos()+strtoupper()
     *       in PHP4 to manage this.
     *
     * @param string $html The text to parse
     * @return array $list An array of arrays of attributes, one for each
     * link tag
     */
    function parseLinkAttrs($html)
    {
        $stripped = preg_replace($this->_removed_re,
                                 "",
                                 $html);

        $html_begin = $this->htmlBegin($stripped);
        $html_end = $this->htmlEnd($stripped);

        if ($html_begin === false) {
            return array();
        }

        if ($html_end === false) {
            $html_end = strlen($stripped);
        }

        $stripped = substr($stripped, $html_begin,
                           $html_end - $html_begin);

        // Workaround to prevent PREG_BACKTRACK_LIMIT_ERROR:
        $old_btlimit = ini_set( 'pcre.backtrack_limit', -1 );

        // Try to find the <HEAD> tag.
        $head_re = $this->headFind();
        $head_match = array();
        if (!$this->match($head_re, $stripped, $head_match)) {
                     ini_set( 'pcre.backtrack_limit', $old_btlimit );
                     return array();
        }

        $link_data = array();
        $link_matches = array();

        if (!preg_match_all($this->_link_find, $head_match[0],
                            $link_matches)) {
            ini_set( 'pcre.backtrack_limit', $old_btlimit );
            return array();
        }

        foreach ($link_matches[0] as $link) {
            $attr_matches = array();
            preg_match_all($this->_attr_find, $link, $attr_matches);
            $link_attrs = array();
            foreach ($attr_matches[0] as $index => $full_match) {
                $name = $attr_matches[1][$index];
                $value = $this->replaceEntities(
                              $this->removeQuotes($attr_matches[2][$index]));

                $link_attrs[strtolower($name)] = $value;
            }
            $link_data[] = $link_attrs;
        }

        ini_set( 'pcre.backtrack_limit', $old_btlimit );
        return $link_data;
    }

    function relMatches($rel_attr, $target_rel)
    {
        // Does this target_rel appear in the rel_str?
        // XXX: TESTME
        $rels = preg_split("/\s+/", trim($rel_attr));
        foreach ($rels as $rel) {
            $rel = strtolower($rel);
            if ($rel == $target_rel) {
                return 1;
            }
        }

        return 0;
    }

    function linkHasRel($link_attrs, $target_rel)
    {
        // Does this link have target_rel as a relationship?
        // XXX: TESTME
        $rel_attr = Auth_OpeniD::arrayGet($link_attrs, 'rel', null);
        return ($rel_attr && $this->relMatches($rel_attr,
                                               $target_rel));
    }

    function findLinksRel($link_attrs_list, $target_rel)
    {
        // Filter the list of link attributes on whether it has
        // target_rel as a relationship.
        // XXX: TESTME
        $result = array();
        foreach ($link_attrs_list as $attr) {
            if ($this->linkHasRel($attr, $target_rel)) {
                $result[] = $attr;
            }
        }

        return $result;
    }

    function findFirstHref($link_attrs_list, $target_rel)
    {
        // Return the value of the href attribute for the first link
        // tag in the list that has target_rel as a relationship.
        // XXX: TESTME
        $matches = $this->findLinksRel($link_attrs_list,
                                       $target_rel);
        if (!$matches) {
            return null;
        }
        $first = $matches[0];
        return Auth_OpenID::arrayGet($first, 'href', null);
    }
}

function Auth_OpenID_legacy_discover($html_text, $server_rel,
                                     $delegate_rel)
{
    $p = new Auth_OpenID_Parse();

    $link_attrs = $p->parseLinkAttrs($html_text);

    $server_url = $p->findFirstHref($link_attrs,
                                    $server_rel);

    if ($server_url === null) {
        return false;
    } else {
        $delegate_url = $p->findFirstHref($link_attrs,
                                          $delegate_rel);
        return array($delegate_url, $server_url);
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'
describe 'package' do

  context 'with defaults for all parameters' do
    it { should contain_class('package') }
  end
end


text:
#ifndef C3DMODELNODE_H_
#define C3DMODELNODE_H_

#include "C3DNode.h"
#include "cocos2d.h"
namespace cocos2d
{

class C3DModel;
class C3DMaterial;
class C3DMesh;
class C3DLightFilter;
class C3DPass;
class C3DAnimation;

/**
 * Defines a node which contains a model.
 */
class C3DModelNode : public C3DNode
{

public:
    C3DNode::Type getType() const;

    static C3DModelNode* create(const std::string& id);

    C3DModel* getModel();

    void setModel(C3DModel* model);

    virtual void draw();

    virtual const Matrix& getWorldMatrix();

    C3DAnimation* getAnimation(const std::string& id = ""){return nullptr;};

    virtual C3DNode* clone(CloneContext& context) const;

protected:

    C3DModelNode(const std::string& id);

    virtual ~C3DModelNode();

public:

     /**
     * Pointer to the C3DModel attached to the C3DNode.
     */
    C3DModel* _model;

};

}

#endif


text:
#include "noircsocket.h"
#include "nosocket_p.h"
#include "nochannel.h"
#include "nouser_p.h"
#include "nonetwork.h"
#include "noserverinfo.h"
#include "nomodule_p.h"
#include "noclient.h"
#include "noapp.h"
#include "noquery.h"
#include "noutils.h"
#include "nonick.h"
#include "nohostmask.h"
#include "nosocketinfo.h"
#include "Csocket/Csocket.h"
#include <deque>

#define IRCSOCKMODULECALL(macFUNC, macEXITER) \
    NETWORKMODULECALL(macFUNC, d->network->user(), d->network, nullptr, macEXITER)

#define IRCSOCKPRIVATECALL(macFUNC, macEXITER) \
    NETWORKMODULECALL(macFUNC, network->user(), network, nullptr, macEXITER)

// It will be bad if user sets it to 0.00000000000001
// If you want no flood protection, set network's flood rate to -1
// TODO move this constant to NoNetwork?
static const double FLOOD_MINIMAL_RATE = 0.3;

class NoIrcSocketPrivate
{
public:
    static NoIrcSocketPrivate* get(NoIrcSocket* socket)
    {
        return socket->d.get();
    }

    void setNick(const NoString& nick);
    void parseISupport(const NoString& line);
    // This is called when we connect and the nick we want is already taken
    void sendAltNick(const NoString& sBadNick);
    void sendNextCap();
    void trySend();
    void resetChans();
    void putIrcQuick(const NoString& line); //!< Should be used for PONG only

    bool onCtcpReply(NoHostMask& nick, NoString& message);
    bool onPrivateCtcp(NoHostMask& nick, NoString& message);
    bool onChannelCtcp(NoNick& nick, const NoString& sChan, NoString& message);
    bool onGeneralCtcp(NoHostMask& nick, NoString& message);
    bool onPrivateMessage(NoHostMask& nick, NoString& message);
    bool onChannelMessage(NoNick& nick, const NoString& sChan, NoString& message);
    bool onPrivateNotice(NoHostMask& nick, NoString& message);
    bool onChannelNotice(NoNick& nick, const NoString& sChan, NoString& message);
    bool onServerCapAvailable(const NoString& cap);

    NoIrcSocket* q = nullptr;

    bool authed = false;
    bool hasNamesX = false;
    bool hasUhNames = false;
    NoString perms = "*!@%+";
    NoString permModes = "qaohv";
    std::set<uchar> userModes;
    std::map<uchar, NoIrcSocket::ChanModeArgs> chanModes;
    NoNetwork* network = nullptr;
    NoNick nick;
    NoString password = "";
    std::map<NoString, NoChannel*> chans;
    uint maxNickLen = 9;
    uint capPaused = 0;
    NoStringSet acceptedCaps;
    NoStringSet pendingCaps;
    time_t lastCtcp = 0;
    uint numCtcp = 0;
    static const time_t ctcpFloodTime;
    static const uint ctcpFloodCount;
    NoStringMap iSupport;
    std::deque<NoString> sendQueue;
    short int sendsAllowed = 0;
    ushort floodBurst = 0;
    double floodRate = 0;
    bool floodProtection = false;
};

// These are used in onGeneralCtcp()
const time_t NoIrcSocketPrivate::ctcpFloodTime = 5;
const uint NoIrcSocketPrivate::ctcpFloodCount = 5;

class NoIrcFloodTimer : public CCron
{
    NoIrcSocket* m_socket;

public:
    NoIrcFloodTimer(NoIrcSocket* socket) : m_socket(socket)
    {
        StartMaxCycles(NoIrcSocketPrivate::get(socket)->floodRate, 0);
    }
    NoIrcFloodTimer(const NoIrcFloodTimer&) = delete;
    NoIrcFloodTimer& operator=(const NoIrcFloodTimer&) = delete;
    void RunJob() override
    {
        NoIrcSocketPrivate* p = NoIrcSocketPrivate::get(m_socket);
        if (p->sendsAllowed < p->floodBurst) {
            p->sendsAllowed++;
        }
        p->trySend();
    }
};

bool NoIrcSocket::isFloodProtected(double fRate)
{
    return fRate > FLOOD_MINIMAL_RATE;
}

NoIrcSocket::NoIrcSocket(NoNetwork* network) : NoSocket(nullptr), d(new NoIrcSocketPrivate)
{
    d->q = this;
    d->network = network;
    d->sendsAllowed = network->floodBurst();
    d->floodBurst = network->floodBurst();
    d->floodRate = network->floodRate();
    d->floodProtection = isFloodProtected(network->floodRate());

    NoSocketPrivate::get(this)->allowControlCodes = true;
    enableReadLine();
    d->nick.setIdent(d->network->ident());
    d->nick.setHost(d->network->bindHost());
    setEncoding(d->network->encoding());

    d->chanModes['b'] = ListArg;
    d->chanModes['e'] = ListArg;
    d->chanModes['I'] = ListArg;
    d->chanModes['k'] = HasArg;
    d->chanModes['l'] = ArgWhenSet;
    d->chanModes['p'] = NoArg;
    d->chanModes['s'] = NoArg;
    d->chanModes['t'] = NoArg;
    d->chanModes['i'] = NoArg;
    d->chanModes['n'] = NoArg;

    network->setIrcSocket(this);

    // RFC says a line can have 512 chars max, but we don't care ;)
    setMaxBufferThreshold(1024);
    if (d->floodProtection) {
        NoSocketPrivate::get(this)->AddCron(new NoIrcFloodTimer(this));
    }
}

NoIrcSocket::~NoIrcSocket()
{
    if (!d->authed) {
        IRCSOCKMODULECALL(onIrcConnectionError(this), NOTHING);
    }

    const std::vector<NoChannel*>& channels = d->network->channels();
    for (NoChannel* channel : channels) {
        channel->reset();
    }

    d->network->ircDisconnected();

    for (const auto& it : d->chans) {
        delete it.second;
    }

    quit();
    d->chans.clear();
    NoSocketInfo info(this);
    NoUserPrivate::get(d->network->user())->addBytesRead(info.bytesRead());
    NoUserPrivate::get(d->network->user())->addBytesWritten(info.bytesWritten());
}

void NoIrcSocket::quit(const NoString& message)
{
    if (!d->authed) {
        close(CloseImmediately);
        return;
    }
    if (!message.empty()) {
        putIrc("QUIT :" + message);
    } else {
        putIrc("QUIT :" + d->network->expandString(d->network->quitMessage()));
    }
    close(CloseAfterWrite);
}

void NoIrcSocket::readLine(const NoString& data)
{
    NoString line = data;

    line.trimRight("\n\r");

    NO_DEBUG("(" << d->network->user()->userName() << "/" << d->network->name() << ") IRC -> BNC [" << line << "]");

    bool bReturn = false;
    IRCSOCKMODULECALL(onRaw(line), &bReturn);
    if (bReturn)
        return;

    if (line.startsWith("PING ")) {
        // Generate a reply and don't forward this to any user,
        // we don't want any PING forwarded
        d->putIrcQuick("PONG " + line.substr(5));
        return;
    } else if (No::token(line, 1).equals("PONG")) {
        // Block PONGs, we already responded to the pings
        return;
    } else if (line.startsWith("ERROR ")) {
        // ERROR :Closing Link: nick[24.24.24.24] (Excess Flood)
        NoString error(line.substr(6));
        error.trimPrefix();
        d->network->putStatus("Error from Server [" + error + "]");
        return;
    }

    NoString cmd = No::token(line, 1);

    if ((cmd.length() == 3) && (isdigit(cmd[0])) && (isdigit(cmd[1])) && (isdigit(cmd[2]))) {
        NoString sServer = No::token(line, 0).leftChomp_n(1);
        uint uRaw = cmd.toUInt();
        NoString nick = No::token(line, 2);
        NoString sRest = No::tokens(line, 3);
        NoString sTmp;

        switch (uRaw) {
        case 1: { // :irc.server.com 001 nick :Welcome to the Internet Relay network nick
            if (d->authed && sServer == "irc.bnc.no") {
                // d->bAuthed == true => we already received another 001 => we might be in a traffic loop
                d->network->putStatus("NoBNC seems to be connected to itself, disconnecting...");
                quit();
                return;
            }

            d->network->setIrcServer(sServer);
            setTimeout(NoNetwork::NoTrafficTimeout); // Now that we are connected, let nature take its course
            putIrc("WHO " + nick);

            d->authed = true;
            d->network->putStatus("Connected!");

            const std::vector<NoClient*>& vClients = d->network->clients();

            for (NoClient* client : vClients) {
                NoString sClientNick = client->nick(false);

                if (!sClientNick.equals(nick)) {
                    // If they connected with a nick that doesn't match the one we got on irc, then we need to update
                    // them
                    client->putClient(":" + sClientNick + "!" + d->nick.ident() + "@" + d->nick.host() + " NICK :" + nick);
                }
            }

            d->setNick(nick);

            IRCSOCKMODULECALL(onIrcConnected(), NOTHING);

            d->network->clearRawBuffer();
            d->network->addRawBuffer(":" + _NAMEDFMT(sServer) + " " + cmd + " {target} " + _NAMEDFMT(sRest));

            d->network->ircConnected();

            break;
        }
        case 5:
            d->parseISupport(sRest);
            d->network->updateExactRawBuffer(":" + _NAMEDFMT(sServer) + " " + cmd + " {target} " + _NAMEDFMT(sRest));
            break;
        case 10: { // :irc.server.com 010 nick <hostname> <port> :<info>
            NoString host = No::token(sRest, 0);
            NoString sPort = No::token(sRest, 1);
            NoString sInfo = No::tokens(sRest, 2).trimPrefix_n();
            NoServerInfo server = NoServerInfo(*d->network->currentServer()); // TODO: store NoServerInfo by value
            server.setPassword("");
            d->network->putStatus("Server [" + server.toString() + "] redirects us to [" + host + ":" + sPort +
                                  "] with reason [" + sInfo + "]");
            d->network->putStatus("Perhaps you want to add it as a new server.");
            // Don't send server redirects to the client
            return;
        }
        case 2:
        case 3:
        case 4:
        case 250: // highest connection count
        case 251: // user count
        case 252: // oper count
        case 254: // channel count
        case 255: // client count
        case 265: // local users
        case 266: // global users
            sTmp = ":" + _NAMEDFMT(sServer) + " " + cmd;
            d->network->updateRawBuffer(sTmp, sTmp + " {target} " + _NAMEDFMT(sRest));
            break;
        case 305:
            d->network->setIrcAway(false);
            break;
        case 306:
            d->network->setIrcAway(true);
            break;
        case 324: { // MODE
            sRest.trim();
            NoChannel* channel = d->network->findChannel(No::token(sRest, 0));

            if (channel) {
                channel->setModes(No::tokens(sRest, 1));

                // We don't SetModeKnown(true) here,
                // because a 329 will follow
                if (!channel->isModeKnown()) {
                    // When we JOIN, we send a MODE
                    // request. This makes sure the
                    // reply isn't forwarded.
                    return;
                }
                if (channel->isDetached()) {
                    return;
                }
            }
        } break;
        case 329: {
            sRest.trim();
            NoChannel* channel = d->network->findChannel(No::token(sRest, 0));

            if (channel) {
                ulong ulDate = No::token(line, 4).toULong();
                channel->setCreationDate(ulDate);

                if (!channel->isModeKnown()) {
                    channel->setModeKnown(true);
                    // When we JOIN, we send a MODE
                    // request. This makes sure the
                    // reply isn't forwarded.
                    return;
                }
                if (channel->isDetached()) {
                    return;
                }
            }
        } break;
        case 331: {
            // :irc.server.com 331 yournick #chan :No topic is set.
            NoChannel* channel = d->network->findChannel(No::token(line, 3));

            if (channel) {
                channel->setTopic("");
                if (channel->isDetached()) {
                    return;
                }
            }

            break;
        }
        case 332: {
            // :irc.server.com 332 yournick #chan :This is a topic
            NoChannel* channel = d->network->findChannel(No::token(line, 3));

            if (channel) {
                NoString topic = No::tokens(line, 4);
                topic.leftChomp(1);
                channel->setTopic(topic);
                if (channel->isDetached()) {
                    return;
                }
            }

            break;
        }
        case 333: {
            // :irc.server.com 333 yournick #chan setternick 1112320796
            NoChannel* channel = d->network->findChannel(No::token(line, 3));

            if (channel) {
                nick = No::token(line, 4);
                ulong ulDate = No::token(line, 5).toULong();

                channel->setTopicOwner(nick);
                channel->setTopicDate(ulDate);

                if (channel->isDetached()) {
                    return;
                }
            }

            break;
        }
        case 352: { // WHO
            // :irc.yourserver.com 352 yournick #chan ident theirhost.com irc.theirserver.com theirnick H :0 Real Name
            sServer = No::token(line, 0);
            nick = No::token(line, 7);
            NoString sChan = No::token(line, 3);
            NoString ident = No::token(line, 4);
            NoString host = No::token(line, 5);

            sServer.leftChomp(1);

            if (nick.equals(d->nick.nick())) {
                d->nick.setIdent(ident);
                d->nick.setHost(host);
            }

            d->network->setIrcNick(d->nick);
            d->network->setIrcServer(sServer);

            const std::vector<NoChannel*>& channels = d->network->channels();

            for (NoChannel* channel : channels) {
                channel->onWho(nick, ident, host);
            }

            if (d->hasNamesX && (nick.size() > 1) && isPermChar(nick[1])) {
                // line uses multi-prefix

                const std::vector<NoClient*>& vClients = d->network->clients();
                for (NoClient* client : vClients) {
                    if (client->hasNamesX()) {
                        d->network->putUser(line, client);
                    } else {
                        // The client doesn't support multi-prefix so we need to remove
                        // the other prefixes.

                        NoString newNick = nick;
                        size_t pos = nick.find_first_not_of(perms());
                        if (pos >= 2 && pos != NoString::npos) {
                            newNick = nick[0] + nick.substr(pos);
                        }
                        NoString sNewLine = sServer + " 352 " + No::token(line, 2) + " " + sChan + " " + ident + " " +
                                            host + " " + No::token(line, 6) + " " + newNick + " " + No::tokens(line, 8);
                        d->network->putUser(sNewLine, client);
                    }
                }

                return;
            }

            NoChannel* channel = d->network->findChannel(sChan);
            if (channel && channel->isDetached()) {
                return;
            }

            break;
        }
        case 353: { // NAMES
            sRest.trim();
            // Todo: allow for non @+= server msgs
            NoChannel* channel = d->network->findChannel(No::token(sRest, 1));
            // If we don't know that channel, some client might have
            // requested a /names for it and we really should forward this.
            if (channel) {
                NoString sNicks = No::tokens(sRest, 2).trimPrefix_n();
                channel->addNicks(sNicks);
                if (channel->isDetached()) {
                    return;
                }
            }

            forwardRaw353(line);

            // We forwarded it already, so return
            return;
        }
        case 366: { // end of names list
            // :irc.server.com 366 nick #chan :End of /NAMES list.
            NoChannel* channel = d->network->findChannel(No::token(sRest, 0));

            if (channel) {
                if (channel->isOn()) {
                    // If we are the only one in the chan, set our default modes
                    if (channel->nickCount() == 1) {
                        NoString modes = channel->defaultModes();

                        if (modes.empty()) {
                            modes = d->network->user()->defaultChanModes();
                        }

                        if (!modes.empty()) {
                            putIrc("MODE " + channel->name() + " " + modes);
                        }
                    }
                }
                if (channel->isDetached()) {
                    // don't put it to clients
                    return;
                }
            }

            break;
        }
        case 375: // begin motd
        case 422: // MOTD File is missing
            if (d->network->ircServer().equals(sServer)) {
                d->network->clearMotdBuffer();
            }
        case 372: // motd
        case 376: // end motd
            if (d->network->ircServer().equals(sServer)) {
                d->network->addMotdBuffer(":" + _NAMEDFMT(sServer) + " " + cmd + " {target} " + _NAMEDFMT(sRest));
            }
            break;
        case 437:
            // :irc.server.net 437 * badnick :nick/channel is temporarily unavailable
            // :irc.server.net 437 mynick badnick :nick/channel is temporarily unavailable
            // :irc.server.net 437 mynick badnick :Cannot change nickname while banned on channel
            if (d->network->isChannel(No::token(sRest, 0)) || nick != "*")
                break;
        case 432: // :irc.server.com 432 * nick :Erroneous Nickname: Illegal characters
        case 433: {
            NoString sBadNick = No::token(sRest, 0);

            if (!d->authed) {
                d->sendAltNick(sBadNick);
                return;
            }
            break;
        }
        case 451:
            // :irc.server.com 451 CAP :You have not registered
            // Servers that dont support CAP will give us this error, dont send it to the client
            if (nick.equals("CAP"))
                return;
        case 470: {
            // :irc.unreal.net 470 mynick [Link] #chan1 has become full, so you are automatically being transferred to
            // the linked channel #chan2
            // :mccaffrey.freenode.net 470 mynick #electronics ##electronics :Forwarding to another channel

            // freenode style numeric
            NoChannel* channel = d->network->findChannel(No::token(sRest, 0));
            if (!channel) {
                // unreal style numeric
                channel = d->network->findChannel(No::token(sRest, 1));
            }
            if (channel) {
                channel->disable();
                d->network->putStatus("channel [" + channel->name() + "] is linked to "
                                                                    "another channel and was thus disabled.");
            }
            break;
        }
        case 670:
            // :hydra.sector5d.org 670 kylef :STARTTLS successful, go ahead with TLS handshake
            // 670 is a response to `STARTTLS` telling the client to switch to TLS

            if (!isSsl()) {
                startTls();
                d->network->putStatus("Switched to SSL (STARTTLS)");
            }

            return;
        }
    } else {
        NoNick nick(No::token(line, 0).trimPrefix_n());
        NoHostMask mask(No::token(line, 0).trimPrefix_n());
        cmd = No::token(line, 1);
        NoString sRest = No::tokens(line, 2);

        if (cmd.equals("NICK")) {
            NoString newNick = sRest.trimPrefix_n();
            bool bIsVisible = false;

            for (NoChannel* channel : d->network->channels()) {
                if (channel->changeNick(nick.nick(), newNick)) {
                    if (!channel->isDetached())
                        bIsVisible = true;
                }
            }

            if (nick.equals(d->nick.nick())) {
                // We are changing our own nick, the clients always must see this!
                bIsVisible = false;
                d->setNick(newNick);
                d->network->putUser(line);
            }

            IRCSOCKMODULECALL(onNick(mask, newNick), NOTHING);

            if (!bIsVisible) {
                return;
            }
        } else if (cmd.equals("QUIT")) {
            NoString message = sRest.trimPrefix_n();
            bool bIsVisible = false;

            // :nick!ident@host.com QUIT :message

            if (nick.equals(d->nick.nick())) {
                d->network->putStatus("You quit [" + message + "]");
                // We don't call module hooks and we don't
                // forward this quit to clients (Some clients
                // disconnect if they receive such a QUIT)
                return;
            }

            for (NoChannel* channel : d->network->channels()) {
                if (channel->removeNick(nick.nick())) {
                    if (!channel->isDetached())
                        bIsVisible = true;
                }
            }

            IRCSOCKMODULECALL(onQuit(mask, message), NOTHING);

            if (!bIsVisible) {
                return;
            }
        } else if (cmd.equals("JOIN")) {
            NoString sChan = No::token(sRest, 0).trimPrefix_n();
            NoChannel* channel;

            if (nick.equals(d->nick.nick())) {
                d->network->addChannel(sChan, false);
                channel = d->network->findChannel(sChan);
                if (channel) {
                    channel->enable();
                    channel->setIsOn(true);
                    putIrc("MODE " + sChan);
                }
            } else {
                channel = d->network->findChannel(sChan);
            }

            if (channel) {
                channel->addNick(nick.hostMask());
                IRCSOCKMODULECALL(onJoin(nick.hostMask(), channel), NOTHING);

                if (channel->isDetached()) {
                    return;
                }
            }
        } else if (cmd.equals("PART")) {
            NoString sChan = No::token(sRest, 0).trimPrefix_n();
            NoString msg = No::tokens(sRest, 1).trimPrefix_n();

            NoChannel* channel = d->network->findChannel(sChan);
            bool bDetached = false;
            if (channel) {
                channel->removeNick(nick.nick());
                IRCSOCKMODULECALL(onPart(nick.hostMask(), channel, msg), NOTHING);

                if (channel->isDetached())
                    bDetached = true;
            }

            if (nick.equals(d->nick.nick())) {
                d->network->removeChannel(sChan);
            }

            /*
             * We use this boolean because
             * d->network->removeChannel() will delete this channel
             * and thus we would dereference an
             * already-freed pointer!
             */
            if (bDetached) {
                return;
            }
        } else if (cmd.equals("MODE")) {
            NoString target = No::token(sRest, 0);
            NoString modes = No::tokens(sRest, 1);
            if (modes.startsWith(":"))
                modes = modes.substr(1);

            NoChannel* channel = d->network->findChannel(target);
            if (channel) {
                channel->modeChange(modes, &nick);

                if (channel->isDetached()) {
                    return;
                }
            } else if (target == d->nick.nick()) {
                NoString sModeArg = No::token(modes, 0);
                bool bAdd = true;
                /* no module call defined (yet?)
                                MODULECALL(onRawUserMode(*opNick, *this, sModeArg, args), d->network->user(),
                   nullptr, );
                */
                for (uint a = 0; a < sModeArg.size(); a++) {
                    const uchar& mode = sModeArg[a];

                    if (mode == '+') {
                        bAdd = true;
                    } else if (mode == '-') {
                        bAdd = false;
                    } else {
                        if (bAdd) {
                            d->userModes.insert(mode);
                        } else {
                            d->userModes.erase(mode);
                        }
                    }
                }
            }
        } else if (cmd.equals("KICK")) {
            // :opnick!ident@host.com KICK #chan nick :msg
            NoString sChan = No::token(sRest, 0);
            NoString sKickedNick = No::token(sRest, 1);
            NoString msg = No::tokens(sRest, 2);
            msg.leftChomp(1);

            NoChannel* channel = d->network->findChannel(sChan);

            if (channel) {
                IRCSOCKMODULECALL(onKick(nick, sKickedNick, channel, msg), NOTHING);
                // do not remove the nick till after the onKick call, so modules
                // can do channel.FindNick or something to get more info.
                channel->removeNick(sKickedNick);
            }

            if (d->nick.nick().equals(sKickedNick) && channel) {
                channel->setIsOn(false);

                // Don't try to rejoin!
                channel->disable();
            }

            if ((channel) && (channel->isDetached())) {
                return;
            }
        } else if (cmd.equals("NOTICE")) {
            // :nick!ident@host.com NOTICE #chan :Message
            NoString target = No::token(sRest, 0);
            NoString msg = No::tokens(sRest, 1);
            msg.leftChomp(1);

            if (No::wildCmp(msg, "\001*\001")) {
                msg.leftChomp(1);
                msg.rightChomp(1);

                if (target.equals(d->nick.nick())) {
                    if (d->onCtcpReply(mask, msg)) {
                        return;
                    }
                }

                d->network->putUser(":" + nick.hostMask() + " NOTICE " + target + " :\001" + msg + "\001");
                return;
            } else {
                if (target.equals(d->nick.nick())) {
                    if (d->onPrivateNotice(mask, msg)) {
                        return;
                    }
                } else {
                    if (d->onChannelNotice(nick, target, msg)) {
                        return;
                    }
                }
            }

            if (nick.equals(d->network->ircServer())) {
                d->network->putUser(":" + nick.nick() + " NOTICE " + target + " :" + msg);
            } else {
                d->network->putUser(":" + nick.hostMask() + " NOTICE " + target + " :" + msg);
            }

            return;
        } else if (cmd.equals("TOPIC")) {
            // :nick!ident@host.com TOPIC #chan :This is a topic
            NoChannel* channel = d->network->findChannel(No::token(line, 2));

            if (channel) {
                NoString topic = No::tokens(line, 3);
                topic.leftChomp(1);

                IRCSOCKMODULECALL(onTopic(nick, channel, topic), &bReturn);
                if (bReturn)
                    return;

                channel->setTopicOwner(nick.nick());
                channel->setTopicDate((ulong)time(nullptr));
                channel->setTopic(topic);

                if (channel->isDetached()) {
                    return; // Don't forward this
                }

                line = ":" + nick.hostMask() + " TOPIC " + channel->name() + " :" + topic;
            }
        } else if (cmd.equals("PRIVMSG")) {
            // :nick!ident@host.com PRIVMSG #chan :Message
            NoString target = No::token(sRest, 0);
            NoString msg = No::tokens(sRest, 1).trimPrefix_n();

            if (No::wildCmp(msg, "\001*\001")) {
                msg.leftChomp(1);
                msg.rightChomp(1);

                if (target.equals(d->nick.nick())) {
                    if (d->onPrivateCtcp(mask, msg)) {
                        return;
                    }
                } else {
                    if (d->onChannelCtcp(nick, target, msg)) {
                        return;
                    }
                }

                d->network->putUser(":" + nick.hostMask() + " PRIVMSG " + target + " :\001" + msg + "\001");
                return;
            } else {
                if (target.equals(d->nick.nick())) {
                    if (d->onPrivateMessage(mask, msg)) {
                        return;
                    }
                } else {
                    if (d->onChannelMessage(nick, target, msg)) {
                        return;
                    }
                }

                d->network->putUser(":" + nick.hostMask() + " PRIVMSG " + target + " :" + msg);
                return;
            }
        } else if (cmd.equals("WALLOPS")) {
            // :blub!dummy@rox-8DBEFE92 WALLOPS :this is a test
            NoString msg = No::tokens(sRest, 0).trimPrefix_n();

            if (!d->network->isUserOnline()) {
                d->network->addNoticeBuffer(":" + _NAMEDFMT(nick.hostMask()) + " WALLOPS :{text}", msg);
            }
        } else if (cmd.equals("CAP")) {
            // CAPs are supported only before authorization.
            if (!d->authed) {
                // No::token(sRest, 0) is most likely "*". No idea why, the
                // CAP spec don't mention this, but all implementations
                // I've seen add this extra asterisk
                NoString sSubCmd = No::token(sRest, 1);

                // If the caplist of a reply is too long, it's split
                // into multiple replies. A "*" is prepended to show
                // that the list was split into multiple replies.
                // This is useful mainly for LS. For ACK and NAK
                // replies, there's no real need for this, because
                // we request only 1 capability per line.
                // If we will need to support broken servers or will
                // send several requests per line, need to delay ACK
                // actions until all ACK lines are received and
                // to recognize past request of NAK by 100 chars
                // of this reply.
                NoString args;
                if (No::token(sRest, 2) == "*") {
                    args = No::tokens(sRest, 3).trimPrefix_n();
                } else {
                    args = No::tokens(sRest, 2).trimPrefix_n();
                }

                if (sSubCmd == "LS") {
                    NoStringVector vsTokens = args.split(" ", No::SkipEmptyParts);

                    for (const NoString& cap : vsTokens) {
                        if (d->onServerCapAvailable(cap) || cap == "multi-prefix" || cap == "userhost-in-names") {
                            d->pendingCaps.insert(cap);
                        }
                    }
                } else if (sSubCmd == "ACK") {
                    args.trim();
                    IRCSOCKMODULECALL(onServerCapResult(args, true), NOTHING);
                    if ("multi-prefix" == args) {
                        d->hasNamesX = true;
                    } else if ("userhost-in-names" == args) {
                        d->hasUhNames = true;
                    }
                    d->acceptedCaps.insert(args);
                } else if (sSubCmd == "NAK") {
                    // This should work because there's no [known]
                    // capability with length of name more than 100 characters.
                    args.trim();
                    IRCSOCKMODULECALL(onServerCapResult(args, false), NOTHING);
                }

                d->sendNextCap();
            }
            // Don't forward any CAP stuff to the client
            return;
        } else if (cmd.equals("INVITE")) {
            IRCSOCKMODULECALL(onInvite(mask, No::token(line, 3).trimPrefix_n(":")), &bReturn);
            if (bReturn)
                return;
        }
    }

    d->network->putUser(line);
}

void NoIrcSocketPrivate::sendNextCap()
{
    if (!capPaused) {
        if (pendingCaps.empty()) {
            // We already got all needed ACK/NAK replies.
            q->putIrc("CAP END");
        } else {
            NoString cap = *pendingCaps.begin();
            pendingCaps.erase(pendingCaps.begin());
            q->putIrc("CAP REQ :" + cap);
        }
    }
}

void NoIrcSocket::pauseCap()
{
    ++d->capPaused;
}

void NoIrcSocket::resumeCap()
{
    --d->capPaused;
    d->sendNextCap();
}

void NoIrcSocket::setPassword(const NoString& s)
{
    d->password = s;
}

uint NoIrcSocket::maxNickLen() const
{
    return d->maxNickLen;
}

bool NoIrcSocketPrivate::onServerCapAvailable(const NoString& cap)
{
    bool bResult = false;
    IRCSOCKPRIVATECALL(onServerCapAvailable(cap), &bResult);
    return bResult;
}

bool NoIrcSocketPrivate::onCtcpReply(NoHostMask& nick, NoString& message)
{
    bool bResult = false;
    IRCSOCKPRIVATECALL(onCtcpReply(nick, message), &bResult);

    return bResult;
}

bool NoIrcSocketPrivate::onPrivateCtcp(NoHostMask& nick, NoString& message)
{
    bool bResult = false;
    IRCSOCKPRIVATECALL(onPrivateCtcp(nick, message), &bResult);
    if (bResult)
        return true;

    if (message.trimPrefix("ACTION ")) {
        bResult = false;
        IRCSOCKPRIVATECALL(onPrivateAction(nick, message), &bResult);
        if (bResult)
            return true;

        if (!network->isUserOnline() || !network->user()->autoClearQueryBuffer()) {
            NoQuery* query = network->addQuery(nick.nick());
            if (query) {
                query->addBuffer(":" + _NAMEDFMT(nick.toString()) + " PRIVMSG {target} :\001ACTION {text}\001", message);
            }
        }

        message = "ACTION " + message;
    }

    // This handles everything which wasn't handled yet
    return onGeneralCtcp(nick, message);
}

bool NoIrcSocketPrivate::onGeneralCtcp(NoHostMask& nick, NoString& message)
{
    const NoStringMap& ctcpReplies = network->user()->ctcpReplies();
    NoString sQuery = No::token(message, 0).toUpper();
    NoStringMap::const_iterator it = ctcpReplies.find(sQuery);
    bool bHaveReply = false;
    NoString reply;

    if (it != ctcpReplies.end()) {
        reply = network->expandString(it->second);
        bHaveReply = true;

        if (reply.empty()) {
            return true;
        }
    }

    if (!bHaveReply && !network->isUserAttached()) {
        if (sQuery == "VERSION") {
            reply = NoApp::tag(false);
        } else if (sQuery == "PING") {
            reply = No::tokens(message, 1);
        }
    }

    if (!reply.empty()) {
        time_t now = time(nullptr);
        // If the last CTCP is older than d->uCTCPFloodTime, reset the counter
        if (lastCtcp + ctcpFloodTime < now)
            numCtcp = 0;
        lastCtcp = now;
        // If we are over the limit, don't reply to this CTCP
        if (numCtcp >= ctcpFloodCount) {
            NO_DEBUG("CTCP flood detected - not replying to query");
            return true;
        }
        numCtcp++;

        q->putIrc("NOTICE " + nick.nick() + " :\001" + sQuery + " " + reply + "\001");
        return true;
    }

    return false;
}

bool NoIrcSocketPrivate::onPrivateNotice(NoHostMask& nick, NoString& message)
{
    bool bResult = false;
    IRCSOCKPRIVATECALL(onPrivateNotice(nick, message), &bResult);
    if (bResult)
        return true;

    if (!network->isUserOnline()) {
        // If the user is detached, add to the buffer
        network->addNoticeBuffer(":" + _NAMEDFMT(nick.toString()) + " NOTICE {target} :{text}", message);
    }

    return false;
}

bool NoIrcSocketPrivate::onPrivateMessage(NoHostMask& nick, NoString& message)
{
    bool bResult = false;
    IRCSOCKPRIVATECALL(onPrivateMessage(nick, message), &bResult);
    if (bResult)
        return true;

    if (!network->isUserOnline() || !network->user()->autoClearQueryBuffer()) {
        NoQuery* query = network->addQuery(nick.nick());
        if (query) {
            query->addBuffer(":" + _NAMEDFMT(nick.toString()) + " PRIVMSG {target} :{text}", message);
        }
    }

    return false;
}

bool NoIrcSocketPrivate::onChannelCtcp(NoNick& nick, const NoString& sChan, NoString& message)
{
    NoChannel* channel = network->findChannel(sChan);
    if (channel) {
        bool bResult = false;
        IRCSOCKPRIVATECALL(onChannelCtcp(nick, channel, message), &bResult);
        if (bResult)
            return true;

        // Record a /me
        if (message.trimPrefix("ACTION ")) {
            bResult = false;
            IRCSOCKPRIVATECALL(onChannelAction(nick, channel, message), &bResult);
            if (bResult)
                return true;
            if (!channel->autoClearChanBuffer() || !network->isUserOnline() || channel->isDetached()) {
                channel->addBuffer(":" + _NAMEDFMT(nick.hostMask()) + " PRIVMSG " + _NAMEDFMT(sChan) +
                                 " :\001ACTION {text}\001",
                                 message);
            }
            message = "ACTION " + message;
        }
    }

    NoHostMask mask(nick.hostMask());
    bool res = onGeneralCtcp(mask, message);

    // TODO: cleanup
    nick.setNick(mask.nick());
    nick.setIdent(mask.ident());
    nick.setHost(mask.host());

    return res || (channel && channel->isDetached());
}

bool NoIrcSocketPrivate::onChannelNotice(NoNick& nick, const NoString& sChan, NoString& message)
{
    NoChannel* channel = network->findChannel(sChan);
    if (channel) {
        bool bResult = false;
        IRCSOCKPRIVATECALL(onChannelNotice(nick, channel, message), &bResult);
        if (bResult)
            return true;

        if (!channel->autoClearChanBuffer() || !network->isUserOnline() || channel->isDetached()) {
            channel->addBuffer(":" + _NAMEDFMT(nick.hostMask()) + " NOTICE " + _NAMEDFMT(sChan) + " :{text}", message);
        }
    }

    return ((channel) && (channel->isDetached()));
}

bool NoIrcSocketPrivate::onChannelMessage(NoNick& nick, const NoString& sChan, NoString& message)
{
    NoChannel* channel = network->findChannel(sChan);
    if (channel) {
        bool bResult = false;
        IRCSOCKPRIVATECALL(onChannelMessage(nick, channel, message), &bResult);
        if (bResult)
            return true;

        if (!channel->autoClearChanBuffer() || !network->isUserOnline() || channel->isDetached()) {
            channel->addBuffer(":" + _NAMEDFMT(nick.hostMask()) + " PRIVMSG " + _NAMEDFMT(sChan) + " :{text}", message);
        }
    }

    return ((channel) && (channel->isDetached()));
}

void NoIrcSocket::putIrc(const NoString& line)
{
    // Only print if the line won't get sent immediately (same condition as in TrySend()!)
    if (d->floodProtection && d->sendsAllowed <= 0) {
        NO_DEBUG("(" << d->network->user()->userName() << "/" << d->network->name() << ") BNC -> IRC [" << line
                     << "] (queued)");
    }
    d->sendQueue.push_back(line);
    d->trySend();
}

void NoIrcSocketPrivate::putIrcQuick(const NoString& line)
{
    // Only print if the line won't get sent immediately (same condition as in TrySend()!)
    if (floodProtection && sendsAllowed <= 0) {
        NO_DEBUG("(" << network->user()->userName() << "/" << network->name() << ") BNC -> IRC [" << line
                     << "] (queued to front)");
    }
    sendQueue.push_front(line);
    trySend();
}

void NoIrcSocketPrivate::trySend()
{
    // This condition must be the same as in putIrc() and putIrcQuick()!
    while (!sendQueue.empty() && (!floodProtection || sendsAllowed > 0)) {
        sendsAllowed--;
        bool skip = false;
        NoString& line = sendQueue.front();
        IRCSOCKPRIVATECALL(onSendToIrc(line), &skip);
        if (!skip) {
            ;
            NO_DEBUG("(" << network->user()->userName() << "/" << network->name() << ") BNC -> IRC [" << line << "]");
            q->write(line + "\r\n");
        }
        sendQueue.pop_front();
    }
}

void NoIrcSocketPrivate::setNick(const NoString& name)
{
    nick.setNick(name);
    network->setIrcNick(name);
}

void NoIrcSocket::onConnected()
{
    NO_DEBUG(name() << " == Connected()");

    NoString pass = d->password;
    NoString nick = d->network->nick();
    NoString ident = d->network->ident();
    NoString realName = d->network->realName();

    bool bReturn = false;
    IRCSOCKMODULECALL(onIrcRegistration(pass, nick, ident, realName), &bReturn);
    if (bReturn)
        return;

    putIrc("CAP LS");

    if (!pass.empty()) {
        putIrc("PASS " + pass);
    }

    putIrc("NICK " + nick);
    putIrc("USER " + ident + " \"" + ident + "\" \"" + ident + "\" :" + realName);

    // SendAltNick() needs this
    d->nick.setNick(nick);
}

void NoIrcSocket::onDisconnected()
{
    IRCSOCKMODULECALL(onIrcDisconnected(), NOTHING);

    NO_DEBUG(name() << " == Disconnected()");
    if (!NoUserPrivate::get(d->network->user())->beingDeleted && d->network->isEnabled() && d->network->servers().size() != 0) {
        d->network->putStatus("Disconnected from IRC. Reconnecting...");
    }
    d->network->clearRawBuffer();
    d->network->clearMotdBuffer();

    d->resetChans();

    // send a "reset user modes" cmd to the client.
    // otherwise, on reconnect, it might think it still
    // had user modes that it actually doesn't have.
    NoString sUserMode;
    for (uchar cMode : d->userModes) {
        sUserMode += cMode;
    }
    if (!sUserMode.empty()) {
        d->network->putUser(":" + d->network->ircNick().hostMask() + " MODE " + d->network->ircNick().nick() + " :-" + sUserMode);
    }

    // also clear the user modes in our space:
    d->userModes.clear();
}

void NoIrcSocket::onSocketError(int iErrno, const NoString& description)
{
    NoString error = description;

    NO_DEBUG(name() << " == SockError(" << iErrno << " " << error << ")");
    if (!NoUserPrivate::get(d->network->user())->beingDeleted) {
        if (isReady()) {
            d->network->putStatus("Cannot connect to IRC (" + error + "). Retrying...");
        } else {
            d->network->putStatus("Disconnected from IRC (" + error + "). Reconnecting...");
        }
#ifdef HAVE_LIBSSL
        if (iErrno == errnoBadSSLCert) {
            // Stringify bad cert
            X509* pCert = NoSocketPrivate::get(this)->GetX509();
            if (pCert) {
                BIO* mem = BIO_new(BIO_s_mem());
                X509_print(mem, pCert);
                X509_free(pCert);
                char* pCertStr = nullptr;
                long iLen = BIO_get_mem_data(mem, &pCertStr);
                NoString sCert(pCertStr, iLen);
                BIO_free(mem);

                NoStringVector vsCert = sCert.split("\n");
                for (const NoString& s : vsCert) {
                    // It shouldn't contain any bad characters, but let's be safe...
                    d->network->putStatus("|" + No::escape(s, No::DebugFormat));
                }
                NoString sSHA1;
                if (peerFingerprint(sSHA1))
                    d->network->putStatus("SHA1: " + No::escape(sSHA1, No::HexColonFormat, No::HexColonFormat));
                NoString sSHA256 = fingerprint();
                d->network->putStatus("SHA-256: " + sSHA256);
                d->network->putStatus("If you trust this certificate, do /no AddTrustedServerFingerprint " + sSHA256);
            }
        }
#endif
    }
    d->network->clearRawBuffer();
    d->network->clearMotdBuffer();

    d->resetChans();
    d->userModes.clear();
}

void NoIrcSocket::onTimeout()
{
    NO_DEBUG(name() << " == Timeout()");
    if (!NoUserPrivate::get(d->network->user())->beingDeleted) {
        d->network->putStatus("IRC connection timed out.  Reconnecting...");
    }
    d->network->clearRawBuffer();
    d->network->clearMotdBuffer();

    d->resetChans();
    d->userModes.clear();
}

void NoIrcSocket::onConnectionRefused()
{
    NO_DEBUG(name() << " == ConnectionRefused()");
    if (!NoUserPrivate::get(d->network->user())->beingDeleted) {
        d->network->putStatus("Connection Refused.  Reconnecting...");
    }
    d->network->clearRawBuffer();
    d->network->clearMotdBuffer();
}

void NoIrcSocket::onReachedMaxBuffer()
{
    NO_DEBUG(name() << " == ReachedMaxBuffer()");
    d->network->putStatus("Received a too long line from the IRC server!");
    quit();
}

void NoIrcSocketPrivate::parseISupport(const NoString& line)
{
    NoStringVector vsTokens = line.split(" ", No::SkipEmptyParts);

    for (const NoString& sToken : vsTokens) {
        NoString name = No::token(sToken, 0, "=");
        NoString value = No::tokens(sToken, 1, "=");

        if (0 < name.length() && ':' == name[0]) {
            break;
        }

        iSupport[name] = value;

        if (name.equals("PREFIX")) {
            NoString sPrefixes = No::token(value, 1, ")");
            NoString sPermModes = No::token(value, 0, ")");
            sPermModes.trimLeft("(");

            if (!sPrefixes.empty() && sPermModes.size() == sPrefixes.size()) {
                perms = sPrefixes;
                permModes = sPermModes;
            }
        } else if (name.equals("CHANTYPES")) {
            network->setChannelPrefixes(value);
        } else if (name.equals("NICKLEN")) {
            uint uMax = value.toUInt();

            if (uMax) {
                maxNickLen = uMax;
            }
        } else if (name.equals("CHANMODES")) {
            if (!value.empty()) {
                chanModes.clear();

                for (uint a = 0; a < 4; a++) {
                    NoString modes = No::token(value, a, ",");

                    for (uint b = 0; b < modes.size(); b++) {
                        chanModes[modes[b]] = (NoIrcSocket::ChanModeArgs)a;
                    }
                }
            }
        } else if (name.equals("NAMESX")) {
            if (hasNamesX)
                continue;
            hasNamesX = true;
            q->putIrc("PROTOCTL NAMESX");
        } else if (name.equals("UHNAMES")) {
            if (hasUhNames)
                continue;
            hasUhNames = true;
            q->putIrc("PROTOCTL UHNAMES");
        }
    }
}

NoString NoIrcSocket::isupport(const NoString& key, const NoString& sDefault) const
{
    NoStringMap::const_iterator i = d->iSupport.find(key.toUpper());
    if (i == d->iSupport.end()) {
        return sDefault;
    } else {
        return i->second;
    }
}

void NoIrcSocket::forwardRaw353(const NoString& line) const
{
    const std::vector<NoClient*>& vClients = d->network->clients();

    for (NoClient* client : vClients) {
        forwardRaw353(line, client);
    }
}

void NoIrcSocket::forwardRaw353(const NoString& line, NoClient* client) const
{
    NoString sNicks = No::tokens(line, 5).trimPrefix_n();

    if ((!d->hasNamesX || client->hasNamesX()) && (!d->hasUhNames || client->hasUhNames())) {
        // client and server have both the same UHNames and Namesx stuff enabled
        d->network->putUser(line, client);
    } else {
        // Get everything except the actual user list
        NoString sTmp = No::token(line, 0, " :") + " :";

        // This loop runs once for every nick on the channel
        NoStringVector vsNicks = sNicks.split(" ", No::SkipEmptyParts);
        for (NoString nick : vsNicks) {
            if (nick.empty())
                break;

            if (d->hasNamesX && !client->hasNamesX() && isPermChar(nick[0])) {
                // Server has, client doesn't have NAMESX, so we just use the first perm char
                size_t pos = nick.find_first_not_of(perms());
                if (pos >= 2 && pos != NoString::npos) {
                    nick = nick[0] + nick.substr(pos);
                }
            }

            if (d->hasUhNames && !client->hasUhNames()) {
                // Server has, client hasnt UHNAMES,
                // so we strip away ident and host.
                nick = No::token(nick, 0, "!");
            }

            sTmp += nick + " ";
        }
        // Strip away the spaces we inserted at the end
        sTmp.trimRight(" ");
        d->network->putUser(sTmp, client);
    }
}

void NoIrcSocketPrivate::sendAltNick(const NoString& sBadNick)
{
    const NoString& sLastNick = nick.nick();

    // We don't know the maximum allowed nick length yet, but we know which
    // nick we sent last. If sBadNick is shorter than that, we assume the
    // server truncated our nick.
    if (sBadNick.length() < sLastNick.length())
        maxNickLen = (uint)sBadNick.length();

    uint uMax = maxNickLen;

    const NoString& sConfNick = network->nick();
    const NoString& sAltNick = network->altNick();
    NoString newNick = sConfNick.left(uMax - 1);

    if (sLastNick.equals(sConfNick)) {
        if ((!sAltNick.empty()) && (!sConfNick.equals(sAltNick))) {
            newNick = sAltNick;
        } else {
            newNick += "-";
        }
    } else if (sLastNick.equals(sAltNick) && !sAltNick.equals(newNick + "-")) {
        newNick += "-";
    } else if (sLastNick.equals(newNick + "-") && !sAltNick.equals(newNick + "|")) {
        newNick += "|";
    } else if (sLastNick.equals(newNick + "|") && !sAltNick.equals(newNick + "^")) {
        newNick += "^";
    } else if (sLastNick.equals(newNick + "^") && !sAltNick.equals(newNick + "a")) {
        newNick += "a";
    } else {
        char cLetter = 0;
        if (sBadNick.empty()) {
            network->putUser("No free nick available");
            q->quit();
            return;
        }

        cLetter = sBadNick.right(1)[0];

        if (cLetter == 'z') {
            network->putUser("No free nick found");
            q->quit();
            return;
        }

        newNick = sConfNick.left(uMax - 1) + ++cLetter;
        if (newNick.equals(sAltNick))
            newNick = sConfNick.left(uMax - 1) + ++cLetter;
    }
    q->putIrc("NICK " + newNick);
    nick.setNick(newNick);
}

uchar NoIrcSocket::permFromMode(uchar mode) const
{
    if (d->permModes.size() == d->perms.size()) {
        for (uint a = 0; a < d->permModes.size(); a++) {
            if (d->permModes[a] == mode) {
                return d->perms[a];
            }
        }
    }

    return 0;
}

std::map<uchar, NoIrcSocket::ChanModeArgs> NoIrcSocket::chanModes() const
{
    return d->chanModes;
}

bool NoIrcSocket::isPermChar(const char c) const
{
    return (c != '\0' && perms().contains(c));
}

bool NoIrcSocket::isPermMode(const char c) const
{
    return (c != '\0' && permModes().contains(c));
}

NoString NoIrcSocket::perms() const
{
    return d->perms;
}

NoString NoIrcSocket::permModes() const
{
    return d->permModes;
}

NoString NoIrcSocket::nickMask() const
{
    return d->nick.hostMask();
}

NoString NoIrcSocket::nick() const
{
    return d->nick.nick();
}

NoString NoIrcSocket::password() const
{
    return d->password;
}

NoNetwork* NoIrcSocket::network() const
{
    return d->network;
}

bool NoIrcSocket::hasNamesX() const
{
    return d->hasNamesX;
}

bool NoIrcSocket::hasUhNames() const
{
    return d->hasUhNames;
}

std::set<uchar> NoIrcSocket::userModes() const
{
    return d->userModes;
}

bool NoIrcSocket::isAuthed() const
{
    return d->authed;
}

bool NoIrcSocket::isCapAccepted(const NoString& cap)
{
    return 1 == d->acceptedCaps.count(cap);
}

NoStringMap NoIrcSocket::isupport() const
{
    return d->iSupport;
}

NoIrcSocket::ChanModeArgs NoIrcSocket::modeType(uchar mode) const
{
    std::map<uchar, ChanModeArgs>::const_iterator it = d->chanModes.find(mode);

    if (it == d->chanModes.end()) {
        return NoArg;
    }

    return it->second;
}

void NoIrcSocketPrivate::resetChans()
{
    for (const auto& it : chans)
        it.second->reset();
}


text:
package com.codeflowcrafter.PEAA.DataManipulation.BaseMapperInterfaces;

import com.codeflowcrafter.PEAA.Domain.Interfaces.IDomainObject;

import java.util.Hashtable;

/**
 * Created by aiko on 3/4/17.
 */

public interface IInvocationDelegates {
    Hashtable GetResults();

    void SetResults(Hashtable results);

    void SuccessfulInvocation(IDomainObject domainObject);

    void FailedInvocationDelegate(IDomainObject domainObject);
}


text:
/*!
	@file
	@author		Albert Semenov
	@date		12/2007
*/
/*
	This file is part of MyGUI.

	MyGUI is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	MyGUI is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with MyGUI.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_TEXT_BOX_H__
#define __MYGUI_TEXT_BOX_H__

#include "MyGUI_Prerequest.h"
#include "MyGUI_Widget.h"

namespace MyGUI
{

	class MYGUI_EXPORT TextBox :
		public Widget
	{
		MYGUI_RTTI_DERIVED( TextBox )

	public:
		TextBox();

		/** Get text region coordinate */
		virtual IntCoord getTextRegion();

		/** Get text region size */
		virtual IntSize getTextSize();

		/** Set widget caption */
		virtual void setCaption(const UString& _value);
		/** Get widget caption */
		virtual const UString& getCaption();

		/** Set widget text font */
		virtual void setFontName(const std::string& _value);
		/** Get widget text font name */
		const std::string& getFontName();

		/** Set widget text font height */
		virtual void setFontHeight(int _value);
		/** Get widget text font height */
		int getFontHeight();

		/** Set widget text align */
		virtual void setTextAlign(Align _value);
		/** Get widget text align */
		Align getTextAlign();

		/** Set widget text colour */
		virtual void setTextColour(const Colour& _value);
		/** Get widget text colour */
		const Colour& getTextColour();

		/** Set TextBox caption and replace special sequences.\n
			"\\n" will be replaced with new line character;\n
			"#{Keyword}" replaced with string from LanguageManager or
			left as it is if kayword wasn't found.
		*/
		void setCaptionWithReplacing(const std::string& _value);

		/** Set widget text shadow colour */
		virtual void setTextShadowColour(const Colour& _value);
		/** Get widget text shadow colour */
		const Colour& getTextShadowColour();

		/** Set widget text shadow */
		virtual void setTextShadow(bool _value);
		/** Get widget text shadow */
		bool getTextShadow();

	protected:
		virtual void setPropertyOverride(const std::string& _key, const std::string& _value);
	};

} // namespace MyGUI

#endif // __MYGUI_TEXT_BOX_H__


text:
package kv

import (
	"bytes"
	"context"
	"encoding/json"

	"github.com/influxdata/influxdb"
)

var (
	variableBucket    = []byte("variablesv1")
	variableOrgsIndex = []byte("variableorgsv1")
)

func (s *Service) initializeVariables(ctx context.Context, tx Tx) error {
	if _, err := tx.Bucket(variableBucket); err != nil {
		return err
	}
	if _, err := tx.Bucket(variableOrgsIndex); err != nil {
		return err
	}
	return nil
}

func decodeVariableOrgsIndexKey(indexKey []byte) (orgID influxdb.ID, variableID influxdb.ID, err error) {
	if len(indexKey) != 2*influxdb.IDLength {
		return 0, 0, &influxdb.Error{
			Code: influxdb.EInvalid,
			Msg:  "malformed variable orgs index key (please report this error)",
		}
	}

	if err := (&orgID).Decode(indexKey[:influxdb.IDLength]); err != nil {
		return 0, 0, &influxdb.Error{
			Code: influxdb.EInvalid,
			Msg:  "bad org id",
			Err:  influxdb.ErrInvalidID,
		}
	}

	if err := (&variableID).Decode(indexKey[influxdb.IDLength:]); err != nil {
		return 0, 0, &influxdb.Error{
			Code: influxdb.EInvalid,
			Msg:  "bad variable id",
			Err:  influxdb.ErrInvalidID,
		}
	}

	return orgID, variableID, nil
}

func (s *Service) findOrganizationVariables(ctx context.Context, tx Tx, orgID influxdb.ID) ([]*influxdb.Variable, error) {
	idx, err := tx.Bucket(variableOrgsIndex)
	if err != nil {
		return nil, err
	}

	// TODO(leodido): support find options
	cur, err := idx.Cursor()
	if err != nil {
		return nil, err
	}

	prefix, err := orgID.Encode()
	if err != nil {
		return nil, err
	}

	variables := []*influxdb.Variable{}
	for k, _ := cur.Seek(prefix); bytes.HasPrefix(k, prefix); k, _ = cur.Next() {
		_, id, err := decodeVariableOrgsIndexKey(k)
		if err != nil {
			return nil, err
		}

		m, err := s.findVariableByID(ctx, tx, id)
		if err != nil {
			return nil, err
		}

		variables = append(variables, m)
	}

	return variables, nil
}

func (s *Service) findVariables(ctx context.Context, tx Tx, filter influxdb.VariableFilter) ([]*influxdb.Variable, error) {
	if filter.OrganizationID != nil {
		return s.findOrganizationVariables(ctx, tx, *filter.OrganizationID)
	}

	if filter.Organization != nil {
		o, err := s.findOrganizationByName(ctx, tx, *filter.Organization)
		if err != nil {
			return nil, err
		}
		return s.findOrganizationVariables(ctx, tx, o.ID)
	}

	variables := []*influxdb.Variable{}
	filterFn := filterVariablesFn(filter)
	err := s.forEachVariable(ctx, tx, func(m *influxdb.Variable) bool {
		if filterFn(m) {
			variables = append(variables, m)
		}
		return true
	})

	if err != nil {
		return nil, err
	}

	return variables, nil
}

func filterVariablesFn(filter influxdb.VariableFilter) func(m *influxdb.Variable) bool {
	if filter.ID != nil {
		return func(m *influxdb.Variable) bool {
			return m.ID == *filter.ID
		}
	}

	if filter.OrganizationID != nil {
		return func(m *influxdb.Variable) bool {
			return m.OrganizationID == *filter.OrganizationID
		}
	}

	return func(m *influxdb.Variable) bool { return true }
}

// forEachVariable will iterate through all variables while fn returns true.
func (s *Service) forEachVariable(ctx context.Context, tx Tx, fn func(*influxdb.Variable) bool) error {
	b, err := tx.Bucket(variableBucket)
	if err != nil {
		return err
	}

	cur, err := b.Cursor()
	if err != nil {
		return err
	}

	for k, v := cur.First(); k != nil; k, v = cur.Next() {
		m := &influxdb.Variable{}
		if err := json.Unmarshal(v, m); err != nil {
			return err
		}
		if !fn(m) {
			break
		}
	}

	return nil
}

// FindVariables returns all variables in the store
func (s *Service) FindVariables(ctx context.Context, filter influxdb.VariableFilter, opt ...influxdb.FindOptions) ([]*influxdb.Variable, error) {
	// todo(leodido) > handle find options
	res := []*influxdb.Variable{}
	err := s.kv.View(ctx, func(tx Tx) error {
		variables, err := s.findVariables(ctx, tx, filter)
		if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound {
			return err
		}
		res = variables
		return nil
	})

	if err != nil {
		return nil, &influxdb.Error{
			Err: err,
		}
	}

	return res, nil
}

// FindVariableByID finds a single variable in the store by its ID
func (s *Service) FindVariableByID(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) {
	var variable *influxdb.Variable
	err := s.kv.View(ctx, func(tx Tx) error {
		m, pe := s.findVariableByID(ctx, tx, id)
		if pe != nil {
			return &influxdb.Error{
				Err: pe,
			}
		}
		variable = m
		return nil
	})
	if err != nil {
		return nil, err
	}

	return variable, nil
}

func (s *Service) findVariableByID(ctx context.Context, tx Tx, id influxdb.ID) (*influxdb.Variable, error) {
	encID, err := id.Encode()
	if err != nil {
		return nil, &influxdb.Error{
			Code: influxdb.EInvalid,
			Err:  err,
		}
	}

	b, err := tx.Bucket(variableBucket)
	if err != nil {
		return nil, err
	}

	d, err := b.Get(encID)
	if IsNotFound(err) {
		return nil, &influxdb.Error{
			Code: influxdb.ENotFound,
			Msg:  influxdb.ErrVariableNotFound,
		}
	}

	if err != nil {
		return nil, err
	}

	variable := &influxdb.Variable{}
	err = json.Unmarshal(d, &variable)
	if err != nil {
		return nil, &influxdb.Error{
			Err: err,
		}
	}

	return variable, nil
}

// CreateVariable creates a new variable and assigns it an ID
func (s *Service) CreateVariable(ctx context.Context, variable *influxdb.Variable) error {
	return s.kv.Update(ctx, func(tx Tx) error {
		variable.ID = s.IDGenerator.ID()

		if err := s.putVariableOrgsIndex(ctx, tx, variable); err != nil {
			return err
		}
		now := s.Now()
		variable.CreatedAt = now
		variable.UpdatedAt = now
		if pe := s.putVariable(ctx, tx, variable); pe != nil {
			return &influxdb.Error{
				Err: pe,
			}

		}
		return nil
	})
}

// ReplaceVariable puts a variable in the store
func (s *Service) ReplaceVariable(ctx context.Context, variable *influxdb.Variable) error {
	return s.kv.Update(ctx, func(tx Tx) error {
		if err := s.putVariableOrgsIndex(ctx, tx, variable); err != nil {
			return &influxdb.Error{
				Err: err,
			}
		}
		return s.putVariable(ctx, tx, variable)
	})
}

func encodeVariableOrgsIndex(variable *influxdb.Variable) ([]byte, error) {
	oID, err := variable.OrganizationID.Encode()
	if err != nil {
		return nil, &influxdb.Error{
			Err: err,
			Msg: "bad organization id",
		}
	}

	mID, err := variable.ID.Encode()
	if err != nil {
		return nil, &influxdb.Error{
			Err: err,
			Msg: "bad variable id",
		}
	}

	key := make([]byte, 0, influxdb.IDLength*2)
	key = append(key, oID...)
	key = append(key, mID...)

	return key, nil
}

func (s *Service) putVariableOrgsIndex(ctx context.Context, tx Tx, variable *influxdb.Variable) error {
	key, err := encodeVariableOrgsIndex(variable)
	if err != nil {
		return err
	}

	idx, err := tx.Bucket(variableOrgsIndex)
	if err != nil {
		return err
	}

	if err := idx.Put(key, nil); err != nil {
		return &influxdb.Error{
			Err: err,
		}
	}

	return nil
}

func (s *Service) removeVariableOrgsIndex(ctx context.Context, tx Tx, variable *influxdb.Variable) error {
	key, err := encodeVariableOrgsIndex(variable)
	if err != nil {
		return err
	}

	idx, err := tx.Bucket(variableOrgsIndex)
	if err != nil {
		return err
	}

	if err := idx.Delete(key); err != nil {
		return err
	}

	return nil
}

func (s *Service) putVariable(ctx context.Context, tx Tx, variable *influxdb.Variable) error {
	m, err := json.Marshal(variable)
	if err != nil {
		return &influxdb.Error{
			Err: err,
		}
	}

	encID, err := variable.ID.Encode()
	if err != nil {
		return &influxdb.Error{
			Code: influxdb.EInvalid,
			Err:  err,
		}
	}

	b, err := tx.Bucket(variableBucket)
	if err != nil {
		return err
	}

	if err := b.Put(encID, m); err != nil {
		return &influxdb.Error{
			Err: err,
		}
	}

	return nil
}

// UpdateVariable updates a single variable in the store with a changeset
func (s *Service) UpdateVariable(ctx context.Context, id influxdb.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) {
	var variable *influxdb.Variable
	err := s.kv.Update(ctx, func(tx Tx) error {
		m, pe := s.findVariableByID(ctx, tx, id)
		if pe != nil {
			return &influxdb.Error{
				Err: pe,
			}
		}
		m.UpdatedAt = s.Now()
		if err := update.Apply(m); err != nil {
			return &influxdb.Error{
				Err: err,
			}
		}

		variable = m
		if pe = s.putVariable(ctx, tx, variable); pe != nil {
			return &influxdb.Error{
				Err: pe,
			}
		}
		return nil
	})

	return variable, err
}

// DeleteVariable removes a single variable from the store by its ID
func (s *Service) DeleteVariable(ctx context.Context, id influxdb.ID) error {
	return s.kv.Update(ctx, func(tx Tx) error {
		m, pe := s.findVariableByID(ctx, tx, id)
		if pe != nil {
			return &influxdb.Error{
				Err: pe,
			}
		}

		encID, err := id.Encode()
		if err != nil {
			return &influxdb.Error{
				Err: err,
			}
		}

		if err := s.removeVariableOrgsIndex(ctx, tx, m); err != nil {
			return &influxdb.Error{
				Err: err,
			}
		}

		b, err := tx.Bucket(variableBucket)
		if err != nil {
			return err
		}

		if err := b.Delete(encID); err != nil {
			return &influxdb.Error{
				Err: err,
			}
		}

		return nil
	})
}


text:
namespace crazy {

namespace {

inline bool PageEquals(const char* p1, const char* p2) {
  return ::memcmp(p1, p2, PAGE_SIZE) == 0;
}

// Swap pages between |addr| and |addr + size| with the bytes
// from the ashmem region identified by |fd|, starting from
// a given |offset|. On failure return false and set |error| message.
bool SwapPagesFromFd(void* addr,
                     size_t size,
                     int fd,
                     size_t offset,
                     Error* error) {
  // Unmap current pages.
  if (::munmap(addr, size) < 0) {
    error->Format("%s: Could not unmap %p-%p: %s",
                  __FUNCTION__,
                  addr,
                  (char*)addr + size,
                  strerror(errno));
    return false;
  }

  // Remap the fd pages at the same location now.
  void* new_map = ::mmap(addr,
                         size,
                         PROT_READ,
                         MAP_FIXED | MAP_SHARED,
                         fd,
                         static_cast<off_t>(offset));
  if (new_map == MAP_FAILED) {
    char* p = reinterpret_cast<char*>(addr);
    error->Format("%s: Could not map %p-%p: %s",
                  __FUNCTION__,
                  p,
                  p + size,
                  strerror(errno));
    return false;
  }

// TODO(digit): Is this necessary?
#ifdef __arm__
  __clear_cache(addr, (char*)addr + size);
#endif

  // Done.
  return true;
}

}  // namespace

bool SharedRelro::Allocate(size_t relro_size,
                           const char* library_name,
                           Error* error) {
  // Allocate a new ashmem region.
  String name("RELRO:");
  name += library_name;
  if (!ashmem_.Allocate(relro_size, name.c_str())) {
    error->Format("Could not allocate RELRO ashmem region for %s: %s",
                  library_name,
                  strerror(errno));
    return false;
  }

  start_ = 0;
  size_ = relro_size;
  return true;
}

bool SharedRelro::CopyFrom(size_t relro_start,
                           size_t relro_size,
                           Error* error) {
  // Map it in the process.
  MemoryMapping map = MemoryMapping::Create(
      nullptr, relro_size, MemoryMapping::CAN_WRITE, ashmem_.fd());
  if (!map.IsValid()) {
    error->Format("Could not allocate RELRO mapping: %s", strerror(errno));
    return false;
  }

  // Copy process' RELRO into it.
  ::memcpy(map.address(), reinterpret_cast<void*>(relro_start), relro_size);

  // Unmap it.
  map.Deallocate();

  // Everything's good.
  start_ = relro_start;
  size_ = relro_size;
  return true;
}

bool SharedRelro::CopyFromRelocated(const ElfView* view,
                                    size_t load_address,
                                    size_t relro_start,
                                    size_t relro_size,
                                    Error* error) {
  // Offset of RELRO section in current library.
  size_t relro_offset = relro_start - view->load_address();

  ElfRelocations relocations;
  if (!relocations.Init(view, error))
    return false;

  // Map the region in memory (any address).
  MemoryMapping map = MemoryMapping::Create(
      nullptr, relro_size, MemoryMapping::CAN_READ_WRITE, ashmem_.fd());
  if (!map.IsValid()) {
    error->Format("Could not allocate RELRO mapping for: %s", strerror(errno));
    return false;
  }

  // Copy and relocate.
  relocations.CopyAndRelocate(relro_start,
                              reinterpret_cast<size_t>(map.address()),
                              load_address + relro_offset, relro_size);
  // Unmap it.
  map.Deallocate();
  start_ = load_address + relro_offset;
  size_ = relro_size;
  return true;
}

bool SharedRelro::ForceReadOnly(Error* error) {
  // Ensure the ashmem region content isn't writable anymore.
  if (!ashmem_.SetProtectionFlags(PROT_READ)) {
    error->Format("Could not make RELRO ashmem region read-only: %s",
                  strerror(errno));
    return false;
  }
  return true;
}

bool SharedRelro::InitFrom(size_t relro_start,
                           size_t relro_size,
                           int ashmem_fd,
                           Error* error) {
  // Create temporary mapping of the ashmem region.
  LOG("Entering addr=%p size=%p fd=%d", (void*)relro_start, (void*)relro_size,
      ashmem_fd);

  // Sanity check: Ashmem file descriptor must be read-only.
  if (!AshmemRegion::CheckFileDescriptorIsReadOnly(ashmem_fd)) {
    error->Format("Ashmem file descriptor is not read-only: %s",
                  strerror(errno));
    return false;
  }

  MemoryMapping fd_map = MemoryMapping::Create(
      nullptr, relro_size, MemoryMapping::CAN_READ, ashmem_fd);
  if (!fd_map.IsValid()) {
    error->Format("Cannot map RELRO ashmem region as read-only: %s",
                  strerror(errno));
    return false;
  }

  LOG("mapping allocated at %p", fd_map.address());

  char* cur_page = reinterpret_cast<char*>(relro_start);
  char* fd_page = static_cast<char*>(fd_map.address());
  size_t p = 0;
  size_t size = relro_size;
  size_t similar_size = 0;

  do {
    // Skip over dissimilar pages.
    while (p < size && !PageEquals(cur_page + p, fd_page + p)) {
      p += PAGE_SIZE;
    }

    // Count similar pages.
    size_t p2 = p;
    while (p2 < size && PageEquals(cur_page + p2, fd_page + p2)) {
      p2 += PAGE_SIZE;
    }

    if (p2 > p) {
      // Swap pages between |pos| and |pos2|.
      LOG("Swap pages at %p-%p", cur_page + p, cur_page + p2);
      if (!SwapPagesFromFd(cur_page + p, p2 - p, ashmem_fd, p, error))
        return false;

      similar_size += (p2 - p);
    }

    p = p2;
  } while (p < size);

  LOG("Swapped %d pages over %d (%d %%, %d KB not shared)",
      similar_size / PAGE_SIZE, size / PAGE_SIZE, similar_size * 100 / size,
      (size - similar_size) / 4096);

  if (similar_size == 0) {
    error->Format("No pages were swapped into RELRO ashmem");
    return false;
  }

  start_ = relro_start;
  size_ = relro_size;
  return true;
}

}  // namespace crazy


text:
This is just a checklist for now.

## Auth features
- [x] Register
- [x] Verify email
- [x] Login
- [x] Forgot password reset via email
- [ ] Remember me (not tested)

## Account features
- [x] Edit account (display name & password)

## Projects/Tasks
- [x] Create task
- [x] List tasks (home screen)
- [x] Check off completed tasks
- [x] Projectify screen
- [x] Add subtasks
- [ ] Add tabindex to button and content checkboxes in Add Task screen
- [ ] Allow select/deselect multiple contexts
- [ ] Remember selected contexts
- [ ] Inline edit task
- [ ] Algorithm for displaying nested tasks by context

## Contexts
- [x] getContexts
- [x] Add contexts to task
- [x] Filter by context
- [x] Add/list custom contexts
- [x] Remove custom contexts

## Roadblocks
- [ ] getRoadblocks function - start with hardcoded roadblocks
- [ ] ability to link person/date/task to roadblock
- [ ] simple way to select roadblock for task

## Tags
- [ ] getTags function - start with hardcoded tags
- [ ] ability to add custom tags

## Layout/CSS
- [x] Add TWBS3
- [x] Master layout template + header/footer

# Not Yet Approved Feature Ideas

- Due dates w/ reminders
- Analytics of tasks over time


text:
Interventions

        Posted on

        by

        Deleted User