text:
using System;
using System.Collections.Generic;

namespace Gwen.Control
{
	/// <summary>
	/// Tree control.
	/// </summary>
	[Xml.XmlControl(CustomHandler = "XmlElementHandler")]
	public class TreeControl : ScrollControl
	{
		private readonly TreeNode m_RootNode;
		private bool m_MultiSelect;

		/// <summary>
		/// List of selected nodes.
		/// </summary>
		public IEnumerable<TreeNode> SelectedNodes
		{
			get
			{
				List<TreeNode> selectedNodes = new List<TreeNode>();

				foreach (ControlBase child in m_RootNode.Children)
				{
					TreeNode node = child as TreeNode;
					if (node == null)
						continue;
					selectedNodes.AddRange(node.SelectedChildren);
				}

				return selectedNodes;
			}
		}

		/// <summary>
		/// First selected node (and only if nodes are not multiselectable).
		/// </summary>
		public TreeNode SelectedNode
		{
			get
			{
				List<TreeNode> selectedNodes = SelectedNodes as List<TreeNode>;
				if (selectedNodes.Count > 0)
					return selectedNodes[0];
				else
					return null;
			}
		}

		/// <summary>
		/// Determines if multiple nodes can be selected at the same time.
		/// </summary>
		[Xml.XmlProperty]
		public bool AllowMultiSelect { get { return m_MultiSelect; } set { m_MultiSelect = value; } }

		/// <summary>
		/// Get the root node of the tree view. Root node is an invisible always expanded node that works
		/// as a parent node for all first tier nodes visible on the control.
		/// </summary>
		public TreeNode RootNode { get { return m_RootNode; } }

		/// <summary>
		/// Invoked when the node's selected state has changed.
		/// </summary>
		[Xml.XmlEvent]
		public event GwenEventHandler<EventArgs> SelectionChanged
		{
			add
			{
				m_RootNode.SelectionChanged += value;
			}
			remove
			{
				m_RootNode.SelectionChanged -= value;
			}
		}

		/// <summary>
		/// Invoked when the node has been selected.
		/// </summary>
		[Xml.XmlEvent]
		public event GwenEventHandler<EventArgs> Selected
		{
			add
			{
				m_RootNode.Selected += value;
			}
			remove
			{
				m_RootNode.Selected -= value;
			}
		}

		/// <summary>
		/// Invoked when the node has been unselected.
		/// </summary>
		[Xml.XmlEvent]
		public event GwenEventHandler<EventArgs> Unselected
		{
			add
			{
				m_RootNode.Unselected += value;
			}
			remove
			{
				m_RootNode.Unselected -= value;
			}
		}

		/// <summary>
		/// Invoked when the node has been double clicked and contains no child nodes.
		/// </summary>
		[Xml.XmlEvent]
		public event GwenEventHandler<EventArgs> NodeDoubleClicked
		{
			add
			{
				m_RootNode.NodeDoubleClicked += value;
			}
			remove
			{
				m_RootNode.NodeDoubleClicked -= value;
			}
		}

		/// <summary>
		/// Invoked when the node has been expanded.
		/// </summary>
		[Xml.XmlEvent]
		public event GwenEventHandler<EventArgs> Expanded
		{
			add
			{
				m_RootNode.Expanded += value;
			}
			remove
			{
				m_RootNode.Expanded -= value;
			}
		}

		/// <summary>
		/// Invoked when the node has been collapsed.
		/// </summary>
		[Xml.XmlEvent]
		public event GwenEventHandler<EventArgs> Collapsed
		{
			add
			{
				m_RootNode.Collapsed += value;
			}
			remove
			{
				m_RootNode.Collapsed -= value;
			}
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="TreeControl"/> class.
		/// </summary>
		/// <param name="parent">Parent control.</param>
		public TreeControl(ControlBase parent)
			: base(parent)
		{
			Padding = Padding.One;

			MouseInputEnabled = true;
			EnableScroll(true, true);
			AutoHideBars = true;

			m_MultiSelect = false;

			m_RootNode = new TreeNode(this);
		}

		/// <summary>
		/// Renders the control using specified skin.
		/// </summary>
		/// <param name="skin">Skin to use.</param>
		protected override void Render(Skin.SkinBase skin)
		{
			if (ShouldDrawBackground)
				skin.DrawTreeControl(this);
		}

		/// <summary>
		/// Adds a new child node.
		/// </summary>
		/// <param name="label">Node's label.</param>
		/// <returns>Newly created control.</returns>
		public TreeNode AddNode(string label, string name = null, object userData = null)
		{
			return m_RootNode.AddNode(label, name, userData);
		}

		/// <summary>
		/// Removes all child nodes.
		/// </summary>
		public virtual void RemoveAll()
		{
			m_RootNode.DeleteAllChildren();
		}

		/// <summary>
		/// Remove node and all of it's child nodes.
		/// </summary>
		/// <param name="node">Node to remove.</param>
		public void RemoveNode(TreeNode node)
		{
			if (node == null)
				return;

			m_RootNode.RemoveNode(node);
		}

		/// <summary>
		/// Remove all nodes.
		/// </summary>
		public void RemoveAllNodes()
		{
			m_RootNode.RemoveAllNodes();
		}

		/// <summary>
		/// Opens the node and all child nodes.
		/// </summary>
		public void ExpandAll()
		{
			m_RootNode.ExpandAll();
		}

		/// <summary>
		/// Clears the selection on the node and all child nodes.
		/// </summary>
		public void UnselectAll()
		{
			m_RootNode.UnselectAll();
		}

		/// <summary>
		/// Find a node bu user data.
		/// </summary>
		/// <param name="userData">Node user data.</param>
		/// <param name="recursive">Determines whether the search should be recursive.</param>
		/// <returns>Found node or null.</returns>
		public TreeNode FindNodeByUserData(object userData, bool recursive = true)
		{
			return m_RootNode.FindNodeByUserData(userData, recursive);
		}

		/// <summary>
		/// Find a node by name.
		/// </summary>
		/// <param name="name">Node name</param>
		/// <param name="recursive">Determines whether the search should be recursive.</param>
		/// <returns>Found node or null.</returns>
		public TreeNode FindNodeByName(string name, bool recursive = true)
		{
			return m_RootNode.FindNodeByName(name, recursive) as TreeNode;
		}

		/// <summary>
		/// Handler for node added event.
		/// </summary>
		/// <param name="node">Node added.</param>
		public virtual void OnNodeAdded(TreeNode node)
		{
			node.LabelPressed += OnNodeSelected;
		}

		/// <summary>
		/// Handler for node selected event.
		/// </summary>
		/// <param name="Control">Node selected.</param>
		protected virtual void OnNodeSelected(ControlBase Control, EventArgs args)
		{
			if (!m_MultiSelect /*|| InputHandler.InputHandler.IsKeyDown(Key.Control)*/)
				UnselectAll();
		}

		internal static ControlBase XmlElementHandler(Xml.Parser parser, Type type, ControlBase parent)
		{
			TreeControl element = new TreeControl(parent);
			parser.ParseAttributes(element);
			if (parser.MoveToContent())
			{
				foreach (string elementName in parser.NextElement())
				{
					if (elementName == "TreeNode")
					{
						parser.ParseElement<TreeNode>(element);
					}
				}
			}
			return element;
		}
	}
}


text:
"""
Optimization algorithms.
"""

__author__ = "David Rusk <drusk@uvic.ca>"

import pandas as pd

def gradient_descent(dataset, theta, learning_rate, iterations=100):
    """
    TODO docs
    """
    theta = pd.Series(theta)
    data = dataset.get_data_frame()

    m = dataset.num_samples()
    iteration = 0
    while iteration < iterations:
        hypothesis = data.dot(theta)
        error = hypothesis - dataset.labels
        theta -= learning_rate * (1.0 / m) * (data.mul(error, axis=0)).sum()
        iteration += 1

    return theta

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;

namespace Azure.Management.Storage.Models
{
    /// <summary> The restriction because of which SKU cannot be used. </summary>
    public partial class Restriction
    {
        /// <summary> Initializes a new instance of Restriction. </summary>
        internal Restriction()
        {
        }

        /// <summary> Initializes a new instance of Restriction. </summary>
        /// <param name="type"> The type of restrictions. As of now only possible value for this is location. </param>
        /// <param name="values"> The value of restrictions. If the restriction type is set to location. This would be different locations where the SKU is restricted. </param>
        /// <param name="reasonCode"> The reason for the restriction. As of now this can be "QuotaId" or "NotAvailableForSubscription". Quota Id is set when the SKU has requiredQuotas parameter as the subscription does not belong to that quota. The "NotAvailableForSubscription" is related to capacity at DC. </param>
        internal Restriction(string type, IReadOnlyList<string> values, ReasonCode? reasonCode)
        {
            Type = type;
            Values = values;
            ReasonCode = reasonCode;
        }

        /// <summary> The type of restrictions. As of now only possible value for this is location. </summary>
        public string Type { get; }
        /// <summary> The value of restrictions. If the restriction type is set to location. This would be different locations where the SKU is restricted. </summary>
        public IReadOnlyList<string> Values { get; }
        /// <summary> The reason for the restriction. As of now this can be "QuotaId" or "NotAvailableForSubscription". Quota Id is set when the SKU has requiredQuotas parameter as the subscription does not belong to that quota. The "NotAvailableForSubscription" is related to capacity at DC. </summary>
        public ReasonCode? ReasonCode { get; }
    }
}


text:
#include <string.h>
#include <stdlib.h>

#ifndef true
  #define true 1
  #define false 0
#endif

#define CFC_NEED_BASE_STRUCT_DEF
#include "CFCBase.h"
#include "CFCParcel.h"
#include "CFCFileSpec.h"
#include "CFCVersion.h"
#include "CFCUtil.h"
#include "CFCJson.h"
#include "CFCClass.h"

struct CFCParcel {
    CFCBase base;
    char *name;
    char *nickname;
    char *host_module_name;
    CFCVersion *version;
    CFCVersion *major_version;
    CFCFileSpec *file_spec;
    char *prefix;
    char *Prefix;
    char *PREFIX;
    char *privacy_sym;
    int is_installed;
    CFCClass **classes;
    size_t num_classes;
    CFCPrereq **prereqs;
    size_t num_prereqs;
};

static void
S_set_prereqs(CFCParcel *self, CFCJson *node, const char *path);

static CFCClass*
S_fetch_class(CFCParcel *self, const char *class_name, int level);

static CFCParcel **registry = NULL;
static size_t num_registered = 0;

CFCParcel*
CFCParcel_fetch(const char *name) {
    for (size_t i = 0; i < num_registered ; i++) {
        CFCParcel *existing = registry[i];
        if (strcmp(existing->name, name) == 0) {
            return existing;
        }
    }

    return NULL;
}

void
CFCParcel_register(CFCParcel *self) {
    const char *name     = self->name;
    const char *nickname = self->nickname;

    for (size_t i = 0; i < num_registered ; i++) {
        CFCParcel *other = registry[i];

        if (strcmp(other->name, name) == 0) {
            CFCUtil_die("Parcel '%s' already registered", name);
        }
        if (strcmp(other->nickname, nickname) == 0) {
            CFCUtil_die("Parcel with nickname '%s' already registered",
                        nickname);
        }
    }

    size_t size = (num_registered + 2) * sizeof(CFCParcel*);
    registry = (CFCParcel**)REALLOCATE(registry, size);
    registry[num_registered++] = (CFCParcel*)CFCBase_incref((CFCBase*)self);
    registry[num_registered]   = NULL;
}

CFCParcel**
CFCParcel_all_parcels(void) {
    if (registry == NULL) {
        registry = (CFCParcel**)MALLOCATE(sizeof(CFCParcel*));
        registry[0] = NULL;
    }

    return registry;
}

void
CFCParcel_reap_singletons(void) {
    for (size_t i = 0; i < num_registered; i++) {
        CFCBase_decref((CFCBase*)registry[i]);
    }
    FREEMEM(registry);
    num_registered = 0;
    registry = NULL;
}

static int
S_validate_name_or_nickname(const char *orig) {
    const char *ptr = orig;
    for (; *ptr != 0; ptr++) {
        if (!CFCUtil_isalpha(*ptr)) { return false; }
    }
    return true;
}

static const CFCMeta CFCPARCEL_META = {
    "Clownfish::CFC::Model::Parcel",
    sizeof(CFCParcel),
    (CFCBase_destroy_t)CFCParcel_destroy
};

CFCParcel*
CFCParcel_new(const char *name, const char *nickname, CFCVersion *version,
              CFCVersion *major_version, CFCFileSpec *file_spec) {
    CFCParcel *self = (CFCParcel*)CFCBase_allocate(&CFCPARCEL_META);
    return CFCParcel_init(self, name, nickname, version, major_version,
                          file_spec);
}

CFCParcel*
CFCParcel_init(CFCParcel *self, const char *name, const char *nickname,
               CFCVersion *version, CFCVersion *major_version,
               CFCFileSpec *file_spec) {
    // Validate name.
    if (!name || !S_validate_name_or_nickname(name)) {
        CFCUtil_die("Invalid name: '%s'", name ? name : "[NULL]");
    }
    self->name = CFCUtil_strdup(name);

    // Validate or derive nickname.
    if (nickname) {
        if (!S_validate_name_or_nickname(nickname)) {
            CFCUtil_die("Invalid nickname: '%s'", nickname);
        }
        self->nickname = CFCUtil_strdup(nickname);
    }
    else {
        // Default nickname to name.
        self->nickname = CFCUtil_strdup(name);
    }

    // Default to version v0.
    if (version) {
        self->version = (CFCVersion*)CFCBase_incref((CFCBase*)version);
    }
    else {
        self->version = CFCVersion_new("v0");
    }
    if (major_version) {
        self->major_version
            = (CFCVersion*)CFCBase_incref((CFCBase*)major_version);
    }
    else {
        self->major_version = CFCVersion_new("v0");
    }

    // Set file_spec.
    self->file_spec = (CFCFileSpec*)CFCBase_incref((CFCBase*)file_spec);

    // Derive prefix, Prefix, PREFIX.
    size_t nickname_len  = strlen(self->nickname);
    size_t prefix_len = nickname_len ? nickname_len + 1 : 0;
    size_t amount     = prefix_len + 1;
    self->prefix = (char*)MALLOCATE(amount);
    self->Prefix = (char*)MALLOCATE(amount);
    self->PREFIX = (char*)MALLOCATE(amount);
    memcpy(self->Prefix, self->nickname, nickname_len);
    if (nickname_len) {
        self->Prefix[nickname_len]  = '_';
        self->Prefix[nickname_len + 1]  = '\0';
    }
    else {
        self->Prefix[nickname_len] = '\0';
    }
    for (size_t i = 0; i < amount; i++) {
        self->prefix[i] = CFCUtil_tolower(self->Prefix[i]);
        self->PREFIX[i] = CFCUtil_toupper(self->Prefix[i]);
    }
    self->prefix[prefix_len] = '\0';
    self->Prefix[prefix_len] = '\0';
    self->PREFIX[prefix_len] = '\0';

    // Derive privacy symbol.
    size_t privacy_sym_len = nickname_len + 4;
    self->privacy_sym = (char*)MALLOCATE(privacy_sym_len + 1);
    memcpy(self->privacy_sym, "CFP_", 4);
    for (size_t i = 0; i < nickname_len; i++) {
        self->privacy_sym[i+4] = CFCUtil_toupper(self->nickname[i]);
    }
    self->privacy_sym[privacy_sym_len] = '\0';

    // Initialize flags.
    self->is_installed = false;

    // Initialize arrays.
    self->classes = (CFCClass**)CALLOCATE(1, sizeof(CFCClass*));
    self->num_classes = 0;
    self->prereqs = (CFCPrereq**)CALLOCATE(1, sizeof(CFCPrereq*));
    self->num_prereqs = 0;

    return self;
}

static CFCParcel*
S_new_from_json(const char *json, CFCFileSpec *file_spec) {
    const char *path = file_spec ? CFCFileSpec_get_path(file_spec) : "[NULL]";
    CFCJson *parsed = CFCJson_parse(json);
    if (!parsed) {
        CFCUtil_die("Invalid JSON parcel definition in '%s'", path);
    }
    if (CFCJson_get_type(parsed) != CFCJSON_HASH) {
        CFCUtil_die("Parcel definition must be a hash in '%s'", path);
    }
    const char  *name          = NULL;
    const char  *nickname      = NULL;
    int          installed     = true;
    CFCVersion  *version       = NULL;
    CFCVersion  *major_version = NULL;
    CFCJson     *prereqs       = NULL;
    CFCJson    **children      = CFCJson_get_children(parsed);
    for (size_t i = 0; children[i]; i += 2) {
        const char *key = CFCJson_get_string(children[i]);
        CFCJson *value = children[i + 1];
        int value_type = CFCJson_get_type(value);
        if (strcmp(key, "name") == 0) {
            if (value_type != CFCJSON_STRING) {
                CFCUtil_die("'name' must be a string (filepath %s)", path);
            }
            name = CFCJson_get_string(value);
        }
        else if (strcmp(key, "nickname") == 0) {
            if (value_type != CFCJSON_STRING) {
                CFCUtil_die("'nickname' must be a string (filepath %s)",
                            path);
            }
            nickname = CFCJson_get_string(value);
        }
        else if (strcmp(key, "installed") == 0) {
            if (value_type != CFCJSON_BOOL) {
                CFCUtil_die("'installed' must be a boolean (filepath %s)",
                            path);
            }
            installed = CFCJson_get_bool(value);
        }
        else if (strcmp(key, "version") == 0) {
            if (value_type != CFCJSON_STRING) {
                CFCUtil_die("'version' must be a string (filepath %s)",
                            path);
            }
            version = CFCVersion_new(CFCJson_get_string(value));
        }
        else if (strcmp(key, "major_version") == 0) {
            if (value_type != CFCJSON_STRING) {
                CFCUtil_die("'major_version' must be a string (filepath %s)",
                            path);
            }
            major_version = CFCVersion_new(CFCJson_get_string(value));
        }
        else if (strcmp(key, "prerequisites") == 0) {
            if (value_type != CFCJSON_HASH) {
                CFCUtil_die("'prerequisites' must be a hash (filepath %s)",
                            path);
            }
            prereqs = value;
        }
        else {
            CFCUtil_die("Unrecognized key: '%s' (filepath '%s')",
                        key, path);
        }
    }
    if (!name) {
        CFCUtil_die("Missing required key 'name' (filepath '%s')", path);
    }
    if (!version) {
        CFCUtil_die("Missing required key 'version' (filepath '%s')", path);
    }
    CFCParcel *self = CFCParcel_new(name, nickname, version, major_version,
                                    file_spec);
    if (!file_spec || !CFCFileSpec_included(file_spec)) {
        self->is_installed = installed;
    }
    if (prereqs) {
        S_set_prereqs(self, prereqs, path);
    }
    CFCBase_decref((CFCBase*)version);
    CFCBase_decref((CFCBase*)major_version);

    CFCJson_destroy(parsed);
    return self;
}

static void
S_set_prereqs(CFCParcel *self, CFCJson *node, const char *path) {
    size_t num_prereqs = CFCJson_get_num_children(node) / 2;
    CFCJson **children = CFCJson_get_children(node);
    CFCPrereq **prereqs
        = (CFCPrereq**)MALLOCATE((num_prereqs + 1) * sizeof(CFCPrereq*));

    for (size_t i = 0; i < num_prereqs; ++i) {
        const char *name = CFCJson_get_string(children[2*i]);

        CFCJson *value = children[2*i+1];
        int value_type = CFCJson_get_type(value);
        CFCVersion *version = NULL;
        if (value_type == CFCJSON_STRING) {
            version = CFCVersion_new(CFCJson_get_string(value));
        }
        else if (value_type != CFCJSON_NULL) {
            CFCUtil_die("Invalid prereq value (filepath '%s')", path);
        }

        prereqs[i] = CFCPrereq_new(name, version);

        CFCBase_decref((CFCBase*)version);
    }
    prereqs[num_prereqs] = NULL;

    // Assume that prereqs are empty.
    FREEMEM(self->prereqs);
    self->prereqs     = prereqs;
    self->num_prereqs = num_prereqs;
}

CFCParcel*
CFCParcel_new_from_json(const char *json, CFCFileSpec *file_spec) {
    return S_new_from_json(json, file_spec);
}

CFCParcel*
CFCParcel_new_from_file(CFCFileSpec *file_spec) {
    const char *path = CFCFileSpec_get_path(file_spec);
    size_t len;
    char *json = CFCUtil_slurp_text(path, &len);
    CFCParcel *self = S_new_from_json(json, file_spec);
    FREEMEM(json);
    return self;
}

void
CFCParcel_destroy(CFCParcel *self) {
    FREEMEM(self->name);
    FREEMEM(self->nickname);
    FREEMEM(self->host_module_name);
    CFCBase_decref((CFCBase*)self->version);
    CFCBase_decref((CFCBase*)self->major_version);
    CFCBase_decref((CFCBase*)self->file_spec);
    FREEMEM(self->prefix);
    FREEMEM(self->Prefix);
    FREEMEM(self->PREFIX);
    FREEMEM(self->privacy_sym);
    for (size_t i = 0; self->classes[i]; ++i) {
        CFCBase_decref((CFCBase*)self->classes[i]);
    }
    FREEMEM(self->classes);
    for (size_t i = 0; self->prereqs[i]; ++i) {
        CFCBase_decref((CFCBase*)self->prereqs[i]);
    }
    FREEMEM(self->prereqs);
    CFCBase_destroy((CFCBase*)self);
}

int
CFCParcel_equals(CFCParcel *self, CFCParcel *other) {
    if (strcmp(self->name, other->name)) { return false; }
    if (strcmp(self->nickname, other->nickname)) { return false; }
    if (CFCVersion_compare_to(self->version, other->version) != 0) {
        return false;
    }
    if (CFCParcel_included(self) != CFCParcel_included(other)) {
        return false;
    }
    return true;
}

const char*
CFCParcel_get_name(CFCParcel *self) {
    return self->name;
}

const char*
CFCParcel_get_nickname(CFCParcel *self) {
    return self->nickname;
}

const char*
CFCParcel_get_host_module_name(CFCParcel *self) {
    return self->host_module_name;
}

void
CFCParcel_set_host_module_name(CFCParcel *self, const char *name) {
    if (self->host_module_name != NULL) {
        if (strcmp(self->host_module_name, name) != 0) {
            CFCUtil_die("Conflicting host modules '%s' and '%s' for parcel %s",
                        self->host_module_name, name, self->name);
        }
    }
    else {
        self->host_module_name = CFCUtil_strdup(name);
    }
}

int
CFCParcel_is_installed(CFCParcel *self) {
    return self->is_installed;
}

void
CFCParcel_set_installed(CFCParcel *self, int is_installed) {
    self->is_installed = is_installed;
}

CFCVersion*
CFCParcel_get_version(CFCParcel *self) {
    return self->version;
}

CFCVersion*
CFCParcel_get_major_version(CFCParcel *self) {
    return self->major_version;
}

const char*
CFCParcel_get_prefix(CFCParcel *self) {
    return self->prefix;
}

const char*
CFCParcel_get_Prefix(CFCParcel *self) {
    return self->Prefix;
}

const char*
CFCParcel_get_PREFIX(CFCParcel *self) {
    return self->PREFIX;
}

const char*
CFCParcel_get_privacy_sym(CFCParcel *self) {
    return self->privacy_sym;
}

const char*
CFCParcel_get_cfp_path(CFCParcel *self) {
    return self->file_spec
           ? CFCFileSpec_get_path(self->file_spec)
           : NULL;
}

const char*
CFCParcel_get_source_dir(CFCParcel *self) {
    return self->file_spec
           ? CFCFileSpec_get_source_dir(self->file_spec)
           : NULL;
}

int
CFCParcel_included(CFCParcel *self) {
    return self->file_spec ? CFCFileSpec_included(self->file_spec) : false;
}

CFCPrereq**
CFCParcel_get_prereqs(CFCParcel *self) {
    return self->prereqs;
}

CFCParcel**
CFCParcel_prereq_parcels(CFCParcel *self) {
    CFCParcel **parcels
        = (CFCParcel**)CALLOCATE(self->num_prereqs + 1, sizeof(CFCParcel*));

    for (size_t i = 0; self->prereqs[i]; ++i) {
        const char *name = CFCPrereq_get_name(self->prereqs[i]);
        parcels[i] = CFCParcel_fetch(name);
    }

    return parcels;
}

int
CFCParcel_has_prereq(CFCParcel *self, CFCParcel *parcel) {
    const char *name = CFCParcel_get_name(parcel);

    if (strcmp(CFCParcel_get_name(self), name) == 0) {
        return true;
    }

    for (int i = 0; self->prereqs[i]; ++i) {
        const char *prereq_name = CFCPrereq_get_name(self->prereqs[i]);
        if (strcmp(prereq_name, name) == 0) {
            return true;
        }
    }

    return false;
}

void
CFCParcel_read_host_data_json(CFCParcel *self, const char *host_lang) {
    const char *source_dir = CFCParcel_get_source_dir(self);
    char *path = CFCUtil_sprintf("%s" CHY_DIR_SEP "parcel_%s.json", source_dir,
                                 host_lang);

    size_t len;
    char *json = CFCUtil_slurp_text(path, &len);
    CFCJson *extra_data = CFCJson_parse(json);
    if (!extra_data) {
        CFCUtil_die("Invalid JSON in file '%s'", path);
    }

    CFCJson *host_module_json
        = CFCJson_find_hash_elem(extra_data, "host_module");
    if (host_module_json) {
        const char *name = CFCJson_get_string(host_module_json);
        CFCParcel_set_host_module_name(self, name);
    }

    CFCJson *class_hash = CFCJson_find_hash_elem(extra_data, "classes");
    if (class_hash) {
        CFCJson **children = CFCJson_get_children(class_hash);
        for (int i = 0; children[i]; i += 2) {
            const char *class_name = CFCJson_get_string(children[i]);
            CFCClass *klass = CFCParcel_class(self, class_name);
            if (!klass) {
                CFCUtil_die("Class '%s' in '%s' not found", class_name, path);
            }
            CFCClass_read_host_data_json(klass, children[i+1], path);
        }
    }

    CFCJson_destroy(extra_data);
    FREEMEM(json);
    FREEMEM(path);
}

void
CFCParcel_add_class(CFCParcel *self, CFCClass *klass) {
    // Ensure unique class name.
    const char *class_name = CFCClass_get_name(klass);
    CFCClass *other = S_fetch_class(self, class_name, 2);
    if (other) {
        CFCUtil_die("Two classes with name %s", class_name);
    }

    const char *struct_sym = CFCClass_get_struct_sym(klass);
    const char *nickname   = CFCClass_get_nickname(klass);

    for (size_t i = 0; self->classes[i]; ++i) {
        CFCClass *other = self->classes[i];

        // Ensure unique struct symbol and nickname in parcel.
        if (strcmp(struct_sym, CFCClass_get_struct_sym(other)) == 0) {
            CFCUtil_die("Class name conflict between %s and %s",
                        CFCClass_get_name(klass), CFCClass_get_name(other));
        }
        if (strcmp(nickname, CFCClass_get_nickname(other)) == 0) {
            CFCUtil_die("Class nickname conflict between %s and %s",
                        CFCClass_get_name(klass), CFCClass_get_name(other));
        }
    }

    size_t num_classes = self->num_classes;
    size_t size = (num_classes + 2) * sizeof(CFCClass*);
    CFCClass **classes = (CFCClass**)REALLOCATE(self->classes, size);
    classes[num_classes]   = (CFCClass*)CFCBase_incref((CFCBase*)klass);
    classes[num_classes+1] = NULL;
    self->classes     = classes;
    self->num_classes = num_classes + 1;
}

static int
S_compare_class_name(const void *va, const void *vb) {
    const char *a = CFCClass_get_name(*(CFCClass**)va);
    const char *b = CFCClass_get_name(*(CFCClass**)vb);

    return strcmp(a, b);
}

void
CFCParcel_connect_and_sort_classes(CFCParcel *self) {
    size_t num_classes = self->num_classes;
    size_t alloc_size  = (num_classes + 1) * sizeof(CFCClass*);
    CFCClass **classes = self->classes;
    CFCClass **sorted  = (CFCClass**)MALLOCATE(alloc_size);

    // Perform a depth-first search of the classes in the parcel, and store
    // the classes in the order that they were visited. This makes sure
    // that subclasses are sorted after their parents.
    //
    // To avoid a recursive algorithm, the end of the sorted array is used
    // as a stack for classes that have yet to be visited.
    //
    // Root and child classes are sorted by name to get a deterministic
    // order.

    // Set up parent/child relationship of classes and find subtree roots
    // in parcel.
    size_t todo = num_classes;
    for (size_t i = 0; i < num_classes; i++) {
        CFCClass *klass  = classes[i];
        CFCClass *parent = NULL;

        const char *parent_name = CFCClass_get_parent_class_name(klass);
        if (parent_name) {
            parent = S_fetch_class(self, parent_name, 1);
            if (!parent) {
                CFCUtil_die("Parent class '%s' of '%s' not found in parcel"
                            " '%s' or its prerequisites", parent_name,
                            CFCClass_get_name(klass), self->name);
            }
            CFCClass_add_child(parent, klass);
        }

        if (!parent || !CFCClass_in_parcel(parent, self)) {
            // Subtree root.
            sorted[--todo] = klass;
        }

        // Resolve types.
        CFCClass_resolve_types(klass);
    }

    qsort(&sorted[todo], num_classes - todo, sizeof(sorted[0]),
          S_compare_class_name);

    size_t num_sorted = 0;
    while (todo < num_classes) {
        CFCClass *klass = sorted[todo++];
        sorted[num_sorted++] = klass;

        // Push children on stack. Since this function is called first for
        // prereq parcels, we can be sure that the class doesn't have
        // children from another parcel yet.
        CFCClass **children = CFCClass_children(klass);
        size_t prev_todo = todo;
        for (size_t i = 0; children[i]; i++) {
            if (todo <= num_sorted) {
                CFCUtil_die("Internal error in CFCParcel_sort_classes");
            }
            sorted[--todo] = children[i];
        }

        qsort(&sorted[todo], prev_todo - todo, sizeof(sorted[0]),
              S_compare_class_name);
    }

    if (num_sorted != num_classes) {
        CFCUtil_die("Internal error in CFCParcel_sort_classes");
    }

    sorted[num_classes] = NULL;

    FREEMEM(self->classes);
    self->classes = sorted;
}

CFCClass*
CFCParcel_class(CFCParcel *self, const char *class_name) {
    return S_fetch_class(self, class_name, 0);
}

static CFCClass*
S_fetch_class(CFCParcel *self, const char *class_name, int level) {
    // level == 0: Only search parcel.
    // level == 1: Search parcel and direct prereqs.
    // level == 2: Search parcel an indirect prereqs.

    for (size_t i = 0; self->classes[i]; ++i) {
        CFCClass *klass = self->classes[i];
        if (strcmp(CFCClass_get_name(klass), class_name) == 0) {
            return klass;
        }
    }

    if (level == 0) { return NULL; }
    if (level == 1) { level = 0; }

    for (size_t i = 0; self->prereqs[i]; ++i) {
        const char *prereq_name   = CFCPrereq_get_name(self->prereqs[i]);
        CFCParcel  *prereq_parcel = CFCParcel_fetch(prereq_name);

        CFCClass *klass = S_fetch_class(prereq_parcel, class_name, level);
        if (klass) { return klass; }
    }

    return NULL;
}

static CFCClass*
S_class_by_struct_sym(CFCParcel *self, const char *struct_sym,
                      size_t prefix_len) {
    // If prefix_len is 0, struct_sym is a short symbol without prefix.
    // Search for a class and check for ambiguity.
    //
    // If prefix_len is greater than 0, struct_sym is a full symbol with prefix.
    // Return a matching class as soon as it's found.

    if (prefix_len != 0
        && strncmp(self->prefix, struct_sym, prefix_len) != 0
       ) {
        return NULL;
    }

    const char *short_struct_sym = struct_sym + prefix_len;
    for (size_t i = 0; self->classes[i]; ++i) {
        CFCClass *klass = self->classes[i];
        if (strcmp(CFCClass_get_struct_sym(klass), short_struct_sym) == 0) {
            return klass;
        }
    }

    return NULL;
}

static CFCClass*
S_class_by_struct_sym_prereq(CFCParcel *self, const char *struct_sym,
                             size_t prefix_len) {
    CFCClass *klass = S_class_by_struct_sym(self, struct_sym, prefix_len);
    if (klass && prefix_len != 0) { return klass; }

    for (size_t i = 0; self->prereqs[i]; ++i) {
        const char *prereq_name   = CFCPrereq_get_name(self->prereqs[i]);
        CFCParcel  *prereq_parcel = CFCParcel_fetch(prereq_name);
        CFCClass *candidate
            = S_class_by_struct_sym(prereq_parcel, struct_sym, prefix_len);

        if (candidate) {
            if (prefix_len != 0) { return candidate; }
            if (klass) {
                CFCUtil_warn("Type '%s' is ambiguous. Do you mean %s or %s?",
                             struct_sym, CFCClass_full_struct_sym(klass),
                             CFCClass_full_struct_sym(candidate));
                return NULL;
            }
            klass = candidate;
        }
    }

    return klass;
}

CFCClass*
CFCParcel_class_by_short_sym(CFCParcel *self, const char *struct_sym) {
    return S_class_by_struct_sym_prereq(self, struct_sym, 0);
}

CFCClass*
CFCParcel_class_by_full_sym(CFCParcel *self, const char *full_struct_sym) {
    size_t prefix_len = 0;
    size_t sym_len    = strlen(full_struct_sym);
    while (prefix_len < sym_len
           && !CFCUtil_isupper(full_struct_sym[prefix_len])
          ) {
        prefix_len += 1;
    }
    if (!prefix_len) {
        CFCUtil_die("Full struct symbol '%s' has invalid prefix",
                    full_struct_sym);
    }

    return S_class_by_struct_sym_prereq(self, full_struct_sym, prefix_len);
}

int
CFCParcel_is_cfish(CFCParcel *self) {
    return !strcmp(self->prefix, "cfish_");
}

CFCClass**
CFCParcel_get_classes(CFCParcel *self) {
    return self->classes;
}

/**************************************************************************/

struct CFCPrereq {
    CFCBase base;
    char *name;
    CFCVersion *version;
};

static const CFCMeta CFCPREREQ_META = {
    "Clownfish::CFC::Model::Prereq",
    sizeof(CFCPrereq),
    (CFCBase_destroy_t)CFCPrereq_destroy
};

CFCPrereq*
CFCPrereq_new(const char *name, CFCVersion *version) {
    CFCPrereq *self = (CFCPrereq*)CFCBase_allocate(&CFCPREREQ_META);
    return CFCPrereq_init(self, name, version);
}

CFCPrereq*
CFCPrereq_init(CFCPrereq *self, const char *name, CFCVersion *version) {
    // Validate name.
    if (!name || !S_validate_name_or_nickname(name)) {
        CFCUtil_die("Invalid name: '%s'", name ? name : "[NULL]");
    }
    self->name = CFCUtil_strdup(name);

    // Default to version v0.
    if (version) {
        self->version = (CFCVersion*)CFCBase_incref((CFCBase*)version);
    }
    else {
        self->version = CFCVersion_new("v0");
    }

    return self;
}

void
CFCPrereq_destroy(CFCPrereq *self) {
    FREEMEM(self->name);
    CFCBase_decref((CFCBase*)self->version);
    CFCBase_destroy((CFCBase*)self);
}

const char*
CFCPrereq_get_name(CFCPrereq *self) {
    return self->name;
}

CFCVersion*
CFCPrereq_get_version(CFCPrereq *self) {
    return self->version;
}


text:
<?php

namespace Faker\Provider;

abstract class Text extends Base
{
    protected static $baseText = '';
    protected static $separator = ' ';
    protected static $separatorLen = 1;
    protected $explodedText;
    protected $consecutiveWords = array();
    protected static $textStartsWithUppercase = true;

    /**
     * Generate a text string by the Markov chain algorithm.
     *
     * Depending on the $maxNbChars, returns a random valid looking text. The algorithm
     * generates a weighted table with the specified number of words as the index and the
     * possible following words as the value.
     *
     * @example 'Alice, swallowing down her flamingo, and began by taking the little golden key'
     * @param integer $maxNbChars Maximum number of characters the text should contain (minimum: 10)
     * @param integer $indexSize  Determines how many words are considered for the generation of the next word.
     *                             The minimum is 1, and it produces the higher level of randomness, although the
     *                             generated text usually doesn't make sense. Higher index sizes (up to 5)
     *                             produce more correct text, at the price of less randomness.
     * @return string
     */
    public function realText($maxNbChars = 200, $indexSize = 2)
    {
        if ($maxNbChars < 10) {
            throw new \InvalidArgumentException('maxNbChars must be at least 10');
        }

        if ($indexSize < 1) {
            throw new \InvalidArgumentException('indexSize must be at least 1');
        }

        if ($indexSize > 5) {
            throw new \InvalidArgumentException('indexSize must be at most 5');
        }

        $words = $this->getConsecutiveWords($indexSize);
        $result = array();
        $resultLength = 0;
        // take a random starting point
        $next = static::randomKey($words);
        while ($resultLength < $maxNbChars && isset($words[$next])) {
            // fetch a random word to append
            $word = static::randomElement($words[$next]);

            // calculate next index
            $currentWords = static::explode($next);
            $currentWords[] = $word;
            array_shift($currentWords);
            $next = static::implode($currentWords);

            // ensure text starts with an uppercase letter
            if ($resultLength == 0 && !static::validStart($word)) {
                continue;
            }

            // append the element
            $result[] = $word;
            $resultLength += static::strlen($word) + static::$separatorLen;
        }

        // remove the element that caused the text to overflow
        array_pop($result);

        // build result
        $result = static::implode($result);

        return static::appendEnd($result);
    }

    protected function getConsecutiveWords($indexSize)
    {
        if (!isset($this->consecutiveWords[$indexSize])) {
            $parts = $this->getExplodedText();
            $words = array();
            $index = array();
            for ($i = 0; $i < $indexSize; $i++) {
                $index[] = array_shift($parts);
            }

            for ($i = 0, $count = count($parts); $i < $count; $i++) {
                $stringIndex = static::implode($index);
                if (!isset($words[$stringIndex])) {
                    $words[$stringIndex] = array();
                }
                $word = $parts[$i];
                $words[$stringIndex][] = $word;
                array_shift($index);
                $index[] = $word;
            }
            // cache look up words for performance
            $this->consecutiveWords[$indexSize] = $words;
        }

        return $this->consecutiveWords[$indexSize];
    }

    protected function getExplodedText()
    {
        if ($this->explodedText === null) {
            $this->explodedText = static::explode(preg_replace('/\s+/u', ' ', static::$baseText));
        }

        return $this->explodedText;
    }

    protected static function explode($text)
    {
        return explode(static::$separator, $text);
    }

    protected static function implode($words)
    {
        return implode(static::$separator, $words);
    }

    protected static function strlen($text)
    {
        return function_exists('mb_strlen') ? mb_strlen($text, 'UTF-8') : strlen($text);
    }

    protected static function validStart($word)
    {
        $isValid = true;
        if (self::$textStartsWithUppercase) {
            $isValid = preg_match('/^\p{Lu}/u', $word);
        }
        return $isValid;
    }

    protected static function appendEnd($text)
    {
        return $text.'.';
    }
}


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

import java.util.Date;

/**
 *
 * @author Matthew
 */
public class tbClienteDTO {

    private int idcliente;
    private String nome;
    private String contato;
    private String email;
    private Date dtcriacao;
    private Date dtedicao;
    private String telefonefixo;
    private String telefonecelular;
    private String fax;

    public tbClienteDTO() {
    }

    public tbClienteDTO(int idcliente, String nome, String contato, String email, Date dtcriacao, Date dtedicao, String telefonefixo, String telefonecelular, String fax) {
        this.idcliente = idcliente;
        this.nome = nome;
        this.contato = contato;
        this.email = email;
        this.dtcriacao = dtcriacao;
        this.dtedicao = dtedicao;
        this.telefonefixo = telefonefixo;
        this.telefonecelular = telefonecelular;
        this.fax = fax;
    }

    public int getIdcliente() {
        return idcliente;
    }

    public void setIdcliente(int idcliente) {
        this.idcliente = idcliente;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getContato() {
        return contato;
    }

    public void setContato(String contato) {
        this.contato = contato;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getDtcriacao() {
        return dtcriacao;
    }

    public void setDtcriacao(Date dtcriacao) {
        this.dtcriacao = dtcriacao;
    }

    public Date getDtedicao() {
        return dtedicao;
    }

    public void setDtedicao(Date dtedicao) {
        this.dtedicao = dtedicao;
    }

    public String getTelefonefixo() {
        return telefonefixo;
    }

    public void setTelefonefixo(String telefonefixo) {
        this.telefonefixo = telefonefixo;
    }

    public String getTelefonecelular() {
        return telefonecelular;
    }

    public void setTelefonecelular(String telefonecelular) {
        this.telefonecelular = telefonecelular;
    }

    public String getFax() {
        return fax;
    }

    public void setFax(String fax) {
        this.fax = fax;
    }

}


text:
AddCSLuaFile "cl_init.lua"
AddCSLuaFile "cl_maths.lua"
AddCSLuaFile "cl_panel.lua"
AddCSLuaFile "sh_init.lua"

include "sh_init.lua"

util.AddNetworkString("Keypad_Wire")

net.Receive("Keypad_Wire", function(_, ply)
	local ent = net.ReadEntity()

	if not IsValid(ply) or not IsValid(ent) or not ent:GetClass():lower() == "keypad_wire" then
		return
	end

	if ent:GetStatus() ~= ent.Status_None then
		return
	end

	if ply:EyePos():Distance(ent:GetPos()) >= 120 then
		return
	end

	local command = net.ReadUInt(4)

	if command == ent.Command_Enter then
		local val = tonumber(ent:GetValue() .. net.ReadUInt(8))

		if val and val > 0 and val <= 9999 then
			ent:SetValue(tostring(val))
			ent:EmitSound("buttons/button15.wav")
		end
	elseif command == ent.Command_Abort then
		ent:SetValue("")
	elseif command == ent.Command_Accept then
		if ent:GetValue() == ent:GetPassword() then
			ent:Process(true)
		else
			ent:Process(false)
		end
	end
end)

function ENT:SetValue(val)
	self.Value = val

	if self:GetSecure() then
		self:SetText(string.rep("*", #val))
	else
		self:SetText(val)
	end
end

function ENT:GetValue()
	return self.Value
end

function ENT:Process(granted)
	local length, repeats, delay, initdelay, owner, outputKey

	if(granted) then
		self:SetStatus(self.Status_Granted)

		length = self.KeypadData.LengthGranted
		repeats = math.min(self.KeypadData.RepeatsGranted, 50)
		delay = self.KeypadData.DelayGranted
		initdelay = self.KeypadData.InitDelayGranted
		owner = self.KeypadData.Owner
		outputKey = "Access Granted"
	else
		self:SetStatus(self.Status_Denied)

		length = self.KeypadData.LengthDenied
		repeats = math.min(self.KeypadData.RepeatsDenied, 50)
		delay = self.KeypadData.DelayDenied
		initdelay = self.KeypadData.InitDelayDenied
		owner = self.KeypadData.Owner
		outputKey = "Access Denied"
	end

	timer.Simple(math.max(initdelay + length * (repeats + 1) + delay * repeats + 0.25, 2), function() -- 0.25 after last timer
		if(IsValid(self)) then
			self:Reset()
		end
	end)

	timer.Simple(initdelay, function()
		if(IsValid(self)) then
			for i = 0, repeats do
				timer.Simple(length * i + delay * i, function()
					if(IsValid(self) and IsValid(owner)) then
						Wire_TriggerOutput(self, outputKey, self.KeypadData.OutputOn)
					end
				end)

				timer.Simple(length * (i + 1) + delay * i, function()
					if(IsValid(self) and IsValid(owner)) then
						Wire_TriggerOutput(self, outputKey, self.KeypadData.OutputOff)
					end
				end)
			end
		end
	end)

	if(granted) then
		self:EmitSound("buttons/button9.wav")
	else
		self:EmitSound("buttons/button11.wav")
	end
end

function ENT:SetData(data)
	self.KeypadData = data

	self:SetPassword(data.Password or "1337")
	self:Reset()
end

function ENT:GetData()
	return self.KeypadData
end

function ENT:Reset()
	self:SetValue("")
	self:SetStatus(self.Status_None)
	self:SetSecure(self.KeypadData.Secure)

	Wire_TriggerOutput(self, "Access Granted", self.KeypadData.OutputOff)
	Wire_TriggerOutput(self, "Access Denied", self.KeypadData.OutputOff)
end


text:
package org.yukung.sandbox.dropwizard.sample.auth;

import com.google.common.base.Optional;
import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.basic.BasicCredentials;
import org.yukung.sandbox.dropwizard.sample.core.User;

/**
 * @author yukung
 */
public class SampleAuthenticator implements Authenticator<BasicCredentials, User> {
    @Override
    public Optional<User> authenticate(BasicCredentials basicCredentials) throws AuthenticationException {
        if ("user".equals(basicCredentials.getUsername()) && "pass".equals(basicCredentials.getPassword())) {
            return Optional.of(new User("yukung " + basicCredentials.getUsername()));
        }
        return Optional.absent();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE editor_palette_item PUBLIC "-//NetBeans//Editor Palette Item 1.1//EN"
  "https://netbeans.org/dtds/editor-palette-item-1_1.dtd">

  <editor_palette_item version="1.1">

      <class name = "org.netbeans.modules.multilangsourcefilepalette.python.InputOutput.Input.Input" />

      <icon16 urlvalue="org/netbeans/modules/multilangsourcefilepalette/icons/Item16.png" />
      <icon32 urlvalue="org/netbeans/modules/multilangsourcefilepalette/icons/BR32.png" />

      <inline-description>
          <display-name>Input</display-name>
          <tooltip> <![CDATA[ input(<user-input>)  ]]></tooltip>
      </inline-description>

  </editor_palette_item>


text:
package org.escom.resdes.app;

import java.net.*;
import java.io.*;
import org.escom.resdes.app.util.FTP;
import org.escom.resdes.app.util.FTPImp;
import org.escom.resdes.repository.ProductoRepository;
import org.escom.resdes.repository.ProductoRepositoryImp;

public class Servidor {

    private FTP ftp;

    public Servidor() throws Exception {
        ftp = new FTPImp();
        iniciar(4040);
    }

    public void iniciar(Integer puerto) throws Exception {
        try {
            ServerSocket ss = new ServerSocket(puerto);
            System.out.println("Servicio iniciado, esperando por cliente...");
            for (;;) {
                Socket cl = ss.accept();
                cl.setSoTimeout(3000);

                ObjectInputStream ois = new ObjectInputStream(cl.getInputStream());
                ObjectOutputStream oos = new ObjectOutputStream(cl.getOutputStream());

                enviarImagenes(oos);
                enviarCatalogo(oos);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void enviarProductos() {

    }

    public void enviarImagenes(ObjectOutputStream oos) throws Exception {
        File[] f = null;
        f = ftp.selectFilesWithPath("PATH_SERVER/IMAGES");
        oos.writeObject(f.length);
        for (File f1 : f) {
            ftp.enviarArchivo(f1.getAbsolutePath(), f1.getName(), f1.length(), oos);
        }
    }

    public void enviarCatalogo(ObjectOutputStream oos) throws Exception {
        ProductoRepository pr = new ProductoRepositoryImp();
        pr.saveCatalogoOnServer();

        File[] f = null;
        f = ftp.selectFilesWithPath("PATH_SERVER/CATALOGO");
        oos.writeObject(f.length);
        for (File f1 : f) {
            ftp.enviarArchivo(f1.getAbsolutePath(), f1.getName(), f1.length(), oos);
        }
    }

    public static void main(String[] args) throws Exception {
        new Servidor();
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>Stomp on Web Sockets</title>

<link rel=stylesheet href=screen.css>
<link rel=alternate type=application/atom+xml href=http://github.com/feeds/jmesnil/commits/stomp-websocket/master>

Stomp On Web Sockets

What is Stomp?

Stomp is a simple text-orientated messaging protocol.
  It defines an interoperable wire format
  so that any of the available Stomp Clients can communicate with any
  Stomp Message Broker to provide easy and widespread
  messaging interoperability among languages, platforms and brokers.

What is the Web Sockets API?

Web Sockets are "TCP for the Web".

When Google announced the availability of
Web Sockets in Google Chrome,
it explained the idea behind Web Sockets:

The Web Sockets API enables web applications to handle bidirectional communications
    with server-side process in a straightforward way. Developers have been using XMLHttpRequest
    ("XHR") for such purposes, but XHR makes developing web applications that communicate back
    and forth to the server unnecessarily complex. XHR is basically asynchronous HTTP,
    and because you need to use a tricky technique like long-hanging GET for sending data
    from the server to the browser, simple tasks rapidly become complex. As opposed to XMLHttpRequest,
    Web Sockets provide a real bidirectional communication channel in your browser.
    Once you get a Web Socket connection, you can send data from browser to server by calling
    a send() method, and receive data from server to browser by an onmessage event handler.

In addition to the new Web Sockets API, there is also a new protocol
    (the "web socket protocol") that the browser uses to communicate with servers.
    The protocol is not raw TCP because it needs to provide the browser's "same-origin"
    security model. It's also not HTTP because web socket traffic differers from HTTP's
    request-response model. Web socket communications using the new web socket protocol
    should use less bandwidth because, unlike a series of XHRs and hanging GETs,
    no headers are exchanged once the single connection has been established. To use this new
    API and protocol and take advantage of the simpler programming model and more
    efficient network traffic, you do need a new server implementation to communicate
    with.

The API is part of HTML5 and is currently only supported by Google Chrome and WebKit nightly builds and other modern Web browsers
  (Firefox, Safari) have ongoing work to support it too.

Server Requirements

This library is not a pure Stomp client. It is aimed to run on the Web Sockets protocol which
  is not TCP. Basically, the Web Sockets protocol requires a handshake between the browser's
  client and the server to ensure the browser's "same-origin" security model remains in effect.

This means that this library can not connect to regular Stomp brokers since they would not understand
  the handshake initiated by the Web Socket which is not part of the Stomp protocol and would
  likely reject the connection.

There are ongoing works to add Web Socket support to Stomp brokers such as HornetQ and
  ActiveMQ so that they will accept Stomp connections over
  the Web Sockets protocol.

HornetQ

HornetQ is the Open Source messaging system developed
  by Red Hat and JBoss. Support for Stomp on Web Sockets is available for HornetQ subversion trunk.

To start HornetQ with support for Stomp on Web Sockets, run the following steps:

  <samp>$ </samp>svn co http://anonsvn.jboss.org/repos/hornetq/trunk/ hornetq
  <samp>...</samp>
  <samp>$ </samp>cd hornetq
  <samp>$ </samp>./build.sh distro
  <samp>...</samp>
  <samp>$ </samp>cd build/hornetq-2.1.0.BETA3/bin
  <samp>$ </samp>./run.sh ../examples/jms/stomp-websockets/server0
  <samp>...
  Started Netty Acceptor version 3.2.0.BETA1-r2215 localhost:61614 for STOMP_WS protocol
  HornetQ Server version 2.0.0.GA (Hornet Queen, 113) started</samp>

HornetQ is now started and listens to Stomp over Web Sockets on the port 61614.

It accepts Web Sockets connections from the URL ws://localhost:61614/stomp

To configure and run HornetQ broker with Stomp on Web Sockets enabled, follow the
  instructions.

ActiveMQ

ActiveMQ is the Open Source messaging system developed by Apache.
  Starting with 5.4 snapshots, ActiveMQ supports Stomp on Web Sockets.

To configure and run ActiveMQ broker with Stomp on Web Sockets enabled, follow the
  instructions.

Stomp API

Stomp Frame

Stomp on Web Socket provides a straightforward mapping from a Stomp frame to a JavaScript
  object.

Frame Object

PropertyTypeNotes

commandStringname of the frame ("CONNECT", "SEND", etc.)

headersJavaScript object

bodyString

The command and headers properties will always be defined
  but the headers can be empty if the frame has no headers.
  The body can be null if the frame does not have a body.

Create a Stomp client

Stomp JavaScript clients will communicate to a Stomp server using a ws:// URL.

To create a Stomp client JavaScript object, you need to call Stomp.client(url)
  with the URL corresponding to the server's Web Socket endpoint:

  var url = "ws://localhost:61614/stomp";
  var client = Stomp.client(url);

Connection to the server

Once a Stomp client is created, it must call its connect() method to effectively
  connect and authenticate to the Stomp server. The method takes two mandatory arguments,
  login and passcode corresponding to the user credentials.

Behind the scene, the client will open a connection using a Web Socket and send
  a CONNECT frame.

The connection is done asynchronously: you have no guarantee to be effectively connected when
  the call to connect returns. To be notified of the connection, you can pass a
  connect_callback function to the connect() method:

  client.connect(login, passcode, connect_callback);

  connect_callback = function() {
    // called back after the client is connected and authenticated to the Stomp server
  };

But what happens if the connection fails? the connect() method accepts an
  optional error_callback argument which will be called if the client is not able
  to connect to the server.
  The callback will be called with a single argument, an error object corresponding to Stomp
  ERROR frame:

  client.connect(login, passcode, connect_callback, error_callback);

  error_callback = function(error) {
    // display the error's message header:
    alert(error.headers.message);
  };

To disconnect a client from the server, you can call its disconnect() method.
  The disconnection is asynchronous: to be notified when the disconnection is effective,
  the disconnect method takes an optional callback argument.

  client.disconnect(function() {
    alert("See you next time!");
  };

When a client is disconnected, it can no longer send or receive messages.

Send messages

When the client is connected to the server, it can send Stomp messages using
  the send() method. The method takes a mandatory destination
  argument corresponding to the Stomp destination. It also takes two optional
  arguments: headers, a JavaScript object containing additional
  message headers and body, a String object.

  client.send("/queue/test", {priority: 9}, "Hello, Stomp");

The client will send a Stomp
  SEND frame to /queue/test destination
  with a header priority set to 9 and a body Hello, Stomp.

If you want to send a message with a body, you must also pass the headers
    argument. If you have no headers to pass, use an empty JavaScript literal {}:

  client.send(destination, {}, body);

Subscribe and receive messages

To receive messages in the browser, the Stomp client must first subscribe to a destination.

You can use the subscribe() method to subscribe to a destination. The method takes 2 mandatory
  arguments: destination, a String corresponding to the destination and
  callback, a function with one message argument.

  id = client.subscribe("/queue/test", callback);

The subscribe() methods returns an id that correspond to the client subscription. You can use this
  subscription ID later on to unsubscribe the client from this destination.

The client will send a Stomp
  SUBSCRIBE frame to the server
  and register the callback. Every time the server
  send a message to the client, the client will in turn call the callback with a Stomp Frame object
  corresponding to the message:

  callback = function(message) {
    // called when the client receives a Stomp message from the server
    if (message.body) {
      alert("got message with body " + message.body)
    } else {
      alert("got empty message");
    }
  });

The subscribe() method takes an optional headers parameters to specify
  additional headers when subscribing to a destination:

  var headers = {ack: 'client', 'selector': "location = 'Europe'"};
  client.subscribe("/queue/test", message_callback, headers);

The client specifies that it will handle the message acknowledgement and is interested to receive
  only messages matching the selector location = 'Europe'.

If you want to subscribe the client to multiple destinations, you can use the same callback to receive all
    the messages:

  onmessage = function(message) {
    // called every time the client receives a message
  }
  client.subscribe("queue/test", onmessage);
  client.subscribe("queue/another", onmessage);

To stop receiving messages, the client can use its unsubscribe() method.
  The method takes a id argument corresponding to the subscription ID to unsubscribe from.

  id = client.subscribe(...);

  ...

  client.unsubscribe(id);

 The method also takes an optional headers argument if the client needs to pass additional headers.

JSON support

The body of a Stomp message must be a String. If you want to send and receive
  JSON objects, you can use JSON.stringify() and JSON.parse() to transform the JSON
  object to a String and vice versa.

  var quote = {symbol: 'APPL', value: 195.46};
  client.send("/topic/stocks", {}, JSON.stringify(quote));

  client.subcribe("/topic/stocks", function(message) {
    var quote = JSON.parse(message.body);
    alert(quote.symbol + " is at " + quote.value);
  };

Acknowledgment

By default, Stomp messages will be automatically acknowledged by the server before the message
  is delivered to the client.

The client can chose instead to handle message acknowledgement by subscribing to a destination and
  specify a ack header set to 'client'.

In that case, the client must use the ack() method to inform the server that it has
  acknowledge the message. The methods takes a mandatory message_id corresponding to the message
  to acknowledge.

  client.subscribe("/queue/test", {ack: 'client'}, function(message) {
    // do something with the message
    ...
    // and acknowledge it
    var message_id = message.headers['message-id']
    client.ack(message_id);
  });

Transactions

Messages can be sent and acknowledged in a transaction.

A transaction is started by the client using its begin() method
  which takes a mandatory transaction, a String which uniquely identifies the
  transaction.
  The client can then send and acknowledge messages in the transasction by specifying a
  transaction set with the transaction name.

A transaction is completed by the client by calling its commit() method.
  Alternatively, the client can abort the transaction by calling its abort method.

  var txid = "unique_transaction_identifier";
  // start the transaction
  client.begin(txid);
  // send the message in a transaction
  client.send("/queue/test", {transaction: txid}, "message in a transaction");
  // commit the transaction to effectively send the message
  client.commit(txid);

If you forget to add the transaction header when calling send()
    the message will not be part of the transaction and will be sent directly without
    waiting for the completion of the transaction.

  var txid = "unique_transaction_identifier";
  // start the transaction
  client.begin(txid);
  // oops! send the message outside the transaction
  client.send("/queue/test", {}, "I thought I was in a transaction!");
  client.abort(txid); // Too late! the message has been sent

Debug

There are few tests in the code and it is helpful to see what is sent and received
  from the library to debug application.

The client can set its debug property to a function with takes a String argument
  to see all the debug statements of the library:

  client.debug = function(str) {
    // append the debug log to a #debug div somewhere in the page using JQuery:
    $("#debug").append(str + "\n");
  };

Example

The source code contains a chat example in examples/chat/index.html

You need to start a Stomp server with support for Web Socket (using for example HornetQ).

Click on the Connect button to connect to the server and subscribe to the /queue/test/ queue.

You can then type messages in the form at the bottom of the page to send Stomp messages to the queue.
  Messages received by the client will be displayed at the top of the page.

You can also send regular Stomp messages and see them displayed in the browser. For
  example using directly telnet on Stomp default port:

  <samp>$ </samp>telnet localhost 61613
  CONNECT
  login:guest
  passcode:guest

  ^@

  <samp>CONNECTED
  session:1092296064
  </samp>

^@ is a null (control-@ in ASCII) byte.

  SEND
  destination:/queue/test

  Hello from TCP!
  ^@

You should now have received this message in your browser.

Contribute

 The source code is hosted on GitHub:

  git clone git://github.com/jmesnil/stomp-websocket.git

© 2010 Jeff Mesnil


text:
require 'rubygems'
require 'bundler/setup'

require 'aperture_ar'


text:
from simpleparse.objectgenerator import Prebuilt
from simpleparse.stt.TextTools import Call, Skip
from .util import eat_indent, count_indent
from .Token import Token

class Dedent(Token):

    def __call__(self, buffer, start, end):
        if start > end:
            return start + 1
        after_indent = eat_indent(buffer, start, end)
        self.processor.indent = count_indent(buffer, after_indent)
        return after_indent + 1  # +1/-1 hack

    def table(self):
        table = (None, Call, self), (None, Skip, -1)  # +1/-1 hack
        return Prebuilt(value=table, report=False)


text:
require 'spree_core'

module Spree
  module AddressBook
    class Engine < Rails::Engine
      engine_name 'spree_address_book'

      initializer "spree.advanced_cart.environment", :before => :load_config_initializers do |app|
        Spree::AddressBook::Config = Spree::AddressBookConfiguration.new
      end

      config.autoload_paths += %W(#{config.root}/lib)

      def self.activate
        Dir.glob(File.join(File.dirname(__FILE__), "../app/**/spree/*_decorator*.rb")) do |c|
          Rails.application.config.cache_classes ? require(c) : load(c)
        end
        Spree::Ability.register_ability(Spree::AddressAbility)
      end

      config.to_prepare &method(:activate).to_proc
    end
  end
end


text:
package com.asakusafw.runtime.io.json.value;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.IOException;

import org.junit.Test;

import com.asakusafw.runtime.io.json.PropertyAdapter;
import com.asakusafw.runtime.value.Date;
import com.asakusafw.runtime.value.DateOption;

/**
 * Test for {@link DateOptionPropertyAdapter}.
 */
public class DateOptionPropertyAdapterTest {

    final DateOptionPropertyAdapter.Builder builder = DateOptionPropertyAdapter.builder();

    /**
     * read.
     * @throws Exception if failed
     */
    @Test
    public void read() throws Exception {
        DateOptionPropertyAdapter adapter = builder.build();
        DateOption option = new DateOption();
        adapter.read(new MockValue("2018-12-31"), option);
        assertThat(option, is(new DateOption(new Date(2018, 12, 31))));
    }

    /**
     * read w/ invalid input.
     * @throws Exception if failed
     */
    @Test(expected = RuntimeException.class)
    public void read_invalid() throws Exception {
        DateOptionPropertyAdapter adapter = builder.build();
        DateOption option = new DateOption();
        adapter.read(new MockValue("OUT A TIME"), option);
    }

    /**
     * write.
     * @throws Exception if failed
     */
    @Test
    public void write() throws Exception {
        DateOptionPropertyAdapter adapter = builder.build();
        MockValue writer = new MockValue();

        adapter.write(new DateOption(new Date(2019, 1, 1)), writer);
        assertThat(writer.get(), is("2019-01-01"));
    }

    /**
     * parse w/ default format.
     * @throws Exception if failed
     */
    @Test
    public void format() throws Exception {
        DateOptionPropertyAdapter adapter = builder.build();
        equivalent(adapter, "2016-12-31", new DateOption(new Date(2016, 12, 31)));
        equivalent(adapter, "2017-01-01", new DateOption(new Date(2017,  1,  1)));
        equivalent(adapter, "2017-01-02", new DateOption(new Date(2017,  1,  2)));
    }

    /**
     * parse w/ custom format - standard.
     * @throws Exception if failed
     */
    @Test
    public void format_standard() throws Exception {
        DateOptionPropertyAdapter adapter = builder
                .withDateFormat("yyyy'x'MM'x'dd")
                .build();
        equivalent(adapter, "2016x12x31", new DateOption(new Date(2016, 12, 31)));
        equivalent(adapter, "2017x01x01", new DateOption(new Date(2017,  1,  1)));
        equivalent(adapter, "2017x01x02", new DateOption(new Date(2017,  1,  2)));
    }

    /**
     * parse w/ custom format - direct.
     * @throws Exception if failed
     */
    @Test
    public void format_direct() throws Exception {
        DateOptionPropertyAdapter adapter = builder
                .withDateFormat("yyyyMMdd")
                .build();
        equivalent(adapter, "20161231", new DateOption(new Date(2016, 12, 31)));
        equivalent(adapter, "20170101", new DateOption(new Date(2017,  1,  1)));
        equivalent(adapter, "20170102", new DateOption(new Date(2017,  1,  2)));
    }

    /**
     * parse w/ custom format - default.
     * @throws Exception if failed
     */
    @Test
    public void format_custom() throws Exception {
        DateOptionPropertyAdapter adapter = builder
                .withDateFormat("yyyy -- MM -- dd")
                .build();
        equivalent(adapter, "2016 -- 12 -- 31", new DateOption(new Date(2016, 12, 31)));
        equivalent(adapter, "2017 -- 01 -- 01", new DateOption(new Date(2017,  1,  1)));
        equivalent(adapter, "2017 -- 01 -- 02", new DateOption(new Date(2017,  1,  2)));
    }

    <T> void equivalent(PropertyAdapter<T> adapter, Object value, T property) throws IOException {
        MockValue x = new MockValue(value);
        adapter.read(x, property);
        x.set("__INVALID__");
        adapter.write(property, x);
        assertThat(x.get(), is(value));
    }
}


text:
#include "modules/drivers/canbus/can_client/socket/socket_can_client_raw.h"

#include <vector>

#include "gtest/gtest.h"

#include "modules/drivers/canbus/proto/can_card_parameter.pb.h"

namespace apollo {
namespace drivers {
namespace canbus {
namespace can {

using apollo::common::ErrorCode;

TEST(SocketCanClientRawTest, simple_test) {
  CANCardParameter param;
  param.set_brand(CANCardParameter::SOCKET_CAN_RAW);
  param.set_channel_id(CANCardParameter::CHANNEL_ID_ZERO);

  SocketCanClientRaw socket_can_client;
  EXPECT_TRUE(socket_can_client.Init(param));
  EXPECT_EQ(socket_can_client.Start(), ErrorCode::CAN_CLIENT_ERROR_BASE);
  std::vector<CanFrame> frames;
  int32_t num = 0;
  EXPECT_EQ(socket_can_client.Send(frames, &num),
            ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED);
  EXPECT_EQ(socket_can_client.Receive(&frames, &num),
            ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED);
  CanFrame can_frame;
  frames.push_back(can_frame);
  EXPECT_EQ(socket_can_client.SendSingleFrame(frames),
            ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED);
  socket_can_client.Stop();
}

}  // namespace can
}  // namespace canbus
}  // namespace drivers
}  // namespace apollo


text:
package org.codehaus.groovy.reflection.stdclasses;

import org.codehaus.groovy.reflection.ClassInfo;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * @author Alex.Tkachman
 */
public class FloatCachedClass extends NumberCachedClass {
    private boolean allowNull;

    public FloatCachedClass(Class klazz, ClassInfo classInfo, boolean allowNull) {
        super(klazz, classInfo);
        this.allowNull = allowNull;
    }

    public Object coerceArgument(Object argument) {
        if (argument instanceof Float) {
            return argument;
        }

        if (argument instanceof Number) {
            Float res = ((Number) argument).floatValue();
            if (argument instanceof BigDecimal && res.isInfinite()) {
                throw new IllegalArgumentException(Float.class + " out of range while converting from BigDecimal");
            }
            return res;
        }
        return argument;
    }

    public boolean isDirectlyAssignable(Object argument) {
        return (allowNull && argument == null) || argument instanceof Float;
    }

    public boolean isAssignableFrom(Class classToTransformFrom) {
        return (allowNull && classToTransformFrom == null)
                || classToTransformFrom == Float.class
                || classToTransformFrom == Integer.class
                || classToTransformFrom == Long.class
                || classToTransformFrom == Short.class
                || classToTransformFrom == Byte.class
                || classToTransformFrom == Float.TYPE
                || classToTransformFrom == Integer.TYPE
                || classToTransformFrom == Long.TYPE
                || classToTransformFrom == Short.TYPE
                || classToTransformFrom == Byte.TYPE
                || classToTransformFrom == BigDecimal.class
                || classToTransformFrom == BigInteger.class;
    }
}


text:
package org.apache.geode.internal.cache.map;

import java.util.List;

import org.apache.logging.log4j.Logger;

import org.apache.geode.cache.Operation;
import org.apache.geode.cache.TransactionId;
import org.apache.geode.internal.cache.EntryEventImpl;
import org.apache.geode.internal.cache.EnumListenerEvent;
import org.apache.geode.internal.cache.InternalRegion;
import org.apache.geode.internal.cache.RegionClearedException;
import org.apache.geode.internal.cache.RegionEntry;
import org.apache.geode.internal.cache.TXEntryState;
import org.apache.geode.internal.cache.TXRmtEvent;
import org.apache.geode.internal.cache.Token;
import org.apache.geode.internal.offheap.annotations.Released;
import org.apache.geode.internal.sequencelog.EntryLogger;
import org.apache.geode.logging.internal.log4j.api.LogService;

/**
 * Does a put for a transaction that is being committed.
 */
public class RegionMapCommitPut extends AbstractRegionMapPut {
  private static final Logger logger = LogService.getLogger();

  private final boolean onlyExisting;
  private final boolean didDestroy;
  private final TXRmtEvent txEvent;
  private final List<EntryEventImpl> pendingCallbacks;
  private final TXEntryState txEntryState;
  private final boolean remoteOrigin;
  private final boolean invokeCallbacks;

  private boolean callbackEventInPending;
  private Operation putOp;

  public RegionMapCommitPut(FocusedRegionMap focusedRegionMap, InternalRegion owner,
      @Released EntryEventImpl callbackEvent, Operation putOp, boolean didDestroy,
      TransactionId txId, TXRmtEvent txEvent, List<EntryEventImpl> pendingCallbacks,
      TXEntryState txEntryState) {
    super(focusedRegionMap, owner, callbackEvent);
    this.putOp = putOp;
    this.didDestroy = didDestroy;
    this.txEvent = txEvent;
    this.pendingCallbacks = pendingCallbacks;
    this.txEntryState = txEntryState;
    this.remoteOrigin = !txId.getMemberId().equals(owner.getMyId());
    this.invokeCallbacks = shouldInvokeCallbacks();
    final boolean isTXHost = txEntryState != null;
    // If the transaction originated on another member and we do not host the transaction entry
    // and are not a replicate or partitioned (i.e. !isAllEvents)
    // then only apply the update to existing entries.
    // If the transaction originated on another member and we do not host the transaction entry
    // and we are a replicate or partitioned
    // then only apply the update to existing entries when the operation is an update and we
    // are initialized.
    // Otherwise use the standard create/update logic.
    this.onlyExisting = remoteOrigin && !isTXHost
        && (!owner.isAllEvents() || (!putOp.isCreate() && isOwnerInitialized()));
  }

  boolean isRemoteOrigin() {
    return remoteOrigin;
  }

  boolean isInvokeCallbacks() {
    return invokeCallbacks;
  }

  private Operation getPutOp() {
    return putOp;
  }

  private boolean isPutOpCreate() {
    return getPutOp().isCreate();
  }

  private boolean shouldInvokeCallbacks() {
    InternalRegion owner = getOwner();
    boolean isPartitioned = owner.isUsedForPartitionedRegionBucket();
    if (isPartitioned) {
      owner = owner.getPartitionedRegion();
    }
    return (isPartitioned || isOwnerInitialized()) && (owner.shouldDispatchListenerEvent()
        || owner.shouldNotifyBridgeClients() || owner.getConcurrencyChecksEnabled());
  }

  private void setCallbackEventInPending(boolean v) {
    this.callbackEventInPending = v;
  }

  boolean isCallbackEventInPending() {
    return this.callbackEventInPending;
  }

  private void makePutOpCreate() {
    putOp = putOp.getCorrespondingCreateOp();
  }

  private void makePutOpUpdate() {
    putOp = putOp.getCorrespondingUpdateOp();
  }

  @Override
  protected boolean isOnlyExisting() {
    return this.onlyExisting;
  }

  @Override
  protected boolean entryExists(RegionEntry regionEntry) {
    return regionEntry != null && !regionEntry.isDestroyedOrRemoved();
  }

  @Override
  protected void serializeNewValueIfNeeded() {
    // nothing needed
  }

  @Override
  protected void setOldValueForDelta() {
    // nothing needed
  }

  @Override
  protected void setOldValueInEvent() {
    if (isCreate()) {
      makePutOpCreate();
    } else {
      if (!getRegionEntry().isDestroyedOrRemoved()) {
        makePutOpUpdate();
      } else {
        makePutOpCreate();
      }
    }
    if (isPutOpCreate()) {
      getEvent().makeCreate();
      getEvent().setOldValue(null);
    } else {
      getEvent().makeUpdate();
      Object oldValue = getRegionEntry().getValueInVM(getOwner());
      getEvent().setOldValue(oldValue);
    }
  }

  @Override
  protected void unsetOldValueForDelta() {
    // nothing needed
  }

  @Override
  protected boolean checkPreconditions() {
    if (isOnlyExisting() && isPutOpCreate()) {
      return false;
    }
    return true;
  }

  @Override
  protected void invokeCacheWriter() {
    // nothing needed
  }

  @Override
  protected void createOrUpdateEntry() {
    final RegionEntry regionEntry = getRegionEntry();
    final EntryEventImpl callbackEvent = getEvent();
    final InternalRegion owner = getOwner();
    final FocusedRegionMap regionMap = getRegionMap();
    final Object key = callbackEvent.getKey();
    final Object newValue = computeNewValue(callbackEvent);

    final int oldSize = isPutOpCreate() ? 0 : owner.calculateRegionEntryValueSize(regionEntry);
    callbackEvent.setRegionEntry(regionEntry);
    regionMap.txRemoveOldIndexEntry(getPutOp(), regionEntry);
    setLastModifiedTime(owner.cacheTimeMillis());
    if (didDestroy) {
      regionEntry.txDidDestroy(getLastModifiedTime());
    }
    if (txEvent != null) {
      txEvent.addPut(getPutOp(), owner, regionEntry, key, newValue,
          callbackEvent.getCallbackArgument());
    }
    regionEntry.setValueResultOfSearch(getPutOp().isNetSearch());
    try {
      regionMap.processAndGenerateTXVersionTag(callbackEvent, regionEntry, txEntryState);
      setNewValueOnRegionEntry(newValue);
      int newSize = owner.calculateRegionEntryValueSize(regionEntry);
      if (isPutOpCreate()) {
        owner.updateSizeOnCreate(key, newSize);
      } else {
        owner.updateSizeOnPut(key, oldSize, newSize);
      }
    } catch (RegionClearedException rce) {
      setClearOccurred(true);
    }
    EntryLogger.logTXPut(owner, key, newValue);
  }

  private void setNewValueOnRegionEntry(final Object newValue) throws RegionClearedException {
    final RegionEntry regionEntry = getRegionEntry();
    final InternalRegion owner = getOwner();
    final boolean wasTombstone = regionEntry.isTombstone();
    final Object preparedValue =
        regionEntry.prepareValueForCache(owner, newValue, getEvent(), !isPutOpCreate());
    regionEntry.setValue(owner, preparedValue);
    if (wasTombstone) {
      owner.unscheduleTombstone(regionEntry);
    }
  }

  private static Object computeNewValue(EntryEventImpl callbackEvent) {
    Object newValue = callbackEvent.getRawNewValueAsHeapObject();
    if (newValue == null) {
      if (callbackEvent.isLocalInvalid()) {
        newValue = Token.LOCAL_INVALID;
      } else {
        newValue = Token.INVALID;
      }
    }
    return newValue;
  }

  @Override
  protected boolean shouldCreatedEntryBeRemoved() {
    return !isCompleted();
  }

  @Override
  protected void doBeforeCompletionActions() {
    final RegionEntry regionEntry = getRegionEntry();
    final EntryEventImpl callbackEvent = getEvent();
    final InternalRegion owner = getOwner();
    final FocusedRegionMap regionMap = getRegionMap();
    final Object key = callbackEvent.getKey();

    regionEntry.updateStatsForPut(getLastModifiedTime(), getLastModifiedTime());
    owner.txApplyPutPart2(regionEntry, key, getLastModifiedTime(), isPutOpCreate(), didDestroy,
        isClearOccurred());
    if (isInvokeCallbacks()) {
      callbackEvent.changeRegionToBucketsOwner();
      callbackEvent.setOriginRemote(isRemoteOrigin());
      pendingCallbacks.add(callbackEvent);
      setCallbackEventInPending(true);
    }
    if (!isClearOccurred()) {
      if (isCreate()) {
        regionMap.lruEntryCreate(regionEntry);
        regionMap.incEntryCount(1);
      } else {
        regionMap.lruEntryUpdate(regionEntry);
      }
    }
  }

  @Override
  protected void doAfterCompletionActions(boolean disabledEviction) {
    if (isOnlyExisting() && !isCompleted()) {
      if (didDestroy) {
        getOwner().txApplyPutHandleDidDestroy(getEvent().getKey());
      }
      if (isInvokeCallbacks()) {
        getEvent().makeUpdate();
        getOwner().invokeTXCallbacks(EnumListenerEvent.AFTER_UPDATE, getEvent(), false);
      }
    }
    if (getOwner().getConcurrencyChecksEnabled() && txEntryState != null) {
      txEntryState.setVersionTag(getEvent().getVersionTag());
    }
    if (!isCallbackEventInPending()) {
      getEvent().release();
    }
  }

}


text:
/**
 * Created by i048697 on 1/4/16.
 */
sap.ui.define(["jquery.sap.global", "sap/ui/core/Control", "sap/ui/core/EnabledPropagator"],
	function(jQuery, Control, EnabledPropagator) {
		"use strict";

		var megaMenuItem = Control.extend("HorizontalMenuPlugin.item.control", {

			metadata: { // the megaMenuItem API
				properties: {
					name: "string", // setter and getter are created behind the scenes,
					// including data binding and type validation
					index: "string",
					level: {
						type: "number",
						defaultValue: 0
					},
					subitems: {
						type: "any[]",
						defaultValue: []
					},
					isOverflow: {
						type: "boolean",
						defaultValue: false
					},
					parentItem: "any",
					megamenu: "any",
					title: "string",
					target: "any"
				},

				events: {
					itemClicked: {}
				},

				aggregations: {
					subitems: {
						type: "HorizontalMenuPlugin.item.control",
						multiple: true,
						visibility: "public"
					}
				}

			},
			_findMenuItemBySemanticObject: function(sObject) {
				var target = this.getTarget();
				var hash = target.semanticObject + "-" + target.action;
				if (sObject === hash) {
					return this;
				}
				var items = this.getAggregation("subitems");
				var menuItem;
				if (items && items.length) {
					$.each(items, function(i, v) {
						menuItem = v._findMenuItemBySemanticObject(sObject);
						if (menuItem) {
							return false;
						}
					});
				}
				return menuItem;

			},
			addSubItems: function(subItems) {
				this.setSubitems(subItems);
				var items = this.getSubitems();
				var level = this.getLevel();
				var oControl = this;
				$.each(items, function(i, v) {
					var menuItem = new HorizontalMenuPlugin.item.control({
						title: v.title,
						index: i,
						target: v.target,
						level: level + 1,
						parentItem: oControl,
						megamenu: oControl.getMegamenu(),
						itemClicked: function(evt) {
							if (evt.oSource === menuItem) {
								oControl.getMegamenu()._navigate(v.target);
								//	target: v.target,
								//	menuItem: evt.oSource

								evt.bCancelBubble = true;
								evt.bPreventDefault = true;
								return false;
							}

						}
					});
					menuItem.addSubItems(items[i].entities);
					oControl.addAggregation("subitems", menuItem, true);
				});

			},

			onAfterRendering: function() {

				var self = this;
				this.$().blur(function(evt) {
					if (!evt.relatedTarget) {
						self.closeAll();
					} else if ($(evt.relatedTarget).closest(".menuItem.open").length === 0) {
						$(this).removeClass("open");
					}
					delete self._target;

				});
			},

			renderer: function(oRm, oControl) { // the part creating the HTML

				oRm.addClass("sapMFocusable");
				oRm.addClass("menuItem");
				if (oControl.getLevel() === 0) {
					oRm.addClass("sapThemeBarText");

				} else {
					oRm.addClass("sapThemeLightText");
					oRm.addClass("sapMListBGSolid");
					oRm.addClass("sapMLIBHoverable");
					oRm.addClass("sapMLIB");

				}
				oRm.addClass("sapMLIBFocusable");
				var subItemsAggregation = oControl.getAggregation("subitems");
				if (subItemsAggregation && subItemsAggregation.length > 0) {

					oRm.addClass("parentMenu");
				}
				var i = oControl.getIndex();
				var isOverflow = oControl.getIsOverflow();
				var style = "";
				if (isOverflow) {
					oRm.addStyle("visibility", "hidden");
				}

				oRm.write("
" + oControl.getTitle() + "");

				if (subItemsAggregation) {
					oControl._drawSubItems(oRm, subItemsAggregation, oControl);
				}
				oRm.write("
");

			},
			_drawSubItems: function(oRm, subItemsAggregation) {
				oRm.write("
");
				oRm.write("
");
				for (var i = 0; i < subItemsAggregation.length; i++) {
					oRm.renderControl(subItemsAggregation[i]);
				}
				oRm.write("
");
				oRm.write("
");
			}

		});
		EnabledPropagator.call(megaMenuItem.prototype);
		megaMenuItem.prototype.onkeydown = function(oEvent) {

			if (oEvent.which === jQuery.sap.KeyCodes.SPACE || oEvent.which === jQuery.sap.KeyCodes.ENTER) {

				this._target = oEvent.target;
			}
		};

		/**
		 * Handle the key up event for SPACE and ENTER.
		 *
		 * @param {jQuery.Event} oEvent - the keyboard event.
		 * @private
		 */
		megaMenuItem.prototype.onkeyup = function(oEvent) {

			// if keydown isn't caught by button, ignore the keyup.
			if (!this._target) {
				return;
			}

			this._target = null;

			if (oEvent.which === jQuery.sap.KeyCodes.SPACE || oEvent.which === jQuery.sap.KeyCodes.ENTER) {
				// mark the event for components that needs to know if the event was handled by the megaMenuItem
				this.fireItemClicked({
					menuItem: this,
					target: this.getTarget()
				});

			}

			oEvent.stopPropagation();
			return false;
		};

		megaMenuItem.prototype.ontouchstart = function(oEvent) {

			// change the source only when the first finger is on the control, the
			// following fingers doesn't affect
			if (oEvent.targetTouches.length === 1) {
				// set target which started the event
				this._target = oEvent.target;
			}
		};
		megaMenuItem.prototype.onmouseout = function(oEvent) {
			if ($(oEvent.relatedTarget).closest(".menuItem.open").length === 0) {
				this.closeAll();
			} else {
				var $outItem = $(oEvent.currentTarget);
				this.closeAllSiblings($outItem);

				oEvent.stopPropagation();
				return false;

			}
		};
		megaMenuItem.prototype.onmouseover = function(oEvent) {
			var $overMenuItem = $(oEvent.currentTarget);

			if (this.getSubitems().length > 0 && !$overMenuItem.hasClass("open")) {
				this.openSubMenu($overMenuItem);
				this.closeAllSiblings($overMenuItem);

				oEvent.stopPropagation();
				return false;
			}

		};

		megaMenuItem.prototype.openSubMenu = function($menuItem) {
			$menuItem.addClass("open");
			if (this.getLevel() === 1) {
				var menuItemAverageWidth = $menuItem.width();
				var numChildOfSubMenus = $menuItem.find(".sapUiMnu").length;
				var totalWidth = menuItemAverageWidth * numChildOfSubMenus;
				var subMenu = $menuItem.find(">.sapUiMnu:first");
				$menuItem.removeClass("rightMenu");
				if (subMenu && (subMenu.offset().left + totalWidth) > $(window).width() && (subMenu.offset().left - totalWidth) > 0) {
					$menuItem.addClass("rightMenu");
				}
			}

		};
		megaMenuItem.prototype.closeAllSiblings = function($menuItem) {

			var $siblings = $menuItem.siblings(".menuItem.open");
			$siblings.removeClass("open");
			$siblings.find(".menuItem.open").removeClass("open");
		};

		megaMenuItem.prototype.closeAll = function() {
			var $openMenuItem = this.getMegamenu().$().find(".menuItem.open");
			$openMenuItem.removeClass("open");
			$openMenuItem.blur();

		};

		megaMenuItem.prototype.hideIfOverFlow = function(containerWidth) {
			var $item = this.$();
			var width = $item.outerWidth(true);
			var offset = $item.position();
			if (offset.left + width > containerWidth) {
				this.setIsOverflow(true);
			} else {
				this.setIsOverflow(false);
			}
		};
		megaMenuItem.prototype.ontap = function(oEvent) {

			// if target is empty set target (specially for selenium test)
			if (!this._target) {
				this._target = oEvent.target;
			}

			// check if target which started the event is the same
			if ((!!this._target) && (this._target === oEvent.target)) {
				var $tapMenuItem = $(oEvent.currentTarget);

				// note: on mobile, the press event should be fired after the focus is on the megaMenuItem
				if (oEvent.originalEvent && oEvent.originalEvent.type === "touchend") {

					//first tap on touch device
					this.focus();
					if (this.getSubitems().length > 0 && !$tapMenuItem.hasClass("open")) {
						this.closeAllSiblings($tapMenuItem);
						oEvent.stopPropagation();
						return false;
					}

				}

				this.closeAll();

				this.fireItemClicked({
					menuItem: this,
					target: this.getTarget()
				});
			}

			// reset target which started the event
			delete this._target;

			oEvent.stopPropagation();
			return false;

		};
	});