text:
#include "Table.h"

#include "MMU.h"
#include <sim/log2.h>

namespace Simulator {
namespace drisc {
namespace mmu {

Table::Table(const std::string& name, Object& parent):
Object(name, parent),
m_offsetWidth(GetConf("OffsetSize", size_t)),
m_vWidth(getMMU().vAW() - m_offsetWidth),
m_pWidth(getMMU().pAW() - m_offsetWidth),
m_numLines(GetConf("NumberOfLines", size_t)),
m_evictionStrategy(getEvictionStrategy(GetConf("EvictionStrategy", std::string))),
m_lines(m_numLines,	Line(getMMU().contextAW(), m_vWidth, m_pWidth)),
m_head(NULL),
m_tail(NULL),
m_indexWidth(ilog2(m_numLines))
{
	if(m_numLines == 0){
		throw exceptf<std::invalid_argument>("A table cannot be initialised with 0 lines");
	}
	initStrategy();
}

AddrWidth Table::getVAddrWidth() const {return getMMU().vAW() - m_offsetWidth;} //MLDTODO Inline? Smth else?
AddrWidth Table::getPAddrWidth() const {return getMMU().pAW() - m_offsetWidth;}

void Table::initStrategy(){
	if (m_evictionStrategy == EvictionStrategy::LRU) {
		// Initially link all nodes in ascending order.
		m_head = &(m_lines[0]);
		m_tail = &(m_lines[m_numLines-1]);
		m_head->previous = m_tail->next = NULL;

		for(unsigned int i=1; i<m_numLines; i++){
			m_lines[i-1].next = &(m_lines[i]);
			m_lines[i].previous = &(m_lines[i-1]);
		}
	}else{
		if (((m_numLines & (m_numLines - 1)) != 0)) {
			throw exceptf<std::invalid_argument>("This eviction strategy requires the number of lines to be a factor of 2");
		}
	}
}

Line *Table::lookup(RAddr contextId, RAddr vAddr, LineTag type){
	contextId.strictExpect(getMMU().contextAW());
	vAddr.strictExpect(m_vWidth);

	Line* line = find(contextId, vAddr, type);
	if(line != NULL) { setPrioHigh(*line); }

	return line;
}

Line *Table::find(RAddr contextId, RAddr vAddr, LineTag type){
	contextId.strictExpect(getMMU().contextAW());
	vAddr.strictExpect(m_vWidth);

	auto lambda =
			[&contextId, &vAddr, &type]
			(Line &line)
			{return line.is(&contextId, &vAddr, type);};
	return find(lambda);
}

Line *Table::find(LineTag type)
{
	auto lambda = [type](Line &line) {return line.is(type);};
	return find(lambda);
}

Line *Table::find(std::function<bool (Line&)> const &lambda)
{
	auto res = std::find_if(m_lines.begin(), m_lines.end(), lambda);
	return (res == m_lines.end())? NULL : &(*res);
}

bool Table::getPending(RAddr tableLineId, RAddr &contextId, RAddr &vAddr, RAddr &d$LineId){
	tableLineId.strictExpect(m_indexWidth);

	Line &line = m_lines.at(tableLineId.m_value);

	if(!line.is(LineTag::PENDING)){
		return false;
	}

	d$LineId = line.d$lineRef;
	contextId = line.contextId;
	vAddr = line.vAddr;

	return true;
}

void Table::releasePending(RAddr tableLineId){
	tableLineId.strictExpect(m_indexWidth);

	Line &line = m_lines.at(tableLineId.m_value);

	assert(line.is(LineTag::PENDING));

	COMMIT{
		line.locked = false;
	}
}

Line* Table::storeNormal(RAddr contextId, RAddr vAddr, RAddr pAddr, bool read, bool write){
	vAddr.strictExpect(m_vWidth);
	pAddr.strictExpect(m_pWidth);
	contextId.strictExpect(getMMU().contextAW());

	Line &dst = pickDestination();
	if(dst.locked){
		DeadlockWrite("Chosen destination TLB line is locked");
		return NULL;
	}

	freeLine(dst);

	COMMIT{
		dst.present = true;
		dst.locked = true;
		dst.contextId = contextId;
		dst.vAddr = vAddr;
		dst.pAddr = pAddr;
		dst.read = read;
		dst.write = write;
	}

	return &dst;
}

Line* Table::fillPending(RAddr tableLineId, bool read, bool write, RAddr pAddr, RAddr &d$LineId)
{
	pAddr.strictExpect(m_pWidth);
	tableLineId.strictExpect(m_indexWidth);

	Line &line = m_lines[tableLineId.m_value];
	assert(line.is(LineTag::PENDING));

	d$LineId = line.d$lineRef;

	COMMIT{
		// locked stays true
		line.present = true;
		line.read = read;
		line.write = write;
		line.pAddr = pAddr;
	}

	return &line;
}

bool Table::storePending(RAddr contextId, RAddr vAddr, Addr &tableLineId, Line* &line){
	contextId.strictExpect(getMMU().contextAW());
	vAddr.strictExpect(m_vWidth);

	//line = find(contextId, vAddr, LineTag::PENDING);

	//if(line == NULL){
		line = &pickDestination();
		if(line->locked){
			return false;
		}

		COMMIT{
			freeLine(*line);

			line->present = false;
			line->locked = true;
			line->contextId = contextId;
			line->vAddr = vAddr;
		}
	//}

	tableLineId = getIndex(*line);

	return true;
}

void Table::setPrioHigh(Line &line) {
	if (this->m_evictionStrategy == EvictionStrategy::ACCESSED) {
		line.accessed = true;
	} else if (this->m_evictionStrategy == EvictionStrategy::LRU) {
		if(&line != m_head){
			if(&line == m_tail){
				m_tail = line.previous;
				m_tail->next = NULL;
			}else{
				Line *prev = line.previous;
				Line *next = line.next;
				prev->next = next;
				next->previous = prev;
			}
			line.previous = NULL;
			line.next = m_head;
			m_head->previous = &line;
			m_head = &line;
		}
	}
}
Line& Table::pickDestination(){
	Line *dest = find(LineTag::FREE);

	if (dest == NULL) {
		switch(m_evictionStrategy){
		case EvictionStrategy::PSEUDO_RANDOM:
			dest = &pickVictim_random(); break;
		case EvictionStrategy::ACCESSED:
			dest = &pickVictim_accessed(); break;
		case EvictionStrategy::LRU:
			dest = &pickVictim_lru(); break;
		default:
			UNREACHABLE
		}
	}

	return *dest;
}

Line& Table::pickVictim_random(){
	Addr mask = m_numLines - 1;
	Addr index = 0;
	for(Line &line : m_lines){
		index ^= line.vAddr.m_value & mask;
	}

	return m_lines.at(index);
}

Line& Table::pickVictim_accessed(){
	auto lambda = [](Line &line){return (line.is(LineTag::NORMAL) && !line.accessed);};
	Line *res = find(lambda);

	return (res == NULL) ? pickVictim_random() : *res;
}

Line& Table::pickVictim_lru(){
	return *m_tail;
}

void Table::freeLines(){
	auto lambda = [&](Line &line) {freeLine(line);};
	std::for_each(m_lines.begin(), m_lines.end(), lambda);
}

void Table::freeLines(const RAddr &contextId, const RAddr *vAddr){ //MLDTODO Document / find out why processId is ref and vAddr is pointer
	auto lambda =
			[&]
			(Line &line)
			{if(line.is(&contextId, vAddr, LineTag::INDEXABLE)){freeLine(line);}};
	std::for_each(m_lines.begin(), m_lines.end(), lambda);
}

void Table::freeLine(Line &line){
	//MLDTODO Figure out how to handle locked lines while invalidating.
	if(line.locked == true){
		throw exceptf<std::domain_error>("Attempt to invalidate locked TLB line");
	}

	COMMIT{
		line.present = false;
	}
}

Line::Line(AddrWidth procWidth, AddrWidth vAddrWidth, AddrWidth pAddrWidth):
	present(false),
	locked(false),
	accessed(false),
	previous(NULL),
	next(NULL),
	contextId(0,procWidth),
	vAddr(0, vAddrWidth),
	pAddr(0, pAddrWidth),
	d$lineRef(0),
	read(false),
	write(false)
{}

/*
 * p(0)	l(0) : bit 0 set  --> tag 1
 * p(0) l(1) : bit 1 set  --> tag 2
 * p(1) l(0) : bit 2 set  --> tag 4
 * p(1) l(1) : bit 3 set  --> tag 8
 *
 * is(0b0000): Always false
 * is(0b0001): True if p=0 && l=0
 * is(0b0011): True if p=0 (l may be 0 or 1)
 * is(ob0110): True if (p=0 && l=1) || (p=1 && l=0)
 */
bool Line::is(LineTag cmp){
	unsigned char type = (present << 1) | locked;
	return (((unsigned)cmp) & ( 1 << type )) >> type;
}

bool Line::is(const RAddr *cmpContextId, const RAddr *cmpVAddr, LineTag cmp)
{
	if(is(cmp)){
		if(cmpContextId == NULL || *cmpContextId == this->contextId){
				if(cmpVAddr == NULL || *cmpVAddr == this->vAddr){
					return true;
				}
		}
	}
	return false;
}

EvictionStrategy getEvictionStrategy(const std::string name){
	if (name == "PSEUDO_RANDOM" || name == "RANDOM" || name == "R") {
		return EvictionStrategy::PSEUDO_RANDOM;
	}
	if (name == "ACCESSED" || name == "A") {
		return EvictionStrategy::ACCESSED;
	}
	if (name == "LRU") {
		return EvictionStrategy::LRU;
	}
	throw exceptf<SimulationException>("Unknown eviction strategy");
}

std::ostream& operator<<(std::ostream& os, EvictionStrategy strategy) {
	switch (strategy) {
		case EvictionStrategy::PSEUDO_RANDOM: os << "PSEUDO_RANDOM"; break;
		case EvictionStrategy::ACCESSED: os << "ACCESSED"; break;
		case EvictionStrategy::LRU:	os << "LRU"; break;
		default: UNREACHABLE
	}

	return os;
}

void Table::Cmd_Info(std::ostream& out, const std::vector<std::string>& /* arguments */) const {
	out << "The Table blablabla\n\n"; //MLDTODO Maybe add some meaningfull, inspiring and brilliant text
	out << "      Eviction strategy: " << m_evictionStrategy << "\n";
	out << "            Offset size: " << unsigned(m_offsetWidth) << " bytes\n";
	out << "        Number of lines: " << unsigned(m_numLines) << "\n";
	out << "  Virtual address width: " << unsigned(m_vWidth) << "\n";
	out << " Physical address width: " << unsigned(m_pWidth) << "\n";
	Cmd_Usage(out);

	//MLDTODO Display statistics
}

void Table::Cmd_Read(std::ostream& out,	const std::vector<std::string>& /* arguments */) const {
	using namespace std;

	if(this->m_evictionStrategy == EvictionStrategy::LRU){
		out << "LRU Linked list: (head) " << getIndex(*m_head) << " <" << unsigned(m_numLines);
		out << " entries> " << getIndex(*m_tail) << " (tail)" << endl;
	}

	out	<< "  # | P | L";

	if (this->m_evictionStrategy == EvictionStrategy::ACCESSED) {
		out << " | A";
	} else if (this->m_evictionStrategy == EvictionStrategy::LRU) {
		out << " | Prev | Next";
	}

	out << " | " << left << setw(RAddr::getPrintWidth(getMMU().contextAW())) << "Proc. ID";
	out << " | " << left << setw(RAddr::getPrintWidth(getVAddrWidth())) << "vAddr";
	out << " | " << "Type-specific Fields";
	out << endl;

	for (unsigned i = 0; i < m_lines.size(); i++) {
		Line line = m_lines.at(i);
		out << noboolalpha << noshowbase << setfill(' ') << dec;
		out << setw(3) << i << " | ";
		out << setw(1) << line.present << " | ";
		out << setw(1) << line.locked << " | ";

		if (this->m_evictionStrategy == EvictionStrategy::ACCESSED) {
			out << setw(1) << line.accessed << " | ";
		} else if (this->m_evictionStrategy == EvictionStrategy::LRU) {
			out << setw(4);
			if(line.previous == NULL){	out << "-"; }
			else{ out << getIndex(*line.previous); }

			out << " | " << setw(4);

			if(line.next == NULL){	out << "-"; }
			else{ out << getIndex(*line.next); }

			out << " | ";
		}

		out << line.contextId << " | ";
		out << line.vAddr << " | ";

		if(line.is(LineTag::FREE)){
			out << "FREE: -" << endl;
		}else if(line.is(LineTag::PENDING)){
			out << dec << "PENDING: D$-line: " << line.d$lineRef << endl;
		}else if(line.is(LineTag::PRESENT)){
			out << "PRESENT: PA=" << line.pAddr << " ";
			out << "R=" << dec << setw(1) << line.read << " ";
			out << "W=" << setw(1) << line.write;
			out << endl;
		}
	}
}

void Table::Cmd_Write(std::ostream& out, const std::vector<std::string>& arguments)
{
	Arguments arg(arguments);

    if (arg.size() == 0){
    	Cmd_Usage(out);
    	return;
    }

    if(arg.is(0, false, "s", "strategy")){
    	arg.expect(2);
		EvictionStrategy old = m_evictionStrategy;

		m_evictionStrategy = getEvictionStrategy(arguments[1]);
		initStrategy();
		out << "Changed eviction strategy from " << old << " to " << m_evictionStrategy << std::endl;
		out << "Priorities have been reset where applicable" << std::endl;
    }else if(arg.is(0, false, "h", "head")){
    	arg.expect(2);
    	assert(m_evictionStrategy == EvictionStrategy::LRU);

    	Addr index = arg.getULL(1, m_numLines);
    	Line *line = &(m_lines[index]);

    	out << "Changed LRU Head from " << getIndex(*m_head);
    	m_head = line;
    	out << " to " << index << std::endl;
    }else if(arg.is(0, false, "t", "tail")){
    	arg.expect(2);
    	assert(m_evictionStrategy == EvictionStrategy::LRU);

    	Addr index = arg.getULL(1, m_numLines);
    	Line *line = &(m_lines[index]);

    	out << "Changed LRU Tail from " << getIndex(*m_tail);
    	m_tail = line;
    }else if(arg.is(0, false, "l", "line")){
    	arg.expect(2, SIZE_MAX);

		Addr lineIndex = arg.getULL(1, m_numLines);
		Line *line = &(m_lines[lineIndex]);

		arg.namedSet("p", true, line->present);
		arg.namedSet("cid", true, line->contextId);
		arg.namedSet("pa", true, line->pAddr);
		arg.namedSet("l", true, line->locked);
		arg.namedSet("va", true, line->vAddr);
		arg.namedSet("rd", true, line->read);
		arg.namedSet("wr", true, line->write);
		arg.namedSet("d$", true, (Addr&)line->d$lineRef);
		arg.namedSet("a", true, line->accessed);

		RAddr lineAddr = RAddr(0, m_numLines);
		if(arg.namedSet("prev", true, lineAddr)){
    		line->previous = &(m_lines[lineAddr.m_value]);
		}

		if(arg.namedSet("next", true, lineAddr)){
			line->next = &(m_lines[lineAddr.m_value]);
		}

		out << "Line " << unsigned(lineIndex) << " has been updated" << std::endl;
    }else{
    	Cmd_Usage(out);
    }
}

void Table::Cmd_Usage_write_line(std::ostream& out) const{
	out << "write line <lineId> <var=val>...:\n";
	out << "    variables:\n";
	out << "        p    Present\n";
	out << "        cid  Context ID\n";
	out << "        pa   Physical Address\n";
	out << "        prev Previous Line (Only for LRU tables)\n";
	out << "        l    Locked\n";
	out << "        va   Virtual Address\n";
	out << "        rd   Read (Only when present)\n";
	out << "        wr   Write (Only when present)\n";
	out << "        d$   D-Cache Line id (Only when locked and not present)\n";
	out << "        a    Accessed (Only for ACCESSED tables)\n";
	out << "        nxt  Next line (Only for LRU tables)\n";
	out << std::endl;
}

void Table::Cmd_Usage(std::ostream& out) const{
	out << "Supported operations:\n";
	out << "    read\n";
	out << "    write s(trategy) <RANDOM|ACCESSED|LRU>\n";
	out << "    write h(head)    <index>\n";
	out << "    write t(ail)     <index>\n";
	out << "    write l(ine)     <index> <variable=value>...\n";
	out << std::endl;
}

} /* namespace mmu */
} /* namespace drisc */
} /* namespace Simulator */


text:
class CustomBoolValidator < Apipie::Validator::BaseValidator
  def validate(value)
    value.in?([true, false])
  end

  def self.build(param_description, argument, options, block)
    new(param_description) if argument == :custom_bool
  end

  def description
    "Must be a boolean."
  end

  def ignore_allow_blank?
    true
  end
end

redpajama_set_name: RedPajamaGithub


text:
{% import '../../hackathons/classmates/data.html' as data %}

# Report

There are {{ data.comments.length }} students who gave a self-introduction. As a
class, we brainstormed and came up with a long list of further questions we can
ask based on this data. Our team chose to tackle on the following:

# Who wrote the most for thier comment?

{% lodash %}

return _.pluck(_.sortBy(data.comments, function(comment){
		return _.size(comment.body.split(""));
		}).reverse(), 'user.login');

{% endlodash %}

In order from most verbose comment to least: {{result | json}}

# Which student has been a member of GitHub the longest?
(This assumes that userIDs were assigned consecutively)

{% lodash %}
return _.first(_.pluck(_.sortBy((_.pluck((data.comments), "user")), "id"), "login"))
{% endlodash %}

Assuming that GitHub userIDs are assigned sequentially, {{result | json}} has been a member of github the longest.

# Who has updated their comment?

{% lodash %}
return _.pluck(_.filter(data.comments, function(comment){
	return comment['created_at'] !== comment['updated_at'];
}), 'user.login');
{% endlodash %}

The students who have updated their comments are: {{result | json}}

# Who uses the most punctuation?

{% lodash %}
return _.chain(data.comments)
    .map(function(obj) {
        return [obj.user.login,
                obj.body.match(/[`~!@#\$%\^&\*\(\)_\+-=\[\]\\\{\}\|;':",\./<>\?]/g).length];
    })
    .sortBy(function(tup) {
        return tup[1];
    })
    .map(function(tup) {
        return tup[0];
    })
{% endlodash %}

In order of least punctuation used to most:

{{ result | json }}


text:
package com.genie.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.envers.Audited;

import com.genie.persistence.PersistenceListener;
import com.genie.utils.DataFormatter;

/**
 * @author ccubukcu
 *
 */
@Audited
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@EntityListeners(value = PersistenceListener.class)
public class BaseEntity extends AbstractBaseEntity {
	private static final long serialVersionUID = 1L;

	@Column(name = "creation_user", length = 50)
	private String creationUser;
	@Column(name = "creation_time")
	@Temporal(TemporalType.TIMESTAMP)
	private Date creationTime;
	@Column(name = "last_update_user", length = 50)
	private String lastUpdateUser;
	@Column(name = "last_update_time")
	@Temporal(TemporalType.TIMESTAMP)
	private Date lastUpdateTime;

	@Column(name = "active")
	private Boolean active;

	public String getCreationUser() {
		return creationUser;
	}

	public void setCreationUser(String creationUser) {
		this.creationUser = creationUser;
	}

	public Date getCreationTime() {
		return creationTime;
	}

	public void setCreationTime(Date creationTime) {
		this.creationTime = creationTime;
	}

	public String getLastUpdateUser() {
		return lastUpdateUser;
	}

	public void setLastUpdateUser(String lastUpdateUser) {
		this.lastUpdateUser = lastUpdateUser;
	}

	public Date getLastUpdateTime() {
		return lastUpdateTime;
	}

	public void setLastUpdateTime(Date lastUpdateTime) {
		this.lastUpdateTime = lastUpdateTime;
	}

	public String getLastUpdateTimeString() {
		if (lastUpdateTime == null)
			return "-";
		return DataFormatter.formatDate(lastUpdateTime);
	}

	public String getCreationTimeString() {
		if (creationTime == null)
			return "";
		else
			return DataFormatter.formatDate(creationTime);
	}

	public void setActive(Boolean active) {
		this.active = active;
	}

	public Boolean getActive() {
		return active;
	}
}


text:
function Phonebook(){
	this.records = [];
	this.loadToLocalStorage();
}

Phonebook.prototype.validate = function(el) {
	if (this.isDuplicate(el)){
		return false;
	}
	if (!el.hasOwnProperty('name') || !this.checkName(el.name)){
		return false;
	}
	if (!el.hasOwnProperty('surname') || !this.checkName(el.surname) ){
		return false;
	}
	if (!el.hasOwnProperty('number') || !this.checkNumber(el.number)){
		return false;
	}
	return true;
}

Phonebook.prototype.readFile = function(element,callback) {
	var input = element;
	if (!input.files.length) {
		this.displayAlert('Please select a file!');
		return;
	}
	var that = this;
	var file = input.files[0];
	input.value = "";
	var reader = new FileReader();
	reader.onloadend = function(e) {
		if (e.target.readyState == FileReader.DONE) {
			var json = e.target.result;
			try{
				var pb = JSON.parse(json);
			}catch(e){
				that.displayAlert("File is not valid");
				return;
			}
			var l = pb.length;
			var k = 0;
			for (var i = 0; i < l; i++) {
				if (!that.validate(pb[i])){
					k++
					continue;
				}
				pb[i].name = pb[i].name.trim();
				pb[i].surname = pb[i].surname.trim();
				pb[i].number = pb[i].number.trim();
				that.records.push(pb[i]);
			}
			if (k > 0){
				that.displayAlert("Error: Phonebook loaded, but "+k+" record/s have been ignored because they are not valid");
			}
			else {
				that.displayAlert("Phonebook loaded successfully!");
			}
			that.saveInLocalStorage();
			callback();
		}
	}
	reader.readAsBinaryString(file);
}

Phonebook.prototype.search = function(text) {
	var search = text.trim() + "£";
	search = search.replace(/surname:/i,"£2");
	search = search.replace(/name:/i,"£1");
	search = search.replace(/number:/i,"£3");
	var l = this.records.length;
	var result = [];
	for (var i = 0; i < l; i++){
		var case1=/£1/.test(search);
		var case2=/£2/.test(search);
		var case3=/£3/.test(search);
		if (case1 || case2 || case3){
			var match1 = false;
			var match2 = false;
			var match3 = false;
			if(case1){
				var r = search.match(/£1(.*?) *£/)[1].trim();
				r = r.split("").join(".*?");
				var regexp = new RegExp(r,"i");
				if(regexp.test(this.records[i].name)){
					match1 = true;
				}
			}
			if(case2) {
				var r = search.match(/£2(.*?) *£/)[1].trim();
				r = r.split("").join(".*?");
				var regexp = new RegExp(r,"i");
				if(regexp.test(this.records[i].surname)){
					match2 = true;
				}
			}
			if(case3) {
				var r = search.match(/£3(.*?) *£/)[1].trim();
				r = r.split("").join(".*?");
				var regexp = new RegExp(r,"i");
				if(regexp.test(this.records[i].number)){
					match3 = true;
				}
			}
			if((case1 == match1)&&(case2 == match2)&&(case3 == match3)){
				var temp = {
					"name" : this.records[i].name,
					"surname" : this.records[i].surname,
					"number" : this.records[i].number,
					"id" : i
				}
				result.push(temp);
			}
		} else {
			var regexp = search.slice(0,-1).split(" ");
			var text = this.records[i].name + " " + this.records[i].surname + " " + this.records[i].number;
			var match = true;
			for (var j = 0; j < regexp.length; j++) {
				regexp[j] = regexp[j].split("").join(".*?");
				regexp[j] = new RegExp(regexp[j], "i");
				if(!regexp[j].test(text)){
					match = false;
					break;
				}
			}
			if(match){
				var temp = {
					"name" : this.records[i].name,
					"surname" : this.records[i].surname,
					"number" : this.records[i].number,
					"id" : i
				}
				result.push(temp);
			}
		}
	}
	return result;
}

Phonebook.prototype.displayAlert = function(text){
	try {
		var alert = document.getElementById('alert');
		alert.style.display = "block";
		alert.innerHTML = text;
		window.setTimeout(function(){alert.style.display = "none"}, 3000);
	} catch(e){
		console.log(e+" Element 'alert' doesn't exist");
	}
}

Phonebook.prototype.isDuplicate = function(e){
	bool = false;
	for (var i = 0; i < this.records.length; i++) {
		if(this.records[i].name == e.name && this.records[i].surname == e.surname && this.records[i].number == e.number){
			bool = true;
			break;
		}
	}
	return bool;
}

Phonebook.prototype.checkName = function(name) {
	var regexp = /^[\w ]+$/;
	return regexp.test(name);
}

Phonebook.prototype.checkNumber = function(n) {
	var regexp = /^\+\d{1,3} \d+ \d{6,}$/;
	return regexp.test(n);
}

Phonebook.prototype.clear = function() {
	this.records=[];
	this.saveInLocalStorage();
	return;
}

Phonebook.prototype.toString = function() {
	if(this.records.length) {
		return JSON.stringify(this.records);
	} else {
		return false;
	}
}

Phonebook.prototype.newRecord = function(name,surname,number) {
	if(this.checkName(name) && this.checkName(surname) && this.checkNumber(number)){
		var e = {
			"name" : name,
			"surname" : surname,
			"number" : number
		};
		if(this.isDuplicate(e)){
			this.displayAlert("This record already exists");
		} else {
			this.records.push(e);
			this.displayAlert("New record added");
			this.saveInLocalStorage();
			return true;
		}
	} else {
		return false;
	}
}

Phonebook.prototype.editRecord = function(i,name,surname,number) {
	if(this.checkName(name) && this.checkName(surname) && this.checkNumber(number)){
		var e = {
			"name" : name,
			"surname" : surname,
			"number" : number
		};
		if(this.isDuplicate(e)){
			return 1;
		} else {
			this.records[i].name = name;
			this.records[i].surname = surname;
			this.records[i].number = number;
			this.saveInLocalStorage();
			return 2;
		}
	} else {
		return false;
	}
}

Phonebook.prototype.removeRecord = function(i) {
	this.records.splice(i,1);
	this.saveInLocalStorage();
}

Phonebook.prototype.saveInLocalStorage = function() {
	if (typeof(Storage) !== 'undefined') {
		var json = this.toString();
		var local = localStorage.getItem('phonebook');
		if (local != json){
			localStorage.setItem('phonebook', json);
		}
	}
}

Phonebook.prototype.loadToLocalStorage = function() {
	if (typeof(Storage) !== 'undefined') {
		var local = JSON.parse(localStorage.getItem('phonebook'));
		if (local){
			var l = local.length;
			for (var i = 0; i < l; i++) {
				if (!this.validate(local[i])){
					continue;
				}
				local[i].name = local[i].name.trim();
				local[i].surname = local[i].surname.trim();
				local[i].number = local[i].number.trim();
				this.records.push(local[i]);
			}
			alert("Phonebook load from localStorage");
		}
	}
}


text:
uint8_t pseudo_rand_8() {

    static uint16_t seed = 0;
    return (uint8_t)(seed = (12657 * seed + 12345) % 256);
}

//Window constructor
Window* Window_new(int16_t x, int16_t y, uint16_t width,
                   uint16_t height, uint16_t flags, Context* context) {

    //Try to allocate space for a new WindowObj and fail through if malloc fails
    Window* window;
    if(!(window = (Window*)malloc(sizeof(Window))))
        return window;

    //Attempt to initialize the new window
    if(!Window_init(window, x, y, width, height, flags, context)) {

        free(window);
        return (Window*)0;
    }

    return window;
}

//Seperate object allocation from initialization so we can implement
//our inheritance scheme
int Window_init(Window* window, int16_t x, int16_t y, uint16_t width,
                uint16_t height, uint16_t flags, Context* context) {

    //Moved over here from the desktop
    //Create child list or clean up and fail
    if(!(window->children = List_new()))
        return 0;

    //Assign the property values
    window->x = x;
    window->y = y;
    window->width = width;
    window->height = height;
    window->context = context;
    window->flags = flags;
    window->parent = (Window*)0;
    window->drag_child = (Window*)0;
    window->drag_off_x = 0;
    window->drag_off_y = 0;
    window->last_button_state = 0;
    window->paint_function = Window_paint_handler;
    window->mousedown_function = Window_mousedown_handler;

    return 1;
}

//Recursively get the absolute on-screen x-coordinate of this window
int Window_screen_x(Window* window) {

    if(window->parent)
        return window->x + Window_screen_x(window->parent);

    return window->x;
}

//Recursively get the absolute on-screen y-coordinate of this window
int Window_screen_y(Window* window) {

    if(window->parent)
        return window->y + Window_screen_y(window->parent);

    return window->y;
}

void Window_draw_border(Window* window) {

    int screen_x = Window_screen_x(window);
    int screen_y = Window_screen_y(window);

    //Draw a 3px border around the window
    Context_draw_rect(window->context, screen_x, screen_y,
                      window->width, window->height, WIN_BORDERCOLOR);
    Context_draw_rect(window->context, screen_x + 1, screen_y + 1,
                      window->width - 2, window->height - 2, WIN_BORDERCOLOR);
    Context_draw_rect(window->context, screen_x + 2, screen_y + 2,
                      window->width - 4, window->height - 4, WIN_BORDERCOLOR);

    //Draw a 3px border line under the titlebar
    Context_horizontal_line(window->context, screen_x + 3, screen_y + 28,
                            window->width - 6, WIN_BORDERCOLOR);
    Context_horizontal_line(window->context, screen_x + 3, screen_y + 29,
                            window->width - 6, WIN_BORDERCOLOR);
    Context_horizontal_line(window->context, screen_x + 3, screen_y + 30,
                            window->width - 6, WIN_BORDERCOLOR);

    //Fill in the titlebar background
    Context_fill_rect(window->context, screen_x + 3, screen_y + 3,
                      window->width - 6, 25, WIN_TITLECOLOR);
}

//Apply clipping for window bounds without subtracting child window rects
void Window_apply_bound_clipping(Window* window, int in_recursion) {

    Rect* temp_rect;
    int screen_x, screen_y;
    List* clip_windows;
    Window* clipping_window;

    //Build the visibility rectangle for this window
    //If the window is decorated and we're recursing, we want to limit
    //the window's drawable area to the area inside the window decoration.
    //If we're not recursing, however, it means we're about to paint
    //ourself and therefore we want to wait until we've finished painting
    //the window border to shrink the clipping area
    screen_x = Window_screen_x(window);
    screen_y = Window_screen_y(window);

    if((!(window->flags & WIN_NODECORATION)) && in_recursion) {

        //Limit client drawable area
        screen_x += WIN_BORDERWIDTH;
        screen_y += WIN_TITLEHEIGHT;
        temp_rect = Rect_new(screen_y, screen_x,
                             screen_y + window->height - WIN_TITLEHEIGHT - WIN_BORDERWIDTH - 1,
                             screen_x + window->width - (2*WIN_BORDERWIDTH) - 1);
    } else {

        temp_rect = Rect_new(screen_y, screen_x, screen_y + window->height - 1,
                             screen_x + window->width - 1);
    }

    //If there's no parent (meaning we're at the top of the window tree)
    //then we just add our rectangle and exit
    if(!window->parent) {

        Context_add_clip_rect(window->context, temp_rect);
        return;
    }

    //Otherwise, we first reduce our clipping area to the visibility area of our parent
    Window_apply_bound_clipping(window->parent, 1);

    //Now that we've reduced our clipping area to our parent's clipping area, we can
    //intersect our own bounds rectangle to get our main visible area
    Context_intersect_clip_rect(window->context, temp_rect);

    //And finally, we subtract the rectangles of any siblings that are occluding us
    clip_windows = Window_get_windows_above(window->parent, window);

    while(clip_windows->count) {

        clipping_window = (Window*)List_remove_at(clip_windows, 0);

        //Make sure we don't try and clip the window from itself
        if(clipping_window == window)
            continue;

        //Get a rectangle from the window, subtract it from the clipping
        //region, and dispose of it
        screen_x = Window_screen_x(clipping_window);
        screen_y = Window_screen_y(clipping_window);

        temp_rect = Rect_new(screen_y, screen_x,
                             screen_y + clipping_window->height - 1,
                             screen_x + clipping_window->width - 1);
        Context_subtract_clip_rect(window->context, temp_rect);
        free(temp_rect);
    }

    //Dispose of the used-up list
    free(clip_windows);
}

//Another override-redirect function
void Window_paint(Window* window) {

    int i, screen_x, screen_y, child_screen_x, child_screen_y;
    Window* current_child;
    Rect* temp_rect;

    //Start by limiting painting to the window's visible area
    Window_apply_bound_clipping(window, 0);

    //Set the context translation
    screen_x = Window_screen_x(window);
    screen_y = Window_screen_y(window);

    //If we have window decorations turned on, draw them and then further
    //limit the clipping area to the inner drawable area of the window
    if(!(window->flags & WIN_NODECORATION)) {

        //Draw border
        Window_draw_border(window);

        //Limit client drawable area
        screen_x += WIN_BORDERWIDTH;
        screen_y += WIN_TITLEHEIGHT;
        temp_rect = Rect_new(screen_y, screen_x,
                             screen_y + window->height - WIN_TITLEHEIGHT - WIN_BORDERWIDTH - 1,
                             screen_x + window->width - (2*WIN_BORDERWIDTH) - 1);
        Context_intersect_clip_rect(window->context, temp_rect);
    }

    //Then subtract the screen rectangles of any children
    //NOTE: We don't do this in Window_apply_bound_clipping because, due to
    //its recursive nature, it would cause the screen rectangles of all of
    //our parent's children to be subtracted from the clipping area -- which
    //would eliminate this window.
    for(i = 0; i < window->children->count; i++) {

        current_child = (Window*)List_get_at(window->children, i);

        child_screen_x = Window_screen_x(current_child);
        child_screen_y = Window_screen_y(current_child);

        temp_rect = Rect_new(child_screen_y, child_screen_x,
                             child_screen_y + current_child->height - 1,
                             child_screen_x + current_child->width - 1);
        Context_subtract_clip_rect(window->context, temp_rect);
        free(temp_rect);
    }

    //Finally, with all the clipping set up, we can set the context's 0,0 to the top-left corner
    //of the window's drawable area, and call the window's final paint function
    window->context->translate_x = screen_x;
    window->context->translate_y = screen_y;
    window->paint_function(window);

    //Now that we're done drawing this window, we can clear the changes we made to the context
    Context_clear_clip_rects(window->context);
    window->context->translate_x = 0;
    window->context->translate_y = 0;

    //Since we're still painting the whole screen whenever anything changes, we must also
    //call on all of our children to paint themselves so we don't miss painting anything
    for(i = 0; i < window->children->count; i++) {

        current_child = (Window*)List_get_at(window->children, i);
        Window_paint(current_child);
    }
}

//This is the default paint method for a new window
void Window_paint_handler(Window* window) {

    //Fill in the window background
    Context_fill_rect(window->context, 0, 0,
                      window->width, window->height, WIN_BGCOLOR);
}

//Used to get a list of windows overlapping the passed window
List* Window_get_windows_above(Window* parent, Window* child) {

    int i;
    Window* current_window;
    List* return_list;

    //Attempt to allocate the output list
    if(!(return_list = List_new()))
        return return_list;

    //We just need to get a list of all items in the
    //child list at higher indexes than the passed window
    //We start by finding the passed child in the list
    for(i = 0; i < parent->children->count; i++)
        if(child == (Window*)List_get_at(parent->children, i))
            break;

    //Now we just need to add the remaining items in the list
    //to the output (IF they overlap, of course)
    //NOTE: As a bonus, this will also automatically fall through
    //if the window wasn't found
    for(; i < parent->children->count; i++) {

        current_window = List_get_at(parent->children, i);

        //Our good old rectangle intersection logic
        if(current_window->x <= (child->x + child->width - 1) &&
		   (current_window->x + current_window->width - 1) >= child->x &&
		   current_window->y <= (child->y + child->height - 1) &&
		   (current_window->y + current_window->height - 1) >= child->y)
            List_add(return_list, current_window); //Insert the overlapping window
    }

    return return_list;
}

//Interface between windowing system and mouse device
void Window_process_mouse(Window* window, uint16_t mouse_x,
                          uint16_t mouse_y, uint8_t mouse_buttons) {

    int i, inner_x1, inner_y1, inner_x2, inner_y2;
    Window* child;

    //If we had a button depressed, then we need to see if the mouse was
    //over any of the child windows
    //We go front-to-back in terms of the window stack for free occlusion
    for(i = window->children->count - 1; i >= 0; i--) {

        child = (Window*)List_get_at(window->children, i);

        //If mouse isn't window bounds, we can't possibly be interacting with it
        if(!(mouse_x >= child->x && mouse_x < (child->x + child->width) &&
           mouse_y >= child->y && mouse_y < (child->y + child->height)))
            continue;

        //Now we'll check to see if we're dragging a titlebar
        if(mouse_buttons && !window->last_button_state) {

            //Let's adjust things so that a raise happens whenever we click inside a
            //child, to be more consistent with most other GUIs
            List_remove_at(window->children, i); //Pull window out of list
            List_add(window->children, (void*)child); //Insert at the top

            //See if the mouse position lies within the bounds of the current
            //window's 31 px tall titlebar
            //We check the decoration flag since we can't drag a window without a titlebar
            if(!(child->flags & WIN_NODECORATION) &&
                mouse_y >= child->y && mouse_y < (child->y + 31)) {

                //We'll also set this window as the window being dragged
                //until such a time as the mouse is released
                window->drag_off_x = mouse_x - child->x;
                window->drag_off_y = mouse_y - child->y;
                window->drag_child = child;

                //We break without setting target_child if we're doing a drag since
                //that shouldn't trigger a mouse event in the child
                break;
            }
        }

        //Found a target, so forward the mouse event to that window and quit looking
        Window_process_mouse(child, mouse_x - child->x, mouse_y - child->y, mouse_buttons);
        break;
    }

    //Moving this outside of the mouse-in-child detection since it doesn't really
    //have anything to do with it
    if(!mouse_buttons)
        window->drag_child = (Window*)0;

    //Update drag window to match the mouse if we have an active drag window
    if(window->drag_child) {

        window->drag_child->x = mouse_x - window->drag_off_x;
        window->drag_child->y = mouse_y - window->drag_off_y;
    }

    //If we didn't find a target in the search, then we ourselves are the target of any clicks
    if(window->mousedown_function && mouse_buttons && !window->last_button_state)
        window->mousedown_function(window, mouse_x, mouse_y);

    //Update the stored mouse button state to match the current state
    window->last_button_state = mouse_buttons;
}

//The default handler for window mouse events doesn't do anything
void Window_mousedown_handler(Window* window, int x, int y) {

    return;
}

//Quick wrapper for shoving a new entry into the child list
void Window_insert_child(Window* window, Window* child) {

    child->parent = window;
    child->context = window->context;
    List_add(window->children, child);
}

//A method to automatically create a new window in the provided parent window
Window* Window_create_window(Window* window, int16_t x, int16_t y,
                             uint16_t width, int16_t height, uint16_t flags) {

    //Attempt to create the window instance
    Window* new_window;
    if(!(new_window = Window_new(x, y, width, height, flags, window->context)))
        return new_window;

    //Attempt to add the window to the end of the parent's children list
    //If we fail, make sure to clean up all of our allocations so far
    if(!List_add(window->children, (void*)new_window)) {

        free(new_window);
        return (Window*)0;
    }

    //Set the new child's parent
    new_window->parent = window;

    return new_window;
}


text:
/**
 * Dependencies
 */

var mongoose = require('mongoose'),
    Apps     = mongoose.model('market_apps');

/**
 * GET /app/:appID
 */
exports.app = function (req, res, next) {

  var appID = req.params.appID;

  // Make sure `:appID` is a number
  if (isNaN(appID))
    return res.json({ error: 'Invalid appID' });

  // Fetch the games (:appID) info
  Apps.findById(appID, function (err, appInfo) {

    if (err) return next(err);

    /**
     * TODO
     * - Proper 404 page for untracked app
     */
    if (!appInfo)
      return res.json(404, { error: 'No stats found for this app' });

    return res.render('app-page', { title: 'Open Market | ' + appInfo.name, appInfo: appInfo });

  });

};


text:
package com.baoyz.viewbinder.setter;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 *
 * @author baoyz
 * @date 2014-7-4
 *
 */
@Retention(RUNTIME)
@Target({METHOD, FIELD})
public @interface BindBackgroundDrawable {
	int value();
	String setter() default "setBackgroundDrawable";
}


text:
const optimization = require('../optimization');
const utils = require('../utils');

module.exports = class Media {
    /**
     * @constructor
     * @param {MediaQuery[]} media
     * @param {*} content
     */
    constructor(media, content) {
        this.media = media;
        this.content = content;
    }

    /**
     * @return {string}
     */
    mediaQueriesToString() {
        return utils.joinAll(this.media, ',');
    }

    /**
     * @return {string}
     */
    toString() {
        const queryString = this.mediaQueriesToString();
        return `@media${queryString[0] === '(' ? '' : ' '}${queryString}{${utils.joinAll(this.content)}}`;
    }

    /**
     * @return {string}
     */
    pretty(indent) {
        let output = '';
        output += utils.indent('@media ' + utils.joinAll(this.media, ', ', utils.prettyMap(indent)) + ' {') + '\n';
        output += this.content.map(line => utils.indent(line.pretty(indent + 1), indent)).join('\n') + '\n';
        output += utils.indent('}', indent) + '\n';
        return output;
    }

    /**
     * @param {object} kw
     * @return {Media}
     */
    optimize(kw) {
        this.media = optimization.optimizeList(this.media, kw);

        // OPT: Remove duplicate media queries.
        this.media = utils.uniq(null, this.media);

        if (!this.media.length) {
            return null;
        }

        return this.optimizeContent(kw);
    }

    /**
     * @param {object} kw
     * @return {Media}
     */
    optimizeContent(kw) {
        this.content = optimization.optimizeBlocks(this.content, kw);
        if (!this.content.length) {
            return null;
        }

        return this;
    }
};


text:
delete from corder;
delete from customer;
delete from product;


text:
package com.apsolete.machinery.calculation;

import com.apsolete.machinery.common.*;

public abstract class DesignContent extends ContentBase
{
    public static final int CHANGEGEARS = 0;
    public static final int GEARWHEELS = 1;
    public static final int GEARWHEELSEXT = 2;
    public static final int BELTS = 3;

    private int _type;

    public DesignContent(int type, int layout, int title)
    {
        super(layout, title);
        _type = type;
    }

    public int type()
    {
        return _type;
    }

    public abstract SettingsBase getSettings();
    public abstract void save();
    public abstract void clear();
    public abstract boolean close();
    public abstract void setOptions();
    protected abstract void calculate();
}


text:
option(WITH_DEBUG_TRANSPORT "Print transport debug messages." OFF)
option(WITH_DEBUG_CHANNELS "Print channel manager debug messages." OFF)
option(WITH_DEBUG_SVC "Print static virtual channel debug messages." OFF)
option(WITH_DEBUG_DVC "Print dynamic virtual channel debug messages." OFF)
option(WITH_DEBUG_TIMEZONE "Print timezone redirection related messages." OFF)
option(WITH_DEBUG_KBD "Print keyboard related debug messages." OFF)
option(WITH_DEBUG_NLA "Print authentication related debug messages." OFF)
option(WITH_DEBUG_NEGO "Print negotiation related debug messages." OFF)
option(WITH_DEBUG_CERTIFICATE "Print certificate related debug messages." OFF)
option(WITH_DEBUG_LICENSE "Print license debug messages." OFF)
option(WITH_DEBUG_GDI "Print graphics debug messages." OFF)
option(WITH_DEBUG_RFX "Print RemoteFX debug messages." OFF)
option(WITH_DEBUG_X11 "Print X11 Client debug messages" OFF)
option(WITH_DEBUG_X11_CLIPRDR "Print X11 clipboard redirection debug messages" OFF)
option(WITH_DEBUG_X11_LOCAL_MOVESIZE "Print X11 Client local movesize debug messages" OFF)
option(WITH_DEBUG_RAIL "Print RemoteApp debug messages" OFF)
option(WITH_DEBUG_XV "Print XVideo debug messages" OFF)
option(WITH_DEBUG_SCARD "Print smartcard debug messages" OFF)
option(WITH_DEBUG_ORDERS "Print drawing orders debug messages" OFF)
option(WITH_MANPAGES "Generate manpages." ON)
option(WITH_PROFILER "Compile profiler." OFF)
option(WITH_SSE2 "Use SSE2 optimization." OFF)
option(WITH_SSE2_TARGET "Allow compiler to generate SSE2 instructions." OFF)
option(WITH_DEBUG_REDIR "Redirection debug messages" OFF)
option(WITH_DEBUG_CLIPRDR "Print clipboard redirection debug messages" OFF)
option(WITH_DEBUG_WND "Print window order debug messages" OFF)
option(WITH_NEON "Enable NEON optimization for rfx decoder" OFF)


text:
package com.amazonaws.services.lambda.runtime.events;

import lombok.*;

import java.util.Map;

/**
 * Represent the class for the Cognito User Pool Verify Auth Challenge Response Lambda Trigger
 *
 * See Verify Auth Challenge Response Lambda Trigger
 *
 * @author jvdl <jvdl@amazon.com>
 */
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class CognitoUserPoolVerifyAuthChallengeResponseEvent extends CognitoUserPoolEvent {
    /**
     * The request from the Amazon Cognito service.
     */
    private Request request;

    /**
     * The response from your Lambda trigger.
     */
    private Response response;

    @Builder(setterPrefix = "with")
    public CognitoUserPoolVerifyAuthChallengeResponseEvent(
            String version,
            String triggerSource,
            String region,
            String userPoolId,
            String userName,
            CallerContext callerContext,
            Request request,
            Response response) {
        super(version, triggerSource, region, userPoolId, userName, callerContext);
        this.request = request;
        this.response = response;
    }

    @Data
    @EqualsAndHashCode(callSuper = true)
    @NoArgsConstructor
    public static class Request extends CognitoUserPoolEvent.Request {
        /**
         * One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the verify auth challenge trigger.
         */
        private Map<String, String> clientMetadata;
        /**
         * This parameter comes from the Create Auth Challenge trigger, and is compared against a user's challengeAnswer to determine whether the user passed the challenge.
         */
        private Map<String, String> privateChallengeParameters;
        /**
         * The answer from the user's response to the challenge.
         */
        private Map<String, String> challengeAnswer;
        /**
         * This boolean is populated when PreventUserExistenceErrors is set to ENABLED for your User Pool client
         */
        private boolean userNotFound;

        @Builder(setterPrefix = "with")
        public Request(Map<String, String> userAttributes,
                       Map<String, String> clientMetadata,
                       Map<String, String> challengeAnswer,
                       Map<String, String> privateChallengeParameters,
                       boolean userNotFound) {
            super(userAttributes);
            this.clientMetadata = clientMetadata;
            this.userNotFound = userNotFound;
            this.challengeAnswer = challengeAnswer;
            this.privateChallengeParameters = privateChallengeParameters;
        }
    }

    @AllArgsConstructor
    @Builder(setterPrefix = "with")
    @Data
    @NoArgsConstructor
    public static class Response {
        /**
         * Set to true if the user has successfully completed the challenge, or false otherwise.
         */
        private boolean answerCorrect;
    }
}


text:
answer = 0
for index in range(1000):
  if not index % 3 or not index % 5:
    answer += index
print answer


text:
using System;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Autofac.Core;

namespace Autofac.Tests.Core
{
    [TestFixture]
    public class ResolvedParameterTests
    {
        [Test]
        public void ResolvesParameterValueFromContext()
        {
            var cb = new ContainerBuilder();
            cb.RegisterInstance((object)'a').Named<char>("character");
            cb.RegisterType<string>()
                .UsingConstructor(typeof(char), typeof(int))
                .WithParameter(new TypedParameter(typeof(int), 5))
                .WithParameter(new ResolvedParameter(
                    (pi, ctx) => pi.ParameterType == typeof(char),
                    (pi, ctx) => ctx.ResolveNamed<char>("character")));
            var c = cb.Build();
            var s = c.Resolve<string>();
            Assert.AreEqual("aaaaa", s);
        }

// ReSharper disable UnusedTypeParameter
        public interface ISomething<T> { }
// ReSharper restore UnusedTypeParameter

        public class ConcreteSomething<T> : ISomething<T> { }

        public class SomethingDecorator<T> : ISomething<T>
        {
            public ISomething<T> Decorated { get; private set; }

            public SomethingDecorator(ISomething<T> decorated)
            {
                Decorated = decorated;
            }
        }

        [Test]
        public void CanConstructDecoratorChainFromOpenGenericTypes()
        {
            var builder = new ContainerBuilder();

            builder.RegisterGeneric(typeof(ConcreteSomething<>));

            var decoratedSomethingArgument = new ResolvedParameter(
                (pi, c) => pi.Name == "decorated",
                (pi, c) => c.Resolve(typeof(ConcreteSomething<>).MakeGenericType(
                                pi.ParameterType.GetGenericArguments())));

            builder.RegisterGeneric(typeof(SomethingDecorator<>))
                .As(typeof(ISomething<>))
                .WithParameter(decoratedSomethingArgument);

            var container = builder.Build();

            var concrete = container.Resolve<ISomething<int>>();

            Assert.IsInstanceOf<SomethingDecorator<int>>(concrete);
            Assert.IsInstanceOf<ConcreteSomething<int>>(((SomethingDecorator<int>)concrete).Decorated);
        }

        [Test]
        public void ResolvedParameterForNamedServiceResolvesNamedService()
        {
            var cb = new ContainerBuilder();
            cb.RegisterInstance((object)'a').Named<char>("character");
            cb.RegisterType<string>()
                .UsingConstructor(typeof(char), typeof(int))
                .WithParameter(new TypedParameter(typeof(int), 5))
                .WithParameter(ResolvedParameter.ForNamed<char>("character"));
            var c = cb.Build();
            var s = c.Resolve<string>();
            Assert.AreEqual("aaaaa", s);
        }

        [Test]
        public void AResolvedParameterForAKeyedServiceMatchesParametersOfTheServiceTypeWhenTheKeyedServiceIsAvailable()
        {
            var k = new object();
            var builder = new ContainerBuilder();
            builder.RegisterInstance((object) 'a').Keyed<char>(k);
            var container = builder.Build();
            var rp = ResolvedParameter.ForKeyed<char>(k);
            var cp = GetCharParameter();
            Func<object> vp;
            Assert.That(rp.CanSupplyValue(cp, container, out vp));
        }

        [Test]
        public void AResolvedParameterForAKeyedServiceDoesNotMatcheParametersOfTheServiceTypeWhenTheKeyedServiceIsUnavailable()
        {
            var rp = ResolvedParameter.ForKeyed<char>(new object());
            var cp = GetCharParameter();
            Func<object> vp;
            var canSupply = rp.CanSupplyValue(cp, new ContainerBuilder().Build(), out vp);
            Assert.That(canSupply, Is.False);
        }

        static ParameterInfo GetCharParameter()
        {
            return typeof(string)
                .GetConstructor(new[] {typeof (char), typeof (int)})
                .GetParameters()
                .First();
        }
    }
}


text:
package edu.usu.sdl.openstorefront.core.model.search;

import edu.usu.sdl.openstorefront.core.view.ComponentSearchView;
import edu.usu.sdl.openstorefront.validation.ValidationResult;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author dshurtleff
 */
public class AdvanceSearchResult
{

	private List<ComponentSearchView> results = new ArrayList<>();
	private ValidationResult validationResult = new ValidationResult();
	private long totalNumber;

	public AdvanceSearchResult()
	{
	}

	public List<ComponentSearchView> getResults()
	{
		return results;
	}

	public void setResults(List<ComponentSearchView> results)
	{
		this.results = results;
	}

	public ValidationResult getValidationResult()
	{
		return validationResult;
	}

	public void setValidationResult(ValidationResult validationResult)
	{
		this.validationResult = validationResult;
	}

	public long getTotalNumber()
	{
		return totalNumber;
	}

	public void setTotalNumber(long totalNumber)
	{
		this.totalNumber = totalNumber;
	}

}


text:
@interface DemoTextViewController ()
- (void)_segmentedControlChanged:(id)sender;

- (void)linkPushed:(DTLinkButton *)button;
- (void)linkLongPressed:(UILongPressGestureRecognizer *)gesture;
- (void)debugButton:(UIBarButtonItem *)sender;

@property (nonatomic, retain) NSMutableSet *mediaPlayers;

@end

@implementation DemoTextViewController

#pragma mark NSObject

- (id)init {
	if ((self = [super init])) {
		NSArray *items = [[NSArray alloc] initWithObjects:@"View", @"Ranges", @"Chars", @"Data", nil];
		_segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
		[items release];

		_segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
		_segmentedControl.selectedSegmentIndex = 0;
		[_segmentedControl addTarget:self action:@selector(_segmentedControlChanged:) forControlEvents:UIControlEventValueChanged];
		self.navigationItem.titleView = _segmentedControl;

		// toolbar
		UIBarButtonItem *spacer = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
		UIBarButtonItem *debug = [[[UIBarButtonItem alloc] initWithTitle:@"Debug Frames" style:UIBarButtonItemStyleBordered target:self action:@selector(debugButton:)] autorelease];
		NSArray *toolbarItems = [NSArray arrayWithObjects:spacer, debug, nil];
		[self setToolbarItems:toolbarItems];
	}
	return self;
}

- (void)dealloc
{
	[_fileName release];
	[_segmentedControl release];
	[_textView release];
	[_rangeView release];
	[_charsView release];
	[_dataView release];
	[baseURL release];

	[lastActionLink release];
	[mediaPlayers release];

	[super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return YES;
}

#pragma mark UIViewController

- (void)loadView {
	[super loadView];

	CGRect frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height);

	// Create data view
	_dataView = [[UITextView alloc] initWithFrame:frame];
	_dataView.editable = NO;
	_dataView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	[self.view addSubview:_dataView];

	// Create chars view
	_charsView = [[UITextView alloc] initWithFrame:frame];
	_charsView.editable = NO;
	_charsView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	[self.view addSubview:_charsView];

	// Create range view
	_rangeView = [[UITextView alloc] initWithFrame:frame];
	_rangeView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	_rangeView.editable = NO;
	[self.view addSubview:_rangeView];

	// Create text view
    [DTAttributedTextContentView setLayerClass:[CATiledLayer class]];
	_textView = [[DTAttributedTextView alloc] initWithFrame:frame];
	_textView.textDelegate = self;
	_textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	[self.view addSubview:_textView];
}

- (void)viewDidLoad {
    [super viewDidLoad];

	// Load HTML data
	NSString *readmePath = [[NSBundle mainBundle] pathForResource:_fileName ofType:nil];
	NSString *html = [NSString stringWithContentsOfFile:readmePath encoding:NSUTF8StringEncoding error:NULL];
	NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];

	// Create attributed string from HTML
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:1.0], NSTextSizeMultiplierDocumentOption,
                             @"Times New Roman", DTDefaultFontFamily,  @"purple", DTDefaultLinkColor, nil]; // @"green",DTDefaultTextColor,

	NSAttributedString *string = [[NSAttributedString alloc] initWithHTML:data options:options documentAttributes:NULL];

	// Display string
    _textView.contentView.edgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
	_textView.attributedString = string;

	// Data view
	_dataView.text = [data description];

    [string release];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];

	CGRect bounds = self.view.bounds;
	_textView.frame = bounds;

	[self _segmentedControlChanged:nil];
	[_textView setContentInset:UIEdgeInsetsMake(0, 0, 44, 0)];
	[_textView setScrollIndicatorInsets:UIEdgeInsetsMake(0, 0, 44, 0)];
	[self.navigationController setToolbarHidden:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
	[super viewDidAppear:animated];

	// now the bar is up so we can autoresize again
	_textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    // fill other tabs
    // Create range view
	NSMutableString *dumpOutput = [[NSMutableString alloc] init];
	NSDictionary *attributes = nil;
	NSRange effectiveRange = NSMakeRange(0, 0);

    if ([_textView.attributedString length])
    {

        while ((attributes = [_textView.attributedString attributesAtIndex:effectiveRange.location effectiveRange:&effectiveRange]))
        {
            [dumpOutput appendFormat:@"Range: (%d, %d), %@\n\n", effectiveRange.location, effectiveRange.length, attributes];
            effectiveRange.location += effectiveRange.length;

            if (effectiveRange.location >= [_textView.attributedString length])
            {
                break;
            }
        }
    }
	_rangeView.text = dumpOutput;

	// Create characters view
	[dumpOutput setString:@""];
	NSData *dump = [[_textView.attributedString string] dataUsingEncoding:NSUTF8StringEncoding];
	for (NSInteger i = 0; i < [dump length]; i++)
	{
		char *bytes = (char *)[dump bytes];
		char b = bytes[i];

		[dumpOutput appendFormat:@"%x %c\n", b, b];
	}
	_charsView.text = dumpOutput;
	[dumpOutput release];
}

- (void)viewWillDisappear:(BOOL)animated;
{
	[self.navigationController setToolbarHidden:YES animated:YES];

	// stop all playing media
	for (MPMoviePlayerController *player in self.mediaPlayers)
	{
		[player stop];
	}

	[super viewWillDisappear:animated];
}

#pragma mark Private Methods

- (void)_segmentedControlChanged:(id)sender {
	UIScrollView *selectedView = _textView;

	switch (_segmentedControl.selectedSegmentIndex) {
		case 1:
			selectedView = _rangeView;
			break;
		case 2:
			selectedView = _charsView;
			break;
		case 3:
			selectedView = _dataView;
			break;
	}

	[self.view bringSubviewToFront:selectedView];
	[selectedView flashScrollIndicators];
}

#pragma mark Custom Views on Text
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForLink:(NSURL *)url identifier:(NSString *)identifier frame:(CGRect)frame
{
	DTLinkButton *button = [[[DTLinkButton alloc] initWithFrame:frame] autorelease];
	button.url = url;
	button.minimumHitSize = CGSizeMake(25, 25); // adjusts it's bounds so that button is always large enough
	button.guid = identifier;

	// use normal push action for opening URL
	[button addTarget:self action:@selector(linkPushed:) forControlEvents:UIControlEventTouchUpInside];

	// demonstrate combination with long press
	UILongPressGestureRecognizer *longPress = [[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(linkLongPressed:)] autorelease];
	[button addGestureRecognizer:longPress];

	return button;
}

- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame
{
	if (attachment.contentType == DTTextAttachmentTypeVideoURL)
	{
		NSURL *url = (id)attachment.contentURL;

		// we could customize the view that shows before playback starts
		UIView *grayView = [[[UIView alloc] initWithFrame:frame] autorelease];
		grayView.backgroundColor = [UIColor blackColor];

		MPMoviePlayerController *player =[[[MPMoviePlayerController alloc] initWithContentURL:url] autorelease];

        NSString *airplayAttr = [attachment.attributes objectForKey:@"x-webkit-airplay"];
        if ([airplayAttr isEqualToString:@"allow"])
        {
            if ([player respondsToSelector:@selector(setAllowsAirPlay:)])
            {
                player.allowsAirPlay = YES;
            }
        }

        NSString *controlsAttr = [attachment.attributes objectForKey:@"controls"];
        if (controlsAttr)
        {
            player.controlStyle = MPMovieControlStyleEmbedded;
        }
        else
        {
            player.controlStyle = MPMovieControlStyleNone;
        }

        NSString *loopAttr = [attachment.attributes objectForKey:@"loop"];
        if (loopAttr)
        {
            player.repeatMode = MPMovieRepeatModeOne;
        }
        else
        {
            player.repeatMode = MPMovieRepeatModeNone;
        }

        NSString *autoplayAttr = [attachment.attributes objectForKey:@"autoplay"];
        if (autoplayAttr)
        {
            player.shouldAutoplay = YES;
        }
        else
        {
            player.shouldAutoplay = NO;
        }

		[player prepareToPlay];
		[self.mediaPlayers addObject:player];

		player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		player.view.frame = grayView.bounds;
		[grayView addSubview:player.view];

		return grayView;
	}
	else if (attachment.contentType == DTTextAttachmentTypeImage)
	{
		// if the attachment has a hyperlinkURL then this is currently ignored
		DTLazyImageView *imageView = [[[DTLazyImageView alloc] initWithFrame:frame] autorelease];
		if (attachment.contents)
		{
			imageView.image = attachment.contents;
		}

		// url for deferred loading
		imageView.url = attachment.contentURL;

		return imageView;
	}

	return nil;
}

#pragma mark Actions

- (void)linkPushed:(DTLinkButton *)button
{
	[[UIApplication sharedApplication] openURL:[button.url absoluteURL]];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex != actionSheet.cancelButtonIndex)
	{
		[[UIApplication sharedApplication] openURL:[self.lastActionLink absoluteURL]];
	}
}

- (void)linkLongPressed:(UILongPressGestureRecognizer *)gesture
{
	if (gesture.state == UIGestureRecognizerStateBegan)
	{
		DTLinkButton *button = (id)[gesture view];
		button.highlighted = NO;
		self.lastActionLink = button.url;

		if ([[UIApplication sharedApplication] canOpenURL:[button.url absoluteURL]])
		{
			UIActionSheet *action = [[[UIActionSheet alloc] initWithTitle:[[button.url absoluteURL] description] delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Open in Safari", nil] autorelease];
			[action showFromRect:button.frame inView:button.superview animated:YES];
		}
	}
}

- (void)debugButton:(UIBarButtonItem *)sender
{
	_textView.contentView.drawDebugFrames = !_textView.contentView.drawDebugFrames;
    [DTCoreTextLayoutFrame setShouldDrawDebugFrames:_textView.contentView.drawDebugFrames];
    [self.view setNeedsDisplay];
}

#pragma mark Properties

- (NSMutableSet *)mediaPlayers
{
	if (!mediaPlayers)
	{
		mediaPlayers = [[NSMutableSet alloc] init];
	}

	return mediaPlayers;
}

@synthesize fileName = _fileName;
@synthesize lastActionLink;
@synthesize mediaPlayers;
@synthesize baseURL;

@end


text:
<?php

namespace Symfony\Component\Form\FieldFactory;

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Automatically creates form fields for properties of an object
 *
 * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
 */
interface FieldFactoryInterface
{
    /**
     * Returns a field for a given property name
     *
     * @param  object $object     The object to create a field for
     * @param  string $property   The name of the property
     * @param  array $options     Custom options for creating the field
     * @return FieldInterface     A field instance
     */
    function getInstance($object, $property, array $options = array());
}


text:
package hr.igord.data;

import java.util.Date;
import org.joda.time.DateTime;

public class AnimalData {

    private String name;
    private int age;
    private DateTime lastUpdate;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

//    public void setAge(int age) {
//        if (age != 5) { // invalid age
//            this.age = -1;
//        } else {
//            this.age = age;
//        }
//    }

    public DateTime getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(Date lastUpdateProxy) {
        this.lastUpdate = new DateTime(lastUpdateProxy);
    }

    public void setLastUpdate(DateTime lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    @Override
    public String toString() {
        return "AnimalData{" + "name=" + name + ", age=" + age + ", lastUpdate=" + lastUpdate + '}';
    }

}

//
//package hr.igord.data;
//
//import java.util.Date;
//import org.joda.time.DateTime;
//
//public class AnimalData {
//
//    private String name;
//    private int age;
//    private Date lastUpdateProxy;
//    private DateTime lastUpdate;
//
//    public String getName() {
//        return name;
//    }
//
//    public void setName(String name) {
//        this.name = name;
//    }
//
//    public int getAge() {
//        return age;
//    }
//
//    public void setAge(int age) {
//        this.age = age;
//    }
//
//    public DateTime getLastUpdate() {
//        return lastUpdate;
//    }
//
//    public void setLastUpdateProxy(Date lastUpdateProxy) {
//        this.lastUpdate = new DateTime(lastUpdateProxy);
//    }
//
//    public void setLastUpdate(DateTime lastUpdate) {
//        this.lastUpdate = lastUpdate;
//    }
//
//    @Override
//    public String toString() {
//        return "AnimalData{" + "name=" + name + ", age=" + age + ", lastUpdate=" + lastUpdate + '}';
//    }
//
//}

//
//package hr.igord.data;
//
//import java.util.Date;
//import org.joda.time.DateTime;
//
//public class AnimalData {
//
//    private String name;
//    private int age;
//    private Date lastUpdateProxy;
//    private DateTime lastUpdate;
////    private LocalTime lastUpdate;
//
//    public String getName() {
//        return name;
//    }
//
//    public void setName(String name) {
//        this.name = name;
//    }
//
//    public int getAge() {
//        return age;
//    }
//
//    public void setAge(int age) {
//        this.age = age;
//    }
//
////    public Date getLastUpdate() {
////        return lastUpdate;
////    }
////
////    public void setLastUpdate(Date lastUpdate) {
////        this.lastUpdate = lastUpdate;
////    }
////
////    @Override
////    public String toString() {
////        return "AnimalData{" + "name=" + name + ", age=" + age + ", lastUpdate=" + lastUpdate.toGMTString() + '}';
////    }
//
////    public LocalTime getLastUpdate() {
////        return lastUpdate;
////    }
////
////    public void setLastUpdate(LocalTime lastUpdate) {
////        this.lastUpdate = lastUpdate;
////    }
////
////    @Override
////    public String toString() {
////        return "AnimalData{" + "name=" + name + ", age=" + age + ", lastUpdate=" + lastUpdate + '}';
////    }
//
//    public DateTime getLastUpdate() {
//        return lastUpdate;
//    }
//
////    public Date getLastUpdateProxy() {
////        throw new UnsupportedOperationException("Proxy");
////    }
//
//    public void setLastUpdateProxy(Date lastUpdateProxy) {
//        this.lastUpdate = new DateTime(lastUpdateProxy);
//    }
//
//    public void setLastUpdate(DateTime lastUpdate) {
//        this.lastUpdate = lastUpdate;
//    }
//
//    @Override
//    public String toString() {
//        return "AnimalData{" + "name=" + name + ", age=" + age + ", lastUpdate=" + lastUpdate + '}';
//    }
//
//}


text:
@implementation ATMSGCell

@end


text:
package jfxtras.internal.scene.control.skin.window;

import javafx.animation.Animation;
import javafx.animation.Animation.Status;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.collections.ListChangeListener.Change;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.SkinBase;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Glow;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.util.Duration;
import jfxtras.scene.control.window.SelectableNode;
import jfxtras.scene.control.window.Window;
import jfxtras.scene.control.window.WindowIcon;

/**
 *
 * @author Michael Hoffer <info@michaelhoffer.de>
 */
public class DefaultWindowSkin extends SkinBase<Window> {

    private double mouseX;
    private double mouseY;
    private double nodeX = 0;
    private double nodeY = 0;
    private boolean dragging = false;
    private boolean zoomable = true;
    private double minScale = 0.1;
    private double maxScale = 10;
    private double scaleIncrement = 0.001;
    private ResizeMode resizeMode;
    private boolean RESIZE_TOP;
    private boolean RESIZE_LEFT;
    private boolean RESIZE_BOTTOM;
    private boolean RESIZE_RIGHT;
    private TitleBar titleBar;
    private Window control;
    private Pane root = new Pane();
    private double contentScale = 1.0;
    private double oldHeight;
    private Timeline minimizeTimeLine;

    public DefaultWindowSkin(Window w) {
        super(w);
        this.control = w;
        titleBar = new TitleBar(control);
        titleBar.setTitle("");
        init();
    }

    private void init() {

        getChildren().add(root);
        root.getChildren().add(titleBar);

        for (WindowIcon i : control.getLeftIcons()) {
            titleBar.addLeftIcon(i);
        }

        for (WindowIcon i : control.getRightIcons()) {
            titleBar.addRightIcon(i);
        }

        control.getLeftIcons().addListener(
                (ListChangeListener.Change<? extends WindowIcon> change) -> {
            while (change.next()) {
                if (change.wasPermutated()) {
                    for (int i = change.getFrom(); i < change.getTo(); ++i) {
                        //permutate
                    }
                } else if (change.wasUpdated()) {
                    //update item
                } else {
                    if (change.wasRemoved()) {
                        for (WindowIcon i : change.getRemoved()) {
                            titleBar.removeLeftIcon(i);
                        }
                    } else if (change.wasAdded()) {
                        for (WindowIcon i : change.getAddedSubList()) {
                            titleBar.addLeftIcon(i);
                        }
                    }
                }
            }
        });

        control.getRightIcons().addListener(
                (ListChangeListener.Change<? extends WindowIcon> change) -> {
            while (change.next()) {
                if (change.wasPermutated()) {
                    for (int i = change.getFrom(); i < change.getTo(); ++i) {
                        //permutate
                    }
                } else if (change.wasUpdated()) {
                    //update item
                } else {
                    if (change.wasRemoved()) {
                        for (WindowIcon i : change.getRemoved()) {
                            titleBar.removeRightIcon(i);
                        }
                    } else if (change.wasAdded()) {
                        for (WindowIcon i : change.getAddedSubList()) {
                            titleBar.addRightIcon(i);
                        }
                    }
                }
            }
        });

        control.minimizedProperty().addListener(
                (ObservableValue<? extends Boolean> ov, final Boolean oldValue, final Boolean newValue) -> {
            if (oldValue == newValue) {
                return;
            }

            boolean storeOldHeight = minimizeTimeLine == null && newValue;

            if (minimizeTimeLine != null) {
                minimizeTimeLine.stop();
                minimizeTimeLine = null;
            }

            double newHeight;

            if (newValue) {
                newHeight = titleBar.getHeight();
            } else {
                newHeight = oldHeight;
            }

            if (storeOldHeight) {
                oldHeight = control.getPrefHeight();
            }

            minimizeTimeLine = new Timeline(
                    new KeyFrame(Duration.ZERO,
                    new KeyValue(control.prefHeightProperty(), control.getPrefHeight())),
                    new KeyFrame(Duration.seconds(0.2),
                    new KeyValue(control.prefHeightProperty(), newHeight)));

            minimizeTimeLine.statusProperty().addListener(
                    (ObservableValue<? extends Status> ov2, Status oldStatus, Status newStatus) -> {
                        if (newStatus == Status.STOPPED) {
                            minimizeTimeLine = null;
                            if (newValue) {
                                control.getContentPane().setVisible(false);
                            }
                        }
            });

            minimizeTimeLine.play();
        });

        control.prefHeightProperty().addListener(new MinimizeHeightListener(control, titleBar));

        initMouseEventHandlers();

        titleBar.setTitle(control.getTitle());

        control.titleProperty().addListener((ObservableValue<? extends String> ov, String oldValue, String newValue) -> {
            titleBar.setTitle(newValue);
            control.autosize();
        });

        root.getChildren().add(control.getContentPane());
        control.getContentPane().setManaged(false);

        control.contentPaneProperty().addListener((ObservableValue<? extends Pane> ov, Pane oldValue, Pane newValue) -> {
            root.getChildren().remove(oldValue);
            root.getChildren().add(newValue);
            newValue.setManaged(false);
        });

        titleBar.setStyle(control.getStyle());

        control.styleProperty().addListener((ObservableValue<? extends String> ov, String t, String t1) -> {
            titleBar.setStyle(t1);
        });

        titleBar.getStyleClass().setAll(control.getTitleBarStyleClass());
        titleBar.getLabel().getStyleClass().setAll(control.getTitleBarStyleClass());

        control.titleBarStyleClassProperty().addListener((ObservableValue<? extends String> ov, String t, String t1) -> {
            titleBar.getStyleClass().setAll(t1);
            titleBar.getLabel().getStyleClass().setAll(t1);
        });

        titleBar.getStylesheets().setAll(control.getStylesheets());

        control.getStylesheets().addListener((Change<? extends String> change) -> {
            while (change.next()) {
                if (change.wasPermutated()) {
                    for (int i = change.getFrom(); i < change.getTo(); ++i) {
                        //permutate
                    }
                } else if (change.wasUpdated()) {
                    //update item
                } else {
                    if (change.wasRemoved()) {
                        for (String i : change.getRemoved()) {
                            titleBar.getStylesheets().remove(i);
                        }
                    } else if (change.wasAdded()) {
                        for (String i : change.getAddedSubList()) {
                            titleBar.getStylesheets().add(i);
                        }
                    }
                }
            }
        });

        control.selectedProperty().addListener(
                (ObservableValue<? extends Boolean> ov, Boolean oldValue, Boolean newValue) -> {
            if (newValue) {
                DropShadow shadow = new DropShadow(20, Color.WHITE);
                Glow effect = new Glow(0.5);
//                    shadow.setInput(effect);
                control.setEffect(effect);
            } else {
                control.setEffect(null);
            }
        });
    }

    private void initMouseEventHandlers() {

        getSkinnable().onMousePressedProperty().set((EventHandler<MouseEvent>) (MouseEvent event) -> {
            final Node n = control;

            final double parentScaleX = n.getParent().
                    localToSceneTransformProperty().getValue().getMxx();
            final double parentScaleY = n.getParent().
                    localToSceneTransformProperty().getValue().getMyy();

            mouseX = event.getSceneX();
            mouseY = event.getSceneY();

            nodeX = n.getLayoutX() * parentScaleX;
            nodeY = n.getLayoutY() * parentScaleY;

            if (control.isMoveToFront()) {
                control.toFront();
            }
        });

        //Event Listener for MouseDragged
        getSkinnable().onMouseDraggedProperty().set((EventHandler<MouseEvent>) (MouseEvent event) -> {
            final Node n = control;

            final double parentScaleX = n.getParent().
                    localToSceneTransformProperty().getValue().getMxx();
            final double parentScaleY = n.getParent().
                    localToSceneTransformProperty().getValue().getMyy();

            final double scaleX = n.localToSceneTransformProperty().
                    getValue().getMxx();
            final double scaleY = n.localToSceneTransformProperty().
                    getValue().getMyy();

            Bounds boundsInScene =
                    control.localToScene(control.getBoundsInLocal());

            double sceneX = boundsInScene.getMinX();
            double sceneY = boundsInScene.getMinY();

            double offsetX = event.getSceneX() - mouseX;
            double offsetY = event.getSceneY() - mouseY;

            if (resizeMode == ResizeMode.NONE && control.isMovable()) {

                nodeX += offsetX;
                nodeY += offsetY;

                double scaledX = nodeX * 1 / parentScaleX;
                double scaledY = nodeY * 1 / parentScaleY;

                double offsetForAllX = scaledX - n.getLayoutX();
                double offsetForAllY = scaledY - n.getLayoutY();

                n.setLayoutX(scaledX);
                n.setLayoutY(scaledY);

                dragging = true;

            } else {

                double width = n.getBoundsInLocal().getMaxX()
                        - n.getBoundsInLocal().getMinX();
                double height = n.getBoundsInLocal().getMaxY()
                        - n.getBoundsInLocal().getMinY();

                if (RESIZE_TOP) {
//                        System.out.println("TOP");

                    double insetOffset = getSkinnable().getInsets().getTop() / 2;

                    double yDiff =
                            sceneY / parentScaleY
                            + insetOffset
                            - event.getSceneY() / parentScaleY;

                    double newHeight = control.getPrefHeight() + yDiff;

                    if (newHeight > control.minHeight(0)) {
                        control.setLayoutY(control.getLayoutY() - yDiff);
                        control.setPrefHeight(newHeight);
                    }
                }
                if (RESIZE_LEFT) {
//                        System.out.println("LEFT");

                    double insetOffset = getSkinnable().getInsets().getLeft() / 2;

                    double xDiff = sceneX / parentScaleX
                            + insetOffset
                            - event.getSceneX() / parentScaleX;

                    double newWidth = control.getPrefWidth() + xDiff;

                    if (newWidth > Math.max(control.minWidth(0),
                            control.getContentPane().minWidth(0))) {
                        control.setLayoutX(control.getLayoutX() - xDiff);
                        control.setPrefWidth(newWidth);
                    } else {
                        //
                    }
                }

                if (RESIZE_BOTTOM) {
//                        System.out.println("BOTTOM");

                    double insetOffset = getSkinnable().getInsets().getBottom() / 2;

                    double yDiff = event.getSceneY() / parentScaleY
                            - sceneY / parentScaleY - insetOffset;

                    double newHeight = yDiff;

                    newHeight = Math.max(
                            newHeight, control.minHeight(0));

                    if (newHeight < control.maxHeight(0)) {
                        control.setPrefHeight(newHeight);
                    }
                }
                if (RESIZE_RIGHT) {

                    double insetOffset = getSkinnable().getInsets().getRight() / 2;

                    double xDiff = event.getSceneX() / parentScaleX
                            - sceneX / parentScaleY - insetOffset;

                    double newWidth = xDiff;

                    newWidth = Math.max(
                            newWidth,
                            Math.max(control.getContentPane().minWidth(0),
                            control.minWidth(0)));

                    if (newWidth < control.maxWidth(0)) {
                        control.setPrefWidth(newWidth);
                    }
                }
            }

            mouseX = event.getSceneX();
            mouseY = event.getSceneY();
        });

        getSkinnable().onMouseClickedProperty().set((EventHandler<MouseEvent>) (MouseEvent event) -> {
            dragging = false;
        });

        getSkinnable().onMouseMovedProperty().set((EventHandler<MouseEvent>) (MouseEvent t) -> {
            if (control.isMinimized() || !control.isResizableWindow()) {

                RESIZE_TOP = false;
                RESIZE_LEFT = false;
                RESIZE_BOTTOM = false;
                RESIZE_RIGHT = false;

                resizeMode = ResizeMode.NONE;

                return;
            }

            final Node n = control;

            final double parentScaleX = n.getParent().localToSceneTransformProperty().getValue().getMxx();
            final double parentScaleY = n.getParent().localToSceneTransformProperty().getValue().getMyy();

            final double scaleX = n.localToSceneTransformProperty().getValue().getMxx();
            final double scaleY = n.localToSceneTransformProperty().getValue().getMyy();

            final double border = control.getResizableBorderWidth() * scaleX;

            double diffMinX = Math.abs(n.getLayoutBounds().getMinX() - t.getX() + getSkinnable().getInsets().getLeft());
            double diffMinY = Math.abs(n.getLayoutBounds().getMinY() - t.getY() + getSkinnable().getInsets().getTop());
            double diffMaxX = Math.abs(n.getLayoutBounds().getMaxX() - t.getX() - getSkinnable().getInsets().getRight());
            double diffMaxY = Math.abs(n.getLayoutBounds().getMaxY() - t.getY() - getSkinnable().getInsets().getBottom());

            boolean left = diffMinX * scaleX < Math.max(border, getSkinnable().getInsets().getLeft() / 2 * scaleX);
            boolean top = diffMinY * scaleY < Math.max(border, getSkinnable().getInsets().getTop() / 2 * scaleY);
            boolean right = diffMaxX * scaleX < Math.max(border, getSkinnable().getInsets().getRight() / 2 * scaleX);
            boolean bottom = diffMaxY * scaleY < Math.max(border, getSkinnable().getInsets().getBottom() / 2 * scaleY);

            RESIZE_TOP = false;
            RESIZE_LEFT = false;
            RESIZE_BOTTOM = false;
            RESIZE_RIGHT = false;

            if (left && !top && !bottom) {
                n.setCursor(Cursor.W_RESIZE);
                resizeMode = ResizeMode.LEFT;
                RESIZE_LEFT = true;
            } else if (left && top && !bottom) {
                n.setCursor(Cursor.NW_RESIZE);
                resizeMode = ResizeMode.TOP_LEFT;
                RESIZE_LEFT = true;
                RESIZE_TOP = true;
            } else if (left && !top && bottom) {
                n.setCursor(Cursor.SW_RESIZE);
                resizeMode = ResizeMode.BOTTOM_LEFT;
                RESIZE_LEFT = true;
                RESIZE_BOTTOM = true;
            } else if (right && !top && !bottom) {
                n.setCursor(Cursor.E_RESIZE);
                resizeMode = ResizeMode.RIGHT;
                RESIZE_RIGHT = true;
            } else if (right && top && !bottom) {
                n.setCursor(Cursor.NE_RESIZE);
                resizeMode = ResizeMode.TOP_RIGHT;
                RESIZE_RIGHT = true;
                RESIZE_TOP = true;
            } else if (right && !top && bottom) {
                n.setCursor(Cursor.SE_RESIZE);
                resizeMode = ResizeMode.BOTTOM_RIGHT;
                RESIZE_RIGHT = true;
                RESIZE_BOTTOM = true;
            } else if (top && !left && !right) {
                n.setCursor(Cursor.N_RESIZE);
                resizeMode = ResizeMode.TOP;
                RESIZE_TOP = true;
            } else if (bottom && !left && !right) {
                n.setCursor(Cursor.S_RESIZE);
                resizeMode = ResizeMode.BOTTOM;
                RESIZE_BOTTOM = true;
            } else {
                n.setCursor(Cursor.DEFAULT);
                resizeMode = ResizeMode.NONE;
            }

            control.autosize();
        });

//        setOnScroll(new EventHandler<ScrollEvent>() {
//            @Override
//            public void handle(ScrollEvent event) {
//
//                if (!isZoomable()) {
//                    return;
//                }
//
//                double scaleValue =
//                        control.getScaleY() + event.getDeltaY() * getScaleIncrement();
//
//                scaleValue = Math.max(scaleValue, getMinScale());
//                scaleValue = Math.min(scaleValue, getMaxScale());
//
//                control.setScaleX(scaleValue);
//                control.setScaleY(scaleValue);
//
//                event.consume();
//            }
//        });
    }

    /**
     * @return the zoomable
     */
    public boolean isZoomable() {
        return zoomable;
    }

    /**
     * @param zoomable the zoomable to set
     */
    public void setZoomable(boolean zoomable) {
        this.zoomable = zoomable;
    }

    /**
     * @return the dragging
     */
    protected boolean isDragging() {
        return dragging;
    }

    public void removeNode(Node n) {
        getChildren().remove(n);
    }

    /**
     * @return the minScale
     */
    public double getMinScale() {
        return minScale;
    }

    /**
     * @param minScale the minScale to set
     */
    public void setMinScale(double minScale) {
        this.minScale = minScale;
    }

    /**
     * @return the maxScale
     */
    public double getMaxScale() {
        return maxScale;
    }

    /**
     * @param maxScale the maxScale to set
     */
    public void setMaxScale(double maxScale) {
        this.maxScale = maxScale;
    }

    /**
     * @return the scaleIncrement
     */
    public double getScaleIncrement() {
        return scaleIncrement;
    }

    /**
     * @param scaleIncrement the scaleIncrement to set
     */
    public void setScaleIncrement(double scaleIncrement) {
        this.scaleIncrement = scaleIncrement;
    }

    @Override
    protected void layoutChildren(double x, double y, double w, double h) {

        super.layoutChildren(x, y, w, h);

        root.relocate(0, 0);
        root.resize(root.getWidth()
                + getSkinnable().getInsets().getLeft() + getSkinnable().getInsets().getRight(),
                root.getHeight()
                + getSkinnable().getInsets().getTop() + getSkinnable().getInsets().getBottom());

        titleBar.relocate(0, 0);
        double titleBarWidth = titleBar.prefWidth(0);
        double windowWidth = root.getWidth();

//        if (titleBarWidth > windowWidth) {
//            titleBar.setPrefWidth(titleBarWidth);
//        }

        double newTitleBarWidth =
                Math.max(
                titleBarWidth,
                windowWidth);

        titleBar.resize(newTitleBarWidth, titleBar.prefHeight(0));

        double leftAndRight = getSkinnable().getInsets().getLeft() + getSkinnable().getInsets().getRight();
        double topAndBottom = getSkinnable().getInsets().getTop() + getSkinnable().getInsets().getBottom();

        control.getContentPane().relocate(
                getSkinnable().getInsets().getLeft(),
                titleBar.prefHeight(0));

        double contentWidth = root.getWidth() - leftAndRight;
        double contentHeight = root.getHeight() - getSkinnable().getInsets().getBottom() - titleBar.prefHeight(0);

        control.getContentPane().resize(
                contentWidth,
                contentHeight);

        titleBar.layoutChildren();
    }

    @Override
    protected double computeMinWidth(double width, double topInset, double rightInset, double bottomInset, double leftInset) {

        double result = root.minWidth(width);

        double minWidth = Math.max(titleBar.prefWidth(width),
                control.getContentPane().minWidth(width)+ getSkinnable().getInsets().getRight());

        result = Math.max(result,minWidth);

        return result;
    }

    @Override
    protected double computePrefWidth(double width, double topInset, double rightInset, double bottomInset, double leftInset) {

        return computeMinWidth(width, topInset, rightInset, bottomInset, leftInset);
    }

    @Override
    protected double computeMinHeight(double height, double topInset, double rightInset, double bottomInset, double leftInset) {

        double result = root.minHeight(height);

        double minHeight = titleBar.prefHeight(height);

        if (!control.isMinimized() && control.getContentPane().isVisible()) {
            minHeight += control.getContentPane().minHeight(height)
                    + getSkinnable().getInsets().getBottom();
        }

        result = Math.max(result, minHeight);

        return result;
    }

    static class MinimizeHeightListener implements ChangeListener<Number> {

        private final Window control;
        private final TitleBar titleBar;

        public MinimizeHeightListener(Window control, TitleBar titleBar) {
            this.control = control;
            this.titleBar = titleBar;
        }

        @Override
        public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
            if (control.isMinimized()
                    && control.getPrefHeight()
                    < titleBar.minHeight(0) + control.getContentPane().minHeight(0)) {
                control.getContentPane().setVisible(false);
//                System.out.println("v: false");
            } else if (!control.isMinimized()
                    && control.getPrefHeight()
                    >= titleBar.minHeight(0) + control.getContentPane().minHeight(0)) {
                control.getContentPane().setVisible(true);
//                System.out.println("v: true");
            }
        }
    }
}

class TitleBar extends HBox {

    public static final String DEFAULT_STYLE_CLASS = "window-titlebar";
    private final Pane leftIconPane;
    private final Pane rightIconPane;
    private final Text label = new Text();
    private final double iconSpacing = 3;
    Window control;
    // estimated size of "...",
    // is there a way to find out text dimension without rendering it
    private final double offset = 40;
    private double originalTitleWidth;

    public TitleBar(Window w) {

        this.control = w;

        setManaged(false);

        getStylesheets().setAll(w.getStylesheets());
        getStyleClass().setAll(DEFAULT_STYLE_CLASS);

        setSpacing(8);

//        label.setTextAlignment(TextAlignment.CENTER);
//        label.getStyleClass().setAll(DEFAULT_STYLE_CLASS);

        leftIconPane = new IconPane();
        rightIconPane = new IconPane();

        getChildren().add(leftIconPane);
//        getChildren().add(VFXLayoutUtil.createHBoxFiller());
        getChildren().add(label);
//        getChildren().add(VFXLayoutUtil.createHBoxFiller());
        getChildren().add(rightIconPane);

        control.boundsInParentProperty().addListener(
                (ObservableValue<? extends Bounds> ov, Bounds t, Bounds t1) -> {
            if (control.getTitle() == null
                    || getLabel().getText() == null
                    || getLabel().getText().isEmpty()) {
                return;
            }

            double maxIconWidth = Math.max(
                    leftIconPane.getWidth(), rightIconPane.getWidth());

            if (!control.getTitle().equals(getLabel().getText())) {
                if (originalTitleWidth
                        + maxIconWidth * 2 + offset < getWidth()) {
                    getLabel().setText(control.getTitle());
                }
            } else if (!"...".equals(getLabel().getText())) {
                if (originalTitleWidth
                        + maxIconWidth * 2 + offset >= getWidth()) {
                    getLabel().setText("...");
                }
            }
        });

    }

    public void setTitle(String title) {
        getLabel().setText(title);

        originalTitleWidth = getLabel().getBoundsInParent().getWidth();

        double maxIconWidth = Math.max(
                leftIconPane.getWidth(), rightIconPane.getWidth());

        if (originalTitleWidth
                + maxIconWidth * 2 + offset >= getWidth()) {
            getLabel().setText("...");
        }
    }

    public String getTitle() {
        return getLabel().getText();
    }

    public void addLeftIcon(Node n) {
        leftIconPane.getChildren().add(n);
    }

    public void addRightIcon(Node n) {
        rightIconPane.getChildren().add(n);
    }

    public void removeLeftIcon(Node n) {
        leftIconPane.getChildren().remove(n);
    }

    public void removeRightIcon(Node n) {
        rightIconPane.getChildren().remove(n);
    }

    @Override
    protected double computeMinWidth(double h) {
        double result = super.computeMinWidth(h);

        double iconWidth =
                Math.max(
                leftIconPane.prefWidth(h),
                rightIconPane.prefWidth(h)) * 2;

        result = Math.max(result,
                iconWidth
                //                + getLabel().prefWidth(h)
                + getInsets().getLeft()
                + getInsets().getRight());

        return result + iconSpacing * 2 + offset;
    }

    @Override
    protected double computePrefWidth(double h) {
        return computeMinWidth(h);
    }

    @Override
    protected void layoutChildren() {
        super.layoutChildren();

        leftIconPane.resizeRelocate(getInsets().getLeft(), getInsets().getTop(),
                leftIconPane.prefWidth(USE_PREF_SIZE),
                getHeight() - getInsets().getTop() - getInsets().getBottom());

        rightIconPane.resize(rightIconPane.prefWidth(USE_PREF_SIZE),
                getHeight() - getInsets().getTop() - getInsets().getBottom());
        rightIconPane.relocate(getWidth() - rightIconPane.getWidth() - getInsets().getRight(),
                getInsets().getTop());
    }

    /**
     * @return the label
     */
    public final Text getLabel() {
        return label;
    }

    private static class IconPane extends Pane {

        private final double spacing = 2;

        public IconPane() {
            setManaged(false);
            //
            setPrefWidth(USE_COMPUTED_SIZE);
            setMinWidth(USE_COMPUTED_SIZE);
        }

        @Override
        protected void layoutChildren() {

            int count = 0;

            double width = getHeight();
            double height = getHeight();

            for (Node n : getManagedChildren()) {

                double x = (width + spacing) * count;

                n.resizeRelocate(x, 0, width, height);

                count++;
            }
        }

        @Override
        protected double computeMinWidth(double h) {
            return getHeight() * getChildren().size()
                    + spacing * (getChildren().size() - 1);
        }

        @Override
        protected double computeMaxWidth(double h) {
            return computeMinWidth(h);
        }

        @Override
        protected double computePrefWidth(double h) {
            return computeMinWidth(h);
        }
    }
}

// TODO do we still need this enum?
enum ResizeMode {

    NONE,
    TOP,
    LEFT,
    BOTTOM,
    RIGHT,
    TOP_LEFT,
    TOP_RIGHT,
    BOTTOM_LEFT,
    BOTTOM_RIGHT
}


text:
import { Component } from 'react';
import PropTypes from 'prop-types';
import { withThrottle } from '../utils/withThrottle';

class RawResizeListener extends Component {
  static propTypes = {
    callback: PropTypes.func.isRequired,
    throttleFn: PropTypes.func.isRequired,
  }

  constructor(props) {
    super(props);
    const { callback, throttleFn } = this.props;
    this.cb = throttleFn(callback);
  }

  componentDidMount() {
    window.addEventListener('resize', this.cb);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.cb);
  }

  render() {
    return null;
  }
}

export const ResizeListener = withThrottle(RawResizeListener);