text:
package fi.csc.microarray.description;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import fi.csc.microarray.description.SADLDescription.Input;
import fi.csc.microarray.description.SADLDescription.Name;
import fi.csc.microarray.description.SADLDescription.Output;
import fi.csc.microarray.description.SADLDescription.Parameter;
import fi.csc.microarray.description.SADLSyntax.InputType;
import fi.csc.microarray.description.SADLSyntax.ParameterType;
import fi.csc.microarray.description.SADLTokeniser.TokenType;
import fi.csc.microarray.exception.MicroarrayException;

/**
 * <p>
 * Parses SADL analysis descriptions. SADL stands for Simple Analysis
 * Description Language. It is used to manage analysis description data inside
 * the Chipster system. Parsing is event based (cf. SAX).
 * </p>
 *
 * @see fi.csc.microarray.description.SADLSyntax
 *
 * @author Aleksi Kallio
 */
public class SADLParser {

	/**
	 * Logger for this class (debugging).
	 */
	private static final Logger logger = Logger.getLogger(SADLParser.class);

	/**
	 * Parse failure caused by illegal input data (bad SADL).
	 */
	@SuppressWarnings("serial")
	public static class ParseException extends MicroarrayException {
		public ParseException(String msg) {
			super(msg);
		}

		public ParseException(String msg, String filename) {
			super(msg + (filename != null ? (" (in " + filename + ")") : ""));
		}
	}

	private String unitName;
	private HashMap<String, InputType> inputTypeMap = new HashMap<String, InputType>();

	public static String generateOperationIdentifier(String category, String name) {
		return "\"" + category + "\"/\"" + name + "\"";
	}

	public SADLParser() {
		this(null);
	}

	public SADLParser(String filename) {
		this.unitName = filename;
		addInputType(GenericInputTypes.GENERIC);
	}

	public SADLDescription parse(String sadlString) throws ParseException {

		SADLTokeniser tokens = new SADLTokeniser(sadlString, unitName);
		return parseTool(tokens);
	}

	public List<SADLDescription> parseMultiple(String sadlString) throws ParseException {

		LinkedList<SADLDescription> descriptions = new LinkedList<SADLDescription>();
		SADLTokeniser tokens = new SADLTokeniser(sadlString, unitName);

		// for avoiding excessive logging in case of parse error
		boolean parsingPreviousSuccessful = true;
		while (tokens.hasNext()) {
			try {
				descriptions.add(parseTool(tokens));
				parsingPreviousSuccessful = true;
			} catch (ParseException pe) {
				pe.printStackTrace();
				if (parsingPreviousSuccessful) {
					descriptions.removeLast();
					logger.error("Could not parse description. ", pe);

				}
				parsingPreviousSuccessful = false;
			}
		}

		return descriptions;
	}

	public void addInputType(InputType type) {
		this.inputTypeMap.put(type.getName(), type);
	}

	/**
	 * Parsing is implemented with recursive descent algorithm (with 1 token
	 * look-a-head).
	 */
	private SADLDescription parseTool(SADLTokeniser tokens) throws ParseException {
		// read first line (analysis)
		skip(tokens, SADLSyntax.KEYWORD_TOOL);

		// read analysis stuff
		Name name = parseName(tokens);
		SADLDescription description = new SADLDescription(name);

		if (tokens.peekType() == TokenType.DESCRIPTION) {
			description.setDescription(tokens.next());
		}

		// read possible inputs
		while (nextTokenIs(tokens, SADLSyntax.KEYWORD_INPUT)) {
			skip(tokens, SADLSyntax.KEYWORD_INPUT);
			Input input = parseInput(tokens, description);
			description.addInput(input);
		}

		// read possible outputs
		while (nextTokenIs(tokens, SADLSyntax.KEYWORD_OUTPUT)) {
			skip(tokens, SADLSyntax.KEYWORD_OUTPUT);
			description.addOutput(parseOutput(tokens));
		}

		// read possible parameters
		while (nextTokenIs(tokens, SADLSyntax.KEYWORD_PARAMETER)) {
			skip(tokens, SADLSyntax.KEYWORD_PARAMETER);
			Parameter parameter = parseParameter(tokens);
			description.addParameter(parameter);
		}

		// read possible runtime
		while (nextTokenIs(tokens, SADLSyntax.KEYWORD_RUNTIME)) {
			skip(tokens, SADLSyntax.KEYWORD_RUNTIME);
			String runtime = parseRuntime(tokens);
			description.setRuntime(runtime);
		}

		// read possible slots
		while (nextTokenIs(tokens, SADLSyntax.KEYWORD_SLOTS)) {
			skip(tokens, SADLSyntax.KEYWORD_SLOTS);
			int slotCount = parseInt(tokens);
			description.setSlotCount(slotCount);
		}

		// check that no trailing content was left behind
		if (tokens.hasNext() && !nextTokenIs(tokens, SADLSyntax.KEYWORD_TOOL)) {
			// content other then new description was left
			throw new ParseException("unexpected content: " + tokens.next(), unitName);
		}

		return description;
	}

	private void skip(SADLTokeniser tokens, String token) throws ParseException {
		String next = tokens.next();
		if (!token.equals(next)) {
			throw new ParseException("expected " + token + ", not " + next, unitName);
		}
	}

	private boolean nextTokenIs(SADLTokeniser tokens, String token) {
		return tokens.hasNext() && token.equals(tokens.peek());
	}

	private Name parseName(SADLTokeniser tokens) throws ParseException {
		Name name = SADLDescription.Name.createEmptyName();

		String rawName = tokens.next();

		if (rawName.contains(SADLSyntax.NAME_SET_DESIGNATOR)) {
			name.setPrefix(rawName.substring(0, rawName.indexOf(SADLSyntax.NAME_SET_DESIGNATOR)));
			name.setPostfix(rawName.substring(
					rawName.indexOf(SADLSyntax.NAME_SET_DESIGNATOR) + SADLSyntax.NAME_SET_DESIGNATOR.length()));

		} else {
			name.setID(rawName);
		}

		if (tokens.hasNext() && SADLSyntax.NAME_SEPARATOR.equals(tokens.peek())) {
			skip(tokens, SADLSyntax.NAME_SEPARATOR); // read separator
			name.setDisplayName(tokens.next());
		}

		if (name.getID() == null && (name.getPrefix() == null && name.getPostfix() == null)) {
			throw new ParseException("id, prefix and postfix are all null");
		}

		return name;
	}

	private String parseRuntime(SADLTokeniser tokens) throws ParseException {
		return tokens.next();
	}

	private int parseInt(SADLTokeniser tokens) throws ParseException {
		String nextToken = tokens.next();
		try {
			return Integer.parseInt(nextToken);
		} catch (NumberFormatException e) {
			throw new ParseException("slot count is not integer: " + nextToken);
		}
	}

	private Output parseOutput(SADLTokeniser tokens) throws ParseException {

		Output output = new Output();

		boolean isMeta = parseMetaIfExists(tokens);
		output.setMeta(isMeta);

		boolean isOptional = parseOptionalIfExists(tokens);
		output.setOptional(isOptional);

		output.setName(parseName(tokens));

		if (tokens.peekType() == TokenType.DESCRIPTION) {
			output.setDescription(tokens.next());
		}

		return output;
	}

	private Input parseInput(SADLTokeniser tokens, SADLDescription description) throws ParseException {

		Input input = new Input();

		boolean isMeta = parseMetaIfExists(tokens);
		input.setMeta(isMeta);

		boolean isOptional = parseOptionalIfExists(tokens);
		input.setOptional(isOptional);

		input.setName(parseName(tokens));
		skip(tokens, SADLSyntax.KEYWORD_TYPE);
		String inputTypeName = tokens.next();
		InputType inputType = inputTypeMap.get(inputTypeName);
		if (inputType == null) {
			throw new ParseException("Invalid input type: " + inputTypeName, description.getName().getID());
		}
		input.setType(inputType);

		if (tokens.peekType() == TokenType.DESCRIPTION) {
			input.setDescription(tokens.next());
		}

		return input;
	}

	private boolean parseMetaIfExists(SADLTokeniser tokens) throws ParseException {

		if (nextTokenIs(tokens, SADLSyntax.KEYWORD_META)) {
			skip(tokens, SADLSyntax.KEYWORD_META);
			return true;

		} else {
			return false;
		}
	}

	private boolean parseOptionalIfExists(SADLTokeniser tokens) throws ParseException {

		if (nextTokenIs(tokens, SADLSyntax.KEYWORD_OPTIONAL)) {
			skip(tokens, SADLSyntax.KEYWORD_OPTIONAL);
			return true;

		} else {
			return false;
		}
	}

	private Parameter parseParameter(SADLTokeniser tokens) throws ParseException {

		boolean isOptional = parseOptionalIfExists(tokens);

		Name name = parseName(tokens);

		skip(tokens, SADLSyntax.KEYWORD_TYPE);
		ParameterType type = null;
		Name[] options = null;

		if (nextTokenIs(tokens, SADLSyntax.ENUM_OPEN)) {
			options = parseEnumType(tokens);
			type = ParameterType.ENUM;

		} else {
			type = ParameterType.valueOf(tokens.next());
		}

		String from = null;
		String to = null;
		String[] defaultValues = new String[0];

		if (nextTokenIs(tokens, SADLSyntax.KEYWORD_FROM)) {
			skip(tokens, SADLSyntax.KEYWORD_FROM);
			from = tokens.next();
			this.validateFromOrToOrDefaultAsNumber(type, from, name, SADLSyntax.KEYWORD_FROM);
		}

		if (nextTokenIs(tokens, SADLSyntax.KEYWORD_TO)) {
			skip(tokens, SADLSyntax.KEYWORD_TO);
			to = tokens.next();
			this.validateFromOrToOrDefaultAsNumber(type, to, name, SADLSyntax.KEYWORD_TO);
		}

		// validate from and to relative to each other
		// from and to have been validated as numbers before
		if (from != null && to != null) {
			double fromDouble = Double.parseDouble(from);
			double toDouble = Double.parseDouble(to);
			if (toDouble < fromDouble) {
				throw new ParseException("parameter " + name.getID() + " " + SADLSyntax.KEYWORD_TO + " '" + to
						+ "' is less than " + SADLSyntax.KEYWORD_FROM + " '" + from + "'");
			}
		}

		if (nextTokenIs(tokens, SADLSyntax.KEYWORD_DEFAULT)) {
			skip(tokens, SADLSyntax.KEYWORD_DEFAULT);
			defaultValues = parseDefaultValues(tokens);

			// validate default against from and to
			if (type == ParameterType.DECIMAL || type == ParameterType.INTEGER) {
				this.validateDefaultNumber(defaultValues, name, type, from, to);
			}
		}

		Parameter parameter = new Parameter(name, type, options, from, to, defaultValues);
		parameter.setOptional(isOptional);

		if (tokens.peekType() == TokenType.DESCRIPTION) {
			parameter.setDescription(tokens.next());
		}

		return parameter;
	}

	private String[] parseDefaultValues(SADLTokeniser tokens) throws ParseException {

		LinkedList<String> list = new LinkedList<String>();
		while (true) {
			list.add(tokens.next());
			if (nextTokenIs(tokens, SADLSyntax.LIST_SEPARATOR)) {
				skip(tokens, SADLSyntax.LIST_SEPARATOR);
			} else {
				break;
			}
		}

		return list.toArray(new String[0]);
	}

	private Name[] parseEnumType(SADLTokeniser tokens) throws ParseException {

		skip(tokens, SADLSyntax.ENUM_OPEN);

		LinkedList<Name> list = new LinkedList<Name>();
		while (true) {
			list.add(parseName(tokens));
			if (nextTokenIs(tokens, SADLSyntax.ENUM_CLOSE)) {
				break;
			} else {
				skip(tokens, SADLSyntax.LIST_SEPARATOR);
			}
		}

		skip(tokens, SADLSyntax.ENUM_CLOSE);

		return list.toArray(new Name[0]);
	}

	private void validateFromOrToOrDefaultAsNumber(ParameterType type, String value, Name name,
			String fromOrToOrDefault) throws ParseException {
		if (type == ParameterType.INTEGER) {
			try {
				Integer.parseInt(value);
			} catch (NumberFormatException e) {
				throw new ParseException("parameter " + name.getID() + " has illegal " + fromOrToOrDefault + " value '"
						+ value + "', should be an integer");
			}
		} else if (type == ParameterType.DECIMAL) {
			try {
				Double.parseDouble(value);
			} catch (NumberFormatException e) {
				throw new ParseException("parameter " + name.getID() + " has illegal " + fromOrToOrDefault + " value '"
						+ value + "', should be a decimal number");
			}
		}
	}

	private void validateDefaultNumber(String[] defaultValues, Name name, ParameterType type, String from, String to)
			throws ParseException {
		// only one default for INTEGER and DECIMAL
		if (defaultValues.length != 1) {
			throw new ParseException(
					"parameter " + name.getID() + " has illegal number of defaults '" + defaultValues.length
							+ "', should be '1' for " + ParameterType.INTEGER + " " + ParameterType.DECIMAL);
		}
		String defaultString = defaultValues[0];

		// parses as an INTEGER or DECIMAL
		this.validateFromOrToOrDefaultAsNumber(type, defaultString, name, SADLSyntax.KEYWORD_DEFAULT);

		// not less than FROM
		if (from != null && Double.parseDouble(from) > Double.parseDouble(defaultString)) {
			throw new ParseException("parameter " + name.getID() + " " + SADLSyntax.KEYWORD_DEFAULT + " '"
					+ defaultString + "' is less than " + SADLSyntax.KEYWORD_FROM + " '" + from + "'");
		}

		// not greater than TO
		if (to != null && Double.parseDouble(to) < Double.parseDouble(defaultString)) {
			throw new ParseException("parameter " + name.getID() + " " + SADLSyntax.KEYWORD_DEFAULT + " '"
					+ defaultString + "' is greater than " + SADLSyntax.KEYWORD_TO + " '" + to + "'");
		}

	}

}


text:
package symlink

import (
	"os"
	"strings"
	"syscall"
	"unicode/utf16"
	"unsafe"

	"github.com/juju/errors"
)

const (
	SYMBOLIC_LINK_FLAG_DIRECTORY = 1
	// This is the equivalent of syscall.GENERIC_EXECUTION
	// Using syscall.GENERIC_EXECUTION results in an "Access denied" error
	GENERIC_EXECUTION = 33554432
	// (TODO): bogdanteleaga or anybody else:
	// Remove this once we upgrade to a go version that has it in the syscall
	// package
	FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400
)

//sys createSymbolicLink(symlinkname *uint16, targetname *uint16, flags uint32) (err error) = CreateSymbolicLinkW
//sys getFinalPathNameByHandle(handle Handle, buf *uint16, buflen uint32, flags uint32) (n uint32, err error) = GetFinalPathNameByHandleW

// New creates newname as a symbolic link to oldname.
// If there is an error, it will be of type *LinkError.
func New(oldname, newname string) error {
	fi, err := os.Stat(oldname)
	if err != nil {
		return &os.LinkError{"symlink", oldname, newname, err}
	}
	var flag uint32
	if fi.IsDir() {
		flag = SYMBOLIC_LINK_FLAG_DIRECTORY
	}

	targetp, err := getLongPath(oldname)
	if err != nil {
		return &os.LinkError{"symlink", oldname, newname, err}
	}

	linkp, err := syscall.UTF16PtrFromString(newname)
	if err != nil {
		return &os.LinkError{"symlink", oldname, newname, err}
	}

	err = createSymbolicLink(linkp, &targetp[0], flag)
	if err != nil {
		return &os.LinkError{"symlink", oldname, newname, err}
	}
	return nil
}

// Read returns the destination of the named symbolic link.
// If there is an error, it will be of type *PathError.
func Read(link string) (string, error) {
	linkp, err := getLongPath(link)
	if err != nil {
		return "", err
	}
	h, err := syscall.CreateFile(
		&linkp[0],
		syscall.GENERIC_READ,
		syscall.FILE_SHARE_READ,
		nil,
		syscall.OPEN_EXISTING,
		GENERIC_EXECUTION,
		0)
	if err != nil {
		return "", &os.PathError{"readlink", link, err}
	}
	defer syscall.CloseHandle(h)

	pathw := make([]uint16, syscall.MAX_PATH)
	n, err := getFinalPathNameByHandle(h, &pathw[0], uint32(len(pathw)), 0)
	if err != nil {
		return "", &os.PathError{"readlink", link, err}
	}
	if n > uint32(len(pathw)) {
		pathw = make([]uint16, n)
		n, err = getFinalPathNameByHandle(h, &pathw[0], uint32(len(pathw)), 0)
		if err != nil {
			return "", &os.PathError{"readlink", link, err}
		}
		if n > uint32(len(pathw)) {
			return "", &os.PathError{"readlink", link, errors.New("link length too long")}
		}
	}
	ret := string(utf16.Decode(pathw[0:n]))

	if strings.HasPrefix(ret, `\\?\`) {
		return ret[4:], nil
	}

	retp, err := getLongPath(ret)
	if err != nil {
		return "", &os.PathError{"readlink", link, err}
	}
	return syscall.UTF16ToString(retp), nil
}

func IsSymlink(path string) (bool, error) {
	var fa syscall.Win32FileAttributeData
	namep, err := syscall.UTF16PtrFromString(path)
	if err != nil {
		return false, errors.Trace(err)
	}
	err = syscall.GetFileAttributesEx(namep, syscall.GetFileExInfoStandard, (*byte)(unsafe.Pointer(&fa)))
	if err != nil {
		return false, errors.Trace(err)
	}
	return fa.FileAttributes&FILE_ATTRIBUTE_REPARSE_POINT != 0, nil
}

// getLongPath converts windows 8.1 short style paths (c:\Progra~1\foo) to full
// long paths.
func getLongPath(path string) ([]uint16, error) {
	pathp, err := syscall.UTF16FromString(path)
	if err != nil {
		return nil, err
	}

	longp := pathp
	n, err := syscall.GetLongPathName(&pathp[0], &longp[0], uint32(len(longp)))
	if err != nil {
		return nil, err
	}
	if n > uint32(len(longp)) {
		longp = make([]uint16, n)
		n, err = syscall.GetLongPathName(&pathp[0], &longp[0], uint32(len(longp)))
		if err != nil {
			return nil, err
		}
	}
	longp = longp[:n]

	return longp, nil
}

func getLongPathAsString(path string) (string, error) {
	longp, err := getLongPath(path)
	if err != nil {
		return "", err
	}
	return syscall.UTF16ToString(longp), nil
}

redpajama_set_name: RedPajamaGithub


text:
var day=new Date();
var m=day.getMonth();
var d=day.getDate();
var y=day.getFullYear();
var today=new Date(y,m,d);

var checkFlag=true;
var arrivalFlag=false;
var departureFlag=false;

var check1=document.getElementById('c1');
var check2=document.getElementById('c2');
var search=document.getElementById('searchBtn');
searchCheck();
var d1=document.getElementById('arrival');
var d2=document.getElementById('departure');
d1.setAttribute("style","background:#ffffff;");
d2.setAttribute("style","background:#ffffff;");
document.getElementById('room_type').value='single';
console.log(document.getElementById('room_type').value);
arrivalCheck();
dateCheck();
checkBoxChange();
function checkBoxChange(){
  if(!c1.checked && !c2.checked){
    document.getElementById("roomRow").setAttribute("class","form-group has-error row");
    document.getElementById("roomMsg").removeAttribute("hidden");
    console.log("NONE IS CHECKED");
    checkFlag=false;
  }
  else{
    document.getElementById("roomRow").setAttribute("class","form-group has-success row");
    document.getElementById("roomMsg").setAttribute("hidden",null);
    checkFlag=true;
  }
  var single=document.getElementById("c1").checked;
   var double=document.getElementById("c2").checked;
   var room_type=document.getElementById("room_type");
   console.log(single);
   if(single == true){
     room_type.value="single";
   }
   if(double == true){
     if(single==true){
      room_type.value+="double";
     }
     else{
      room_type.value="double";
     }

   }
   if(room_type.value == "singledouble"){
     room_type.value="sd";
   }
   console.log(room_type.value);
  searchCheck();
}
function arrivalCheck(){
  console.log("D KO YOUK TL");
  var arrival=new Date(d1.value);
  var departure=new Date(d2.value);
  if(d1.value!=""){
    if(arrival>=today){
      document.getElementById("arrivalRow").setAttribute("class","form-group has-success row");
      try{document.getElementById("arrivalMsg").setAttribute("hidden",null);}catch(e){console.log("error2");}
      arrivalFlag=true;
    }
    else {
      console.log("Must be today or later");
      document.getElementById("arrivalRow").setAttribute("class","form-group has-error row");
      document.getElementById("arrivalMsg").removeAttribute("hidden");
      arrivalFlag=false;
    }
    //arrivalFlag=true;
    try{dateCheck()}catch(e){console.log("error1"); }
  }
  searchCheck();
}
function dateCheck(){

  var arrival=new Date(d1.value);
  var departure=new Date(d2.value);
  if(d2.value!=""){
    if(departure<arrival){
      console.log("DEPARTURE FALSE");
      document.getElementById("departureRow").setAttribute("class","form-group has-error row");
      document.getElementById("departureMsg").removeAttribute("hidden");
      departureFlag=false;
    }
    else{
      console.log("DEPARTURE TRUE");
      document.getElementById("departureRow").setAttribute("class","form-group has-success row");
      try{document.getElementById("departureMsg").setAttribute("hidden",null);}catch(e){console.log("error2");}
      departureFlag=true;
    }
    searchCheck();
  }
}
function searchCheck(){
  if(arrivalFlag==true && departureFlag==true && checkFlag==true){
    console.log("all true");
    search.removeAttribute("disabled");
  }
  else{
    console.log("FALSE");
    search.setAttribute("disabled","true");
  }
}

function loginFail(){
  console.log("WIN LAR DL");
  $(function() {
  $("#loginFailModal").modal();
  });
}
// function showSuccess(){
// $("#successAlert").hide().show('medium');
// }
// function showFail(){
// $("#failAlert").hide().show()('medium');
// }
function loginClick(type){

  console.log(type);
  var usecase=document.getElementById('loginUseCase');
  usecase.value=type;

  //console.log(type);
  $(function() {
  $("#loginModal").modal();
  });
}
function searchClick(){
  $(function() {
  $("#myModal").modal();
  });
}
$('#reservationForm').parsley();


text:
package org.nd4j.parameterserver.distributed.v2.util;

import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.nd4j.common.primitives.Atomic;
import org.nd4j.common.util.SerializationUtils;
import org.nd4j.parameterserver.distributed.v2.enums.MeshBuildMode;
import org.nd4j.parameterserver.distributed.enums.NodeStatus;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
public class MeshOrganizer implements Serializable {
    private static final long serialVersionUID = 1L;

    private MeshBuildMode buildMode = MeshBuildMode.MESH;

    // this value determines max number of direct downstream connections for any given node (affects root node as well)
    public static final int MAX_DOWNSTREAMS = 8;

    // max distance from root
    public static final int MAX_DEPTH = 5;

    // just shortcut to the root node of the tree
    @Getter(AccessLevel.PUBLIC)
    private Node rootNode = new Node(true);

    // SortedSet, with sort by number of downstreams
    private transient List<Node> sortedNodes = new ArrayList<>();

    // flattened map of the tree, ID -> Node
    private transient Map<String, Node> nodeMap = new HashMap<>();

    // this field is used
    private long version = 0L;

    public MeshOrganizer() {
        for (int e = 0; e < MAX_DOWNSTREAMS; e++)
            fillQueue.add(rootNode);
    }

    @Deprecated
    public MeshOrganizer(@NonNull MeshBuildMode mode) {
        this();
        this.buildMode = mode;
    }

    // queue with future leafs
    protected transient Queue<Node> fillQueue = new LinkedTransferQueue<>();

    public long getVersion() {
        return version;
    }

    /**
     * This method adds new node to the network
     *
     * PLEASE NOTE: Default port 40123 is used
     * @param ip
     */
    public Node  addNode(@NonNull String ip) {
        return addNode(ip, 40123);
    }

    /**
     * This methods adds new node to the network
     */
    public Node addNode(@NonNull String ip, @NonNull int port) {
        val node = Node.builder()
                .id(ip)
                .port(port)
                .upstream(null)
                .build();

         return this.addNode(node);
    }

    /**
     * This method returns absolutely independent copy of this Mesh
     * @return
     */
    public MeshOrganizer clone() {
        val b = SerializationUtils.toByteArray(this);
        return SerializationUtils.fromByteArray(b);
    }

    /**
     * This method adds new node to the mesh
     *
     * @param node
     * @return
     */
    public synchronized Node addNode(@NonNull Node node) {
        version++;

        if (buildMode == MeshBuildMode.MESH) {
            // :)
            val candidate = fillQueue.poll();

            // adding node to the candidate
            candidate.addDownstreamNode(node);

            // adding this node for future connections
            for (int e = 0; e < MAX_DOWNSTREAMS; e++)
                fillQueue.add(node);

            sortedNodes.add(node);
            Collections.sort(sortedNodes);
        } else {
            rootNode.addDownstreamNode(node);
        }

        // after all we add this node to the flattened map, for future access
        nodeMap.put(node.getId(), node);

        return node;
    }

    /**
     * This method marks Node (specified by IP) as offline, and remaps its downstreams
     *
     * @param ip
     * @throws NoSuchElementException
     */
    public void markNodeOffline(@NonNull String ip) throws NoSuchElementException {
        markNodeOffline(getNodeById(ip));
    }

    /**
     * This method marks given Node as offline, remapping its downstreams
     * @param node
     */
    public  void markNodeOffline(@NonNull Node node) {
        synchronized (node) {
            node.status(NodeStatus.OFFLINE);

            for (val n : node.getDownstreamNodes())
                remapNode(n);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MeshOrganizer that = (MeshOrganizer) o;

        val bm = buildMode == that.buildMode;
        val rn = Objects.equals(rootNode, that.rootNode);

        return  bm && rn;
    }

    @Override
    public int hashCode() {
        return Objects.hash(buildMode, rootNode);
    }

    /**
     * This method reconnects given node to another node
     */
    public void remapNode(@NonNull String ip) {
        remapNode(getNodeById(ip));
    }

    /**
     * This method reconnects given node to another node
     */
    public void remapNodeAndDownstreams(@NonNull String ip) {
        remapNodeAndDownstreams(getNodeById(ip));
    }

    /**
     * This method remaps node and its downstreams somewhere
     * @param node
     */
    public synchronized void remapNodeAndDownstreams(@NonNull Node node) {
        version++;
        node.setUpstreamNode(this.rootNode);

        for (val n: node.getDownstreamNodes()) {
            this.rootNode.addDownstreamNode(n);
            node.removeFromDownstreams(n);
        }
    }

    /**
     * This method reconnects given node to another node
     */
    public synchronized void remapNode(@NonNull Node node) {
        version++;

        if (buildMode == MeshBuildMode.MESH) {
            node.getUpstreamNode().removeFromDownstreams(node);

            boolean m = false;
            for (val n : sortedNodes) {
                // we dont want to remap node to itself
                if (!Objects.equals(n, node) && n.status().equals(NodeStatus.ONLINE)) {
                    n.addDownstreamNode(node);
                    m = true;
                    break;
                }
            }

            // if we were unable to find good enough node - we'll map this node to the rootNode
            if (!m) {
                rootNode.addDownstreamNode(node);
            }

            // i hope we won't deadlock here? :)
            synchronized (this) {
                Collections.sort(sortedNodes);
            }
        } else if (buildMode == MeshBuildMode.PLAIN) {
            // nothing to do here
        }
    }

    /**
     * This method removes  node from tree
     */
    public void removeNode() {
        // TODO: implement this one
        throw new UnsupportedOperationException();
    }

    private void readObject(ObjectInputStream ois)
            throws ClassNotFoundException, IOException {
        // default deserialization
        ois.defaultReadObject();

        val desc = rootNode.getDescendantNodes();

        nodeMap = new HashMap<>();

        for (val d: desc)
            nodeMap.put(d.getId(), d);
    }

    /**
     * This method returns true, if node is known
     * @return
     */
    public boolean isKnownNode(@NonNull String id) {
        if (rootNode.getId() == null)
            return false;

        if (rootNode.getId().equals(id))
            return true;

        return nodeMap.containsKey(id);
    }

    /**
     * This method returns upstream connection for a given node
     */
    public Node getUpstreamForNode(@NonNull String ip) throws NoSuchElementException {
        val node = getNodeById(ip);

        return node.getUpstreamNode();
    }

    /**
     * This method returns downstream connections for a given node
     */
    public Collection<Node> getDownstreamsForNode(@NonNull String ip) throws NoSuchElementException {
        val node = getNodeById(ip);

        return node.getDownstreamNodes();
    }

    /**
     * This method returns total number of nodes below given one
     * @return
     */
    public long numberOfDescendantsOfNode() {
        return rootNode.numberOfDescendants();
    }

    /**
     * This method returns total number of nodes in this mesh
     *
     * PLESE NOTE: this method INCLUDES root node
     * @return
     */
    public long totalNodes() {
        return rootNode.numberOfDescendants() + 1;
    }

    /**
     * This method returns size of flattened map of nodes.
     * Suited for tests.
     *
     * @return
     */
    protected long flatSize() {
        return (long) nodeMap.size();
    }

    /**
     * This method returns our mesh as collection of nodes
     * @return
     */
    public Collection<Node> flatNodes() {
        return nodeMap.values();
    }

    /**
     * This method returns Node representing given IP
     * @return
     */
    public Node getNodeById(@NonNull String id) throws NoSuchElementException {
        if (id.equals(rootNode.getId()))
            return rootNode;

        val node = nodeMap.get(id);
        if (node == null) {
            log.info("Existing nodes: [{}]", this.flatNodes());
            throw new NoSuchElementException(id);
        }

        return node;
    }

    /**
     * This class represents basic tree node
     */
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class Node implements Serializable, Comparable<Node> {
        private static final long serialVersionUID = 1L;

        @Getter(AccessLevel.PUBLIC)
        @Setter(AccessLevel.PROTECTED)
        @Builder.Default
        private boolean rootNode = false;

        @Getter
        @Setter
        private String id;

        @Getter
        @Setter
        private int port;

        @Getter(AccessLevel.NONE)
        @Setter(AccessLevel.NONE)
        private Node upstream;

        @Getter(AccessLevel.NONE)
        @Setter(AccessLevel.NONE)
        private final List<Node> downstream = new CopyOnWriteArrayList<>();

        private AtomicInteger position = new AtomicInteger(0);

        @Getter(AccessLevel.NONE)
        @Setter(AccessLevel.NONE)
        @Builder.Default
        private Atomic<NodeStatus> status = new Atomic<>(NodeStatus.ONLINE);

        /**
         * This method returns current status of this node
         * @return
         */
        public synchronized NodeStatus status() {
            return status.get();
        }

        /**
         * This method ret
         * @param status
         */
        protected synchronized void status(@NonNull NodeStatus status) {
            this.status.set(status);
        }

        /**
         * This method return candidate for new connection
         *
         * @param node
         * @return
         */
        protected Node getNextCandidate(Node node) {
            // if there's no candidates - just connect to this node
            if (downstream.size() == 0)
                return this;

            if (node == null)
                return downstream.get(0);

            // TODO: we can get rid of flat scan here, but it's one-off step anyway...

            // we return next node after this node
            boolean b = false;
            for (val v: downstream) {
                if (b)
                    return v;

                if (Objects.equals(node, v))
                    b = true;
            }

            return null;
        }

        protected Node(boolean rootNode) {
            this.rootNode = rootNode;
        }

        /**
         * This method adds downstream node to the list of connections
         * @param node
         * @return
         */
        public Node addDownstreamNode(@NonNull Node node) {
            this.downstream.add(node);
            node.setUpstreamNode(this);
            return node;
        }

        /**
         * This method pushes node to the bottom of this node downstream
         * @param node
         * @return
         */
        protected Node pushDownstreamNode(@NonNull Node node) {
            if (isRootNode()) {
                if (downstream.size() == 0) {
                    return addDownstreamNode(node);
                } else {
                    // we should find first not full sub-branch
                    for (val d: downstream)
                        if (d.numberOfDescendants() < MeshOrganizer.MAX_DEPTH * MeshOrganizer.MAX_DOWNSTREAMS)
                            return d.pushDownstreamNode(node);

                     // if we're here - we'll have to add new branch to the root
                    return addDownstreamNode(node);
                }
            } else {
                val distance = distanceFromRoot();

                for (val d: downstream)
                    if (d.numberOfDescendants() < MeshOrganizer.MAX_DOWNSTREAMS * (MeshOrganizer.MAX_DEPTH - distance))
                        return d.pushDownstreamNode(node);

                return addDownstreamNode(node);
            }
        }

        /**
         * This method allows to set master node for this node
         * @param node
         * @return
         */
        protected Node setUpstreamNode(@NonNull Node node) {
            this.upstream = node;
            return node;
        }

        /**
         * This method returns the node this one it connected to
         * @return
         */
        public Node getUpstreamNode() {
            return upstream;
        }

        /**
         * This method returns number of downstream nodes connected to this node
         * @return
         */
        public long numberOfDescendants() {
            val cnt = new AtomicLong(downstream.size());

            for (val n: downstream)
                cnt.addAndGet(n.numberOfDescendants());

            return cnt.get();
        }

        /**
         * This method returns number of nodes that has direct connection for this node
         * @return
         */
        public long numberOfDownstreams() {
            return downstream.size();
        }

        /**
         * This method returns collection of nodes that have direct connection to this node
         * @return
         */
        public Collection<Node> getDownstreamNodes() {
            return downstream;
        }

        /**
         * This method returns all nodes
         * @return
         */
        public Collection<Node> getDescendantNodes() {
            val result = new ArrayList<Node>(getDownstreamNodes());
            for (val n:downstream)
                result.addAll(n.getDescendantNodes());

            return result;
        }

        /**
         * This method returns number of hops between
         * @return
         */
        public int distanceFromRoot() {
            if (upstream.isRootNode())
                return 1;
            else
                return upstream.distanceFromRoot() + 1;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Node node = (Node) o;

            val rn = this.upstream == null ? "root" : this.upstream.getId();
            val on = node.upstream == null ? "root" : node.upstream.getId();

            return rootNode == node.rootNode &&
                    port == node.port &&
                    Objects.equals(id, node.id) &&
                    Objects.equals(downstream, node.downstream) &&
                    Objects.equals(status, node.status) &&
                    Objects.equals(rn, on);

        }

        @Override
        public int hashCode() {
            return Objects.hash(upstream == null ? "root" : upstream.getId(), rootNode, id, port, downstream, status);
        }

        @Override
        public String toString() {
            val builder = new StringBuilder();
            if (downstream == null || downstream.size() == 0)
                builder.append("none");
            else {
                for (val n: downstream) {
                    builder.append("[").append(n.getId()).append("], ");
                }
            }
            // downstreams: [" + builder.toString() +"]; ]
            // upstreamId: [" + upstreamId + "];
            val strId = id == null ? "null" : id;
            val upstreamId = upstream == null ? "none" : upstream.getId();
            return "[ Id: ["+ strId +"]; ]";
        }

        /**
         * This method remove all downstreams for a given node
         */
        public void truncateDownstreams() {
            downstream.clear();
        }

        /**
         * This method removes
         * @param node
         */
        public synchronized void removeFromDownstreams(@NonNull Node node) {
            val r = downstream.remove(node);

            if (!r)
                throw new NoSuchElementException(node.getId());
        }

        @Override
        public int compareTo(@NonNull Node o) {
            return Long.compare(this.numberOfDownstreams(), o.numberOfDownstreams());
        }
    }
}


text:
import './ek-namespace-actions.less';
import Directive from 'directive';
import icons from '../icons';
import Controller from './ek-namespace-actions.controller';
import template from './ek-namespace-actions.html';

class NamespaceActionsDirective extends Directive {
    constructor() {
        super({ Controller, template });

        this.bindToController = {
            namespace: '='
        };
    }

    compile(tElement) {
        tElement
            .addClass('ek-namespace-actions');

        return ($scope, $element, $attrs, $controller) => {
            _.extend($scope, { icons });
            $controller.drop = $element.find('ek-drop').controller('ekDrop');
        };
    }
}

export default NamespaceActionsDirective;


text:
package com.navercorp.nbasearc.confmaster.server.cluster;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;

import com.navercorp.nbasearc.confmaster.server.MemoryObjectMapper;

public class PhysicalMachineCluster implements
        Comparable<PhysicalMachineCluster>, ClusterComponent {

    private MemoryObjectMapper mapper = new MemoryObjectMapper();

    private String clusterName;
    private String pmName;
    private String path;
    private PmClusterData persistentData;

    public PhysicalMachineCluster(byte []d, String clusterName, String pmName) {
    	persistentData = mapper.readValue(d, PmClusterData.class);
    	init(clusterName, pmName);
    }

    public PhysicalMachineCluster(String clusterName, String pmName) {
    	persistentData = new PmClusterData();
    	init(clusterName, pmName);
    }

    public void init(String clusterName, String pmName) {
    	this.pmName = pmName;
    	this.clusterName = clusterName;

        path = PathUtil.pmClusterPath(clusterName, pmName);
        setPmName(pmName);
    }

    public String getPmName() {
        return pmName;
    }

    public void setPmName(String pmName) {
        this.pmName = pmName;
    }

    public boolean isEmpty() {
        return persistentData.getPgsIdList().isEmpty() && persistentData.getGwIdList().isEmpty();
    }

    @Override
    public String toString() {
        return fullName(pmName, clusterName);
    }

    public static String fullName(String pmName, String clusterName) {
        return "pm:" + pmName + "/cluster:" + clusterName;
    }

    public String getPath() {
        return path;
    }

    @Override
    public String getName() {
        return clusterName;
    }

    @Override
    public void release() {
    }

    @Override
    public int compareTo(PhysicalMachineCluster o) {
        return pmName.compareTo(o.pmName);
    }

    public byte[] persistentDataToBytes() {
        return persistentData.toBytes();
    }

    public String persistentDataToString() {
        return persistentData.toString();
    }

    public PmClusterData clonePersistentData() {
        return (PmClusterData) persistentData.clone();
    }

	@JsonAutoDetect(
	        fieldVisibility=Visibility.ANY,
	        getterVisibility=Visibility.NONE,
	        setterVisibility=Visibility.NONE)
	@JsonIgnoreProperties(ignoreUnknown=true)
	@JsonPropertyOrder({"pgs_ID_List", "gw_ID_List"})
	public static class PmClusterData implements Cloneable {

	    @JsonProperty("pgs_ID_List")
	    private List<Integer> pgsIdList;
	    @JsonProperty("gw_ID_List")
	    private List<Integer> gwIdList;

	    @JsonIgnore
	    private final MemoryObjectMapper mapper = new MemoryObjectMapper();

	    public PmClusterData() {
		    pgsIdList = new ArrayList<Integer>();
		    gwIdList = new ArrayList<Integer>();
	    }

	    public void addPgsId(Integer id) {
	        pgsIdList.add(id);
	    }

	    public void deletePgsId(Integer id) {
	        pgsIdList.remove(id);
	    }

	    public void deletePgsId(String id) {
	        pgsIdList.remove(Integer.valueOf(id));
	    }

	    public void addGwId(Integer id) {
	        gwIdList.add(id);
	    }

	    public void deleteGwId(Integer id) {
	        gwIdList.remove(id);
	    }

	    public void deleteGwId(String id) {
	        gwIdList.remove(Integer.valueOf(id));
	    }

	    public List<Integer> getPgsIdList() {
	        return pgsIdList;
	    }

	    public void setPgsIdList(List<Integer> pgsIdList) {
	        this.pgsIdList = pgsIdList;
	    }

	    public List<Integer> getGwIdList() {
	        return gwIdList;
	    }

	    public void setGwIdList(List<Integer> gwIdList) {
	        this.gwIdList = gwIdList;
	    }

	    @Override
	    public boolean equals(Object obj) {
	        if (obj == null) {
	            return false;
	        }
	        if (obj == this) {
	            return true;
	        }
	        if (!(obj instanceof PmClusterData)) {
	            return false;
	        }

	        PmClusterData rhs = (PmClusterData) obj;
	        if (!pgsIdList.equals(rhs.pgsIdList)) {
	            return false;
	        }
	        if (!gwIdList.equals(rhs.gwIdList)) {
	            return false;
	        }
	        return true;
	    }

	    @Override
	    public int hashCode() {
	        assert false : "hashCode not designed";
	        return 42; // any arbitrary constant will do
	    }

	    @Override
	    public Object clone() {
	        try {
	            super.clone();
	        } catch (CloneNotSupportedException e) {
	            throw new RuntimeException(e);
	        }
	        PmClusterData data = new PmClusterData();
	        data.pgsIdList = new ArrayList<Integer>(this.pgsIdList);
	        data.gwIdList = new ArrayList<Integer>(this.gwIdList);
	        return data;
	    }

	    @Override
	    public String toString() {
            return mapper.writeValueAsString(this);
	    }

	    public byte[] toBytes() {
            return mapper.writeValueAsBytes(this);
	    }

	}

	public List<Integer> getPgsIdList() {
		return persistentData.getPgsIdList();
	}

	public List<Integer> getGwIdList() {
		return persistentData.getGwIdList();
	}

	public void addGwId(Integer gwId) {
		persistentData.addGwId(gwId);
	}

	public void deleteGwId(String gwId) {
		persistentData.deleteGwId(gwId);
	}

	public void addPgsId(Integer pgsId) {
		persistentData.addPgsId(pgsId);
	}

	public void deletePgsId(String pgsId) {
		persistentData.deletePgsId(pgsId);
	}
}


text:
package org.apache.activemq.artemis.spi.core.protocol;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;

import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQInterruptedException;
import org.apache.activemq.artemis.core.client.ActiveMQClientLogger;
import org.apache.activemq.artemis.core.client.ActiveMQClientMessageBundle;
import org.apache.activemq.artemis.core.remoting.CloseListener;
import org.apache.activemq.artemis.core.remoting.FailureListener;
import org.apache.activemq.artemis.spi.core.remoting.Connection;

public abstract class AbstractRemotingConnection implements RemotingConnection
{
   protected final List<FailureListener> failureListeners = new CopyOnWriteArrayList<FailureListener>();
   protected final List<CloseListener> closeListeners = new CopyOnWriteArrayList<CloseListener>();
   protected final Connection transportConnection;
   protected final Executor executor;
   protected final long creationTime;
   protected volatile boolean dataReceived;

   public AbstractRemotingConnection(final Connection transportConnection, final Executor executor)
   {
      this.transportConnection = transportConnection;
      this.executor = executor;
      this.creationTime = System.currentTimeMillis();
   }

   public List<FailureListener> getFailureListeners()
   {
      return new ArrayList<FailureListener>(failureListeners);
   }

   protected void callFailureListeners(final ActiveMQException me, String scaleDownTargetNodeID)
   {
      final List<FailureListener> listenersClone = new ArrayList<FailureListener>(failureListeners);

      for (final FailureListener listener : listenersClone)
      {
         try
         {
            listener.connectionFailed(me, false, scaleDownTargetNodeID);
         }
         catch (ActiveMQInterruptedException interrupted)
         {
            // this is an expected behaviour.. no warn or error here
            ActiveMQClientLogger.LOGGER.debug("thread interrupted", interrupted);
         }
         catch (final Throwable t)
         {
            // Failure of one listener to execute shouldn't prevent others
            // from
            // executing
            ActiveMQClientLogger.LOGGER.errorCallingFailureListener(t);
         }
      }
   }

   protected void callClosingListeners()
   {
      final List<CloseListener> listenersClone = new ArrayList<CloseListener>(closeListeners);

      for (final CloseListener listener : listenersClone)
      {
         try
         {
            listener.connectionClosed();
         }
         catch (final Throwable t)
         {
            // Failure of one listener to execute shouldn't prevent others
            // from
            // executing
            ActiveMQClientLogger.LOGGER.errorCallingFailureListener(t);
         }
      }
   }

   public void setFailureListeners(final List<FailureListener> listeners)
   {
      failureListeners.clear();

      failureListeners.addAll(listeners);
   }

   public Object getID()
   {
      return transportConnection.getID();
   }

   public String getRemoteAddress()
   {
      return transportConnection.getRemoteAddress();
   }

   public void addFailureListener(final FailureListener listener)
   {
      if (listener == null)
      {
         throw ActiveMQClientMessageBundle.BUNDLE.failListenerCannotBeNull();
      }
      failureListeners.add(listener);
   }

   public boolean removeFailureListener(final FailureListener listener)
   {
      if (listener == null)
      {
         throw ActiveMQClientMessageBundle.BUNDLE.failListenerCannotBeNull();
      }

      return failureListeners.remove(listener);
   }

   public void addCloseListener(final CloseListener listener)
   {
      if (listener == null)
      {
         throw ActiveMQClientMessageBundle.BUNDLE.closeListenerCannotBeNull();
      }

      closeListeners.add(listener);
   }

   public boolean removeCloseListener(final CloseListener listener)
   {
      if (listener == null)
      {
         throw ActiveMQClientMessageBundle.BUNDLE.closeListenerCannotBeNull();
      }

      return closeListeners.remove(listener);
   }

   public List<CloseListener> removeCloseListeners()
   {
      List<CloseListener> ret = new ArrayList<CloseListener>(closeListeners);

      closeListeners.clear();

      return ret;
   }

   public List<FailureListener> removeFailureListeners()
   {
      List<FailureListener> ret = getFailureListeners();

      failureListeners.clear();

      return ret;
   }

   public void setCloseListeners(List<CloseListener> listeners)
   {
      closeListeners.clear();

      closeListeners.addAll(listeners);
   }

   public ActiveMQBuffer createTransportBuffer(final int size)
   {
      return transportConnection.createTransportBuffer(size);
   }

   public Connection getTransportConnection()
   {
      return transportConnection;
   }

   public long getCreationTime()
   {
      return creationTime;
   }

   public boolean checkDataReceived()
   {
      boolean res = dataReceived;

      dataReceived = false;

      return res;
   }

   /*
    * This can be called concurrently by more than one thread so needs to be locked
    */
   public void fail(final ActiveMQException me)
   {
      fail(me, null);
   }

   public void bufferReceived(final Object connectionID, final ActiveMQBuffer buffer)
   {
      dataReceived = true;
   }

}


text:
<?php

namespace Pactum;

/**
 * Class ConfigParser
 * @package Pactum
 * @author Michal Tomczak (michal.tomczak@newclass.pl)
 */
class ConfigParser
{
    /**
     * @var ConfigBuilderObject[]
     */
    private $objects;
    /**
     * @var ConfigBuilderArray[]
     */
    private $arrays;
    /**
     * @var ConfigBuilderValue[]
     */
    private $values;
    /**
     * @var ObjectReader[]
     */
    private $readers;
    /**
     * @var callable[]
     */
    private $filters;

    /**
     * ConfigParser constructor.
     * @param ObjectReader[] $readers
     * @param callable[] $filters
     * @param ConfigBuilderObject[] $objects
     * @param ConfigBuilderArray[] $arrays
     * @param ConfigBuilderValue[] $values
     */
    public function __construct($readers, $filters, $objects, $arrays, $values)
    {
        $this->objects = $objects;
        $this->arrays = $arrays;
        $this->values = $values;
        $this->readers = $readers;
        $this->filters = $filters;
    }

    /**
     * @return ConfigContainer
     */
    public function execute()
    {
        if (!$this->readers) {
            return new ConfigContainer([], [], []);
        }

        $result = [];
        $objects = [];
        $arrays = [];
        $values = [];

        foreach ($this->arrays as $name => $builder) {
            $arrays[$name] = $this->parseArray($this->readers, $name, $builder);
        }

        $result['arrays'] = $arrays;

        foreach ($this->objects as $name => $builder) {
            $objects[$name] = $this->parseObject($this->readers, $name, $builder);
        }

        $result['objects'] = $objects;

        foreach ($this->values as $name => $builder) {
            $values[$name] = $this->parseValue($this->readers, $name, $builder);
        }

        $result['values'] = $values;

        return new ConfigContainer($result['objects'], $result['arrays'], $result['values']);

    }

    /**
     *
     * @param ObjectReader[] $readers
     * @param string $name
     * @param ConfigBuilderValue $builder
     * @return mixed
     * @throws ConfigException
     * @throws InvalidValueException
     */
    private function parseValue(array $readers, $name, ConfigBuilderValue $builder)
    {
        $exception = null;
        $value = null;
        try {
            $value = $this->readValue($readers, $name);
        } catch (ElementNotFoundException $e) {
            $exception = $e;
        }

        $process = new ParserProcess($this, $builder->getType(), $readers[0]->getPath(), $name, $builder, $value);

        $this->fireFilters($process);

        $value = $process->getValue();

        if ($exception !== null && $value === null) {
            if ($builder->isRequired()) {
                throw $exception;
            }
            $value = $builder->getDefault();
        }

        if (!$builder->isValid($value)) {
            throw new InvalidValueException($name, $value, $builder->getType());
        }

        return $value;
    }

    /**
     *
     * @param ObjectReader[] $readers
     * @param string $name
     * @param ConfigBuilderObject $builder
     * @return ConfigContainer
     * @throws ElementNotFoundException
     */
    private function parseObject(array $readers, $name, ConfigBuilderObject $builder)
    {
        try {$readers = $this->readObject($readers, $name);
        } catch (ElementNotFoundException $e) {
            if(!$builder->isRequired()){
                return null;
            }

            throw $e;
        }

        $objects = [];
        $arrays = [];
        $values = [];

        foreach ($builder->getArrays() as $name => $subBuilder) {
            $arrays[$name] = $this->parseArray($readers, $name, $subBuilder);
        }

        foreach ($builder->getObjects() as $name => $subBuilder) {
            $objects[$name] = $this->parseObject($readers, $name, $subBuilder);
        }

        foreach ($builder->getValues() as $name => $subBuilder) {
            $values[$name] = $this->parseValue($readers, $name, $subBuilder);
        }

        $value = new ConfigContainer($objects, $arrays, $values);
        $process = new ParserProcess($this, 'object', $readers[0]->getPath(), $name, $builder, $value);

        $this->fireFilters($process);
        $value = $process->getValue();

        return $value;
    }

    /**
     *
     * @param ArrayReader[] $readers
     * @param string $name
     * @param ConfigBuilderArray $builder
     * @return ConfigContainer[]
     * @throws ConfigException
     * @throws ElementNotFoundException
     * @throws InvalidNumberElementException
     */
    private function parseArray(array $readers, $name, ConfigBuilderArray $builder)
    {
        $results = [];
        try {
            $readers = $this->readArray($readers, $name);
        } catch (ElementNotFoundException $e) {
            if ($builder->getMin() !== 0) {
                throw $e;
            }
            return $results;
        }

        $type = $builder->getType();
        $builderArray = $builder->getValue();
        switch ($type) {
            case 'array':
                throw new ConfigException('Deep array is not supported. Use object instead array.');

            case 'object':
                foreach ($readers as $reader) {
                    foreach ($reader->getObjects() as $name => $subBuilder) {
                        $results[] = $this->parseObject([$reader], $name, $builderArray);
                    }
                }
                break;
            default:
                foreach ($readers as $reader) {
                    foreach ($reader->getValues() as $name => $subBuilder) {
                        $results[] = $this->parseValue([$reader], $name, $builderArray);
                    }
                }

        }

        $process = new ParserProcess($this, 'array', $readers[0]->getPath(), $name, $builder, $results);

        $this->fireFilters($process);
        $results = $process->getValue();

        $resultNumber = count($results);
        if ($builder->getMin() > $resultNumber) {
            throw new InvalidNumberElementException($readers[0]->getPath(), $builder->getMin(), $resultNumber);
        }

        if ($builder->getMax() !== null && $resultNumber > $builder->getMax()) {
            throw new InvalidNumberElementException($readers[0]->getPath(), $builder->getMax(), $resultNumber);
        }

        return $results;
    }

    /**
     * @param ObjectReader[] $readers
     * @param string $name
     * @return mixed
     * @throws ElementNotFoundException
     * @throws TooManyElementException
     */
    private function readValue(array $readers, $name)
    {
        $records = [];
        $exception = null;
        foreach ($readers as $reader) {
            try {
                $records[] = $reader->getValue($name);
            } catch (ElementNotFoundException $e) {
                $exception = $e;
            }
        }

        if (!$records) {
            throw $exception;
        }

        if (count($records) > 1) {
            throw new TooManyElementException($readers[0]->getPath(), $name);
        }
        return $records[0];

    }

    /**
     * @param ObjectReader[] $readers
     * @param string $name
     * @return mixed
     * @throws ElementNotFoundException
     * @throws TooManyElementException
     */
    private function readObject(array $readers, $name)
    {
        $records = [];
        $exception = null;
        foreach ($readers as $reader) {
            try {
                $records[] = $reader->getObject($name);
            } catch (ElementNotFoundException $e) {
                $exception = $e;
            }
        }

        if (!$records) {
            throw $exception;
        }

        if (count($records) > 1) {
            throw new TooManyElementException($readers[0]->getPath(), $name);
        }

        return $records;

    }

    /**
     * @param ObjectReader[] $readers
     * @param string $name
     * @return mixed[]
     * @throws ElementNotFoundException
     * @throws TooManyElementException
     */
    private function readArray(array $readers, $name)
    {
        $records = [];
        $exception = null;
        foreach ($readers as $reader) {
            try {
                $records[] = $reader->getArray($name);
            } catch (ElementNotFoundException $e) {
                $exception = $e;
            }
        }

        if (!$records) {
            throw $exception;
        }

        return $records;

    }

    /**
     * @param ParserProcess $process
     */
    private function fireFilters($process)
    {
        foreach ($this->filters as $filter) {
            call_user_func($filter, $process);
        }
    }

    /**
     * @param ObjectReader $reader
     */
    public function addReader($reader)
    {
        $this->readers[] = $reader;
    }
}


text:
package org.rschrage.xue;

import org.rschrage.util.ReflectionUtils;
import org.rschrage.xue.annotation.Dependency;
import org.rschrage.xue.constants.Constant;
import org.rschrage.xue.dom.DomRepresentation;
import org.rschrage.xue.exception.*;
import org.rschrage.xue.handler.TagGroupHandler;
import org.rschrage.xue.mapping.TagMapping;
import org.rschrage.xue.util.InjectionUtils;
import org.rschrage.xue.util.StreamUtils;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.*;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Rico on 10.07.2015.
 *
 * @author Rico Schrage
 */
public class XueCore {
    private static final String ENCODING = "UTF-8";
    private static final int TRIES = 1;

    private final List<TagGroupHandler<?, ?>> tagGroupHandlerList;
    private final List<Class<? extends TagGroupHandler>> closed;

    private final Map<Constant, String> constantMap;

    private TagGroupHandler<?, ?> currentHandler;
    private int remainingTries = TRIES;

    /**
     * Constructs XueCore, which uses tagMapping and attributeMapping for everything, which have to be mapped.
     */
    public XueCore() {
        tagGroupHandlerList = new ArrayList<>();
        closed = new ArrayList<>();
        constantMap = new EnumMap<>(Constant.class);

        for (Constant constant : Constant.values()) {
            constantMap.put(constant, constant.toString());
        }
    }

    private TagGroupHandler<?, ?> calculateNextTagHandler() {
        for (TagGroupHandler<?, ?> t : tagGroupHandlerList) {
            if (closed.contains(t.getClass())) {
                continue;
            }
            List<Class<?>> depend = calcDependencies(t);
            if (depend.isEmpty() || closed.containsAll(depend)) {
                closed.add(t.getClass());
                return t;
            }
        }
        if (closed.size() == tagGroupHandlerList.size())
            return null;

        throw new XueException("The dependencies of the tag handler are cyclic!");
    }

    private List<Class<?>> calcDependencies(TagGroupHandler<?, ?> tagGroupHandler) {
        List<Field> fields = ReflectionUtils.getAllFields(tagGroupHandler.getClass());
        List<Class<?>> tagHandlers = new ArrayList<>();
        for (final Field field : fields) {
            if (field.isAnnotationPresent(Dependency.class)) {
                tagHandlers.add(field.getType());
            }
        }
        return tagHandlers;
    }

    public void overwriteConstant(Constant constant, String value) {
        constantMap.put(constant, value);
    }

    public void addHandler(TagGroupHandler<?, ?> tagGroupHandler) {
        for (TagGroupHandler<?, ?> other : tagGroupHandlerList) {
            if (other.getClass() == tagGroupHandler.getClass()) {
                throw new IllegalArgumentException();
            }
        }

        for (TagGroupHandler<?, ?> other : tagGroupHandlerList) {
            InjectionUtils.injectByType(Dependency.class, tagGroupHandler, other);
            InjectionUtils.injectByType(Dependency.class, other, tagGroupHandler);
        }
        tagGroupHandler.setConstantMap(constantMap);

        this.tagGroupHandlerList.add(tagGroupHandler);
    }

    public <E, D extends DomRepresentation<E>> Map<String, D> getDom(Class<TagGroupHandler<E, D>> tagGroupHandlerClass) {
        for (TagGroupHandler<?, ?> t : tagGroupHandlerList) {
            if (t.getClass() == tagGroupHandlerClass) {
                //noinspection unchecked
                return (Map<String, D>) t.getDom();
            }
        }
        throw new IllegalArgumentException("There does not exist a tag-group handler of the given class!");
    }

    public List<TagGroupHandler<?, ?>> getDomContainer() {
        return tagGroupHandlerList;
    }

    /**
     * Generic method to add a mapping to the given tagHandler. For core tag handler use the special methods instead.
     * This method should be used for custom tagHandler.
     *
     * @param tagHandler handler of a group of tags
     * @param tagMapping mapping
     * @param <B> makes sure that the tagHandler und tagMapping fit together
     */
    public <B, D extends DomRepresentation<B>> void addMapping(Class<? extends TagGroupHandler<B, D>> tagHandler, TagMapping<B> tagMapping) {
        addMappingUnsafe(tagHandler, tagMapping);
    }

    /**
     * Generic <b>unsafe</b> method to add a mapping to the given tagHandler. The given class object must be a tag handler which can add the given
     * mapping. Just use this method when you have to otherwise {@link #addMapping(Class, TagMapping)} is the far better choice.
     * @param tagHandler class of the taghandler
     * @param tagMapping mapping you want to add
     * @param <B> internal
     * @throws ClassCastException can be thrown when the class object is not a tagHandler or if the tagHandler can't add the mapping.
     */
    public <B> void addMappingUnsafe(Class<? extends TagGroupHandler> tagHandler, TagMapping<B> tagMapping) {
        for (TagGroupHandler<?, ?> t : tagGroupHandlerList) {
            if (t.getClass() == tagHandler) {
                //noinspection unchecked
                ((TagGroupHandler<B, ?>)t).addBuilderMapping(tagMapping);
            }
        }
    }

    public <B> Map<String, B> getResult(Class<? extends TagGroupHandler<B, ?>> handlerClass, String domain, Class<B> resultClass) {
        //noinspection unchecked
        return getResultUnsafe(handlerClass, domain, resultClass);
    }

    /**
    * Generic method to get/create the result map of a tagHandler.
    *
    * @param handlerClass type of the handler you want to get the map from
    * @param <B> ensures a correct return type
    * @return Result of the handlerClass
    */
    public <B> Map<String, B> getResultUnsafe(Class<? extends TagGroupHandler> handlerClass, String domain, Class<B> resultClass) {
        for (TagGroupHandler<?, ?> t : tagGroupHandlerList) {
            if (t.getClass() == handlerClass) {
                //noinspection unchecked
                List<?> dom = t.getDom();
                Map<String, B> resultMap = new HashMap<>();
                for (int i = 0; i < dom.size(); ++i) {
                    DomRepresentation<B> domObject = (DomRepresentation<B>) dom.get(i);
                    //noinspection unchecked
                    if (domain.equals(domObject.getDomain())) {
                        resultMap.put(domObject.getName(), domObject.getObject());
                    }
                }
                return resultMap;
            }
        }
        throw new IllegalArgumentException(handlerClass + " is not part of this core!");
    }

    public void loadDirectory(File directory) throws FileNotFoundException {
        if (!directory.isDirectory()) {
            throw new XueException("The object have to be a directory!");
        }
        File[] files = directory.listFiles();
        if (files == null) {
            throw new XueException("There are no listable files in this directory!");
        }
        for (File file : files) {
            load(new FileInputStream(file), file.getName());
            closed.clear();
        }
    }

    /**
     * Creates all elements specified in xml-file, which has been used to create the PullParser.
     *
     * @param inputXml Xml input stream.
     *
     * @throws XueSyntaxException see {@link XueSyntaxException}
     * @throws ConstTagUnknownException see {@link ConstTagUnknownException}
     * @throws AttributeUnknownException see {@link AttributeUnknownException}
     * @throws ElementTagUnknownException see {@link ElementTagUnknownException}
     */
    public void load(InputStream inputXml, String filename) {
        if (tagGroupHandlerList.isEmpty() || closed.size() == tagGroupHandlerList.size()) {
            throw new IllegalArgumentException();
        }
        try {
            boolean finished = false;
            String xml = StreamUtils.convertStreamToString(inputXml);
            while (!finished) {
                finished = true;
                Pattern pattern = Pattern.compile("<" + Constant.XUE_INPUT_TAG_NAME + " " + Constant.XUE_INPUT_SRC_ATT + "?=?\"(.*)\".*/>");
                Matcher m = pattern.matcher(xml);
                StringBuffer sb = new StringBuffer();
                while (m.find()) {
                    String src = m.group(1);
                    m.appendReplacement(sb, StreamUtils.convertStreamToString(getClass().getResourceAsStream(src)));
                    finished = false;
                }
                m.appendTail(sb);
                xml = sb.toString();
            }
            currentHandler = calculateNextTagHandler();
            //noinspection ConstantConditions intellij too bad not true fakenews!
            currentHandler.setDomain(filename);
            while (currentHandler != null) {
                XmlPullParser xpp = new KXmlParser();
                inputXml = new ByteArrayInputStream(xml.getBytes());
                inputXml.mark(Integer.MAX_VALUE);
                xpp.setInput(inputXml, ENCODING);
                while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
                    switch (xpp.getEventType()) {

                        case XmlPullParser.START_TAG:
                            handleStartTag(xpp);
                            break;

                        case XmlPullParser.END_TAG:
                            handleEndTag(xpp);
                            if (currentHandler != null) {
                                currentHandler.setDomain(filename);
                            }
                            break;

                        default:
                            break;
                    }
                    xpp.next();
                    if (currentHandler == null) {
                        break;
                    }
                }
                if (remainingTries == 0) {
                    currentHandler = calculateNextTagHandler();
                    //noinspection ConstantConditions intellij too bad not true fakenews!
                    if (currentHandler != null) {
                        currentHandler.setDomain(filename);
                    }
                    remainingTries = TRIES;
                }
                else {
                    remainingTries--;
                }
                inputXml.reset();
            }
        }
        catch (XmlPullParserException e) {
            throw new XueParseException(e);
        }
        catch (IOException e) {
            throw new XueIOException(e);
        }
    }

    /**
     * Defines what happens when the parser reaches a start-tag.
     *
     * @param xpp PullParser, which has been created with the xml resource.
     * @throws XueSyntaxException if a const tag has been placed wrong
     * @throws ConstTagUnknownException if a tag in <constants>...</constants> is unknown
     * @throws AttributeUnknownException if an attribute is unknow.
     * @throws ElementTagUnknownException if a tag in <elements>...</elements> is unknown
     */
    private void handleStartTag(XmlPullParser xpp) throws XmlPullParserException {
        if (!currentHandler.isActive() && currentHandler.getName().equals(xpp.getName())) {
            currentHandler.setActive(true);
            currentHandler.startHandle(xpp);
            return;
        }

        if (currentHandler.isActive()) {
            currentHandler.handle(xpp);
        }
    }

    private String handleXueInput(XmlPullParser xpp) {
        if (xpp.getAttributeName(0).equals(Constant.XUE_INPUT_SRC_ATT.toString())) {
            return xpp.getAttributeValue(0);
        }
        return null;
    }

    /**
     * Defines what happens when the parser reaches an end-tag.
     *
     * @param xpp PullParser, which has been created with the xml resource.
     */
    private void handleEndTag(XmlPullParser xpp) throws XmlPullParserException {
        if (currentHandler.getName().equals(xpp.getName()) && currentHandler.isActive()) {
            currentHandler.setActive(false);
            currentHandler.stopHandle(xpp);
            currentHandler = calculateNextTagHandler();
        }
    }
}


text:
<?php
class ControllerLocalisationTaxClass extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('localisation/tax_class');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('localisation/tax_class');

		$this->getList();
	}

	public function add() {
		$this->load->language('localisation/tax_class');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('localisation/tax_class');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_localisation_tax_class->addTaxClass($this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('localisation/tax_class', 'token=' . $this->session->data['token'] . $url, true));
		}

		$this->getForm();
	}

	public function edit() {
		$this->load->language('localisation/tax_class');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('localisation/tax_class');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_localisation_tax_class->editTaxClass($this->request->get['tax_class_id'], $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('localisation/tax_class', 'token=' . $this->session->data['token'] . $url, true));
		}

		$this->getForm();
	}

	public function delete() {
		$this->load->language('localisation/tax_class');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('localisation/tax_class');

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $tax_class_id) {
				$this->model_localisation_tax_class->deleteTaxClass($tax_class_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('localisation/tax_class', 'token=' . $this->session->data['token'] . $url, true));
		}

		$this->getList();
	}

	protected function getList() {
		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'title';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('localisation/tax_class', 'token=' . $this->session->data['token'] . $url, true)
		);

		$data['add'] = $this->url->link('localisation/tax_class/add', 'token=' . $this->session->data['token'] . $url, true);
		$data['delete'] = $this->url->link('localisation/tax_class/delete', 'token=' . $this->session->data['token'] . $url, true);

		$data['tax_classes'] = array();

		$filter_data = array(
			'sort'  => $sort,
			'order' => $order,
			'start' => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit' => $this->config->get('config_limit_admin')
		);

		$tax_class_total = $this->model_localisation_tax_class->getTotalTaxClasses();

		$results = $this->model_localisation_tax_class->getTaxClasses($filter_data);

		foreach ($results as $result) {
			$data['tax_classes'][] = array(
				'tax_class_id' => $result['tax_class_id'],
				'title'        => $result['title'],
				'edit'         => $this->url->link('localisation/tax_class/edit', 'token=' . $this->session->data['token'] . '&tax_class_id=' . $result['tax_class_id'] . $url, true)
			);
		}

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_list'] = $this->language->get('text_list');
		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_confirm'] = $this->language->get('text_confirm');

		$data['column_title'] = $this->language->get('column_title');
		$data['column_action'] = $this->language->get('column_action');

		$data['button_add'] = $this->language->get('button_add');
		$data['button_edit'] = $this->language->get('button_edit');
		$data['button_delete'] = $this->language->get('button_delete');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}

		if (isset($this->request->post['selected'])) {
			$data['selected'] = (array)$this->request->post['selected'];
		} else {
			$data['selected'] = array();
		}

		$url = '';

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['sort_title'] = $this->url->link('localisation/tax_class', 'token=' . $this->session->data['token'] . '&sort=title' . $url, true);

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $tax_class_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('localisation/tax_class', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($tax_class_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($tax_class_total - $this->config->get('config_limit_admin'))) ? $tax_class_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $tax_class_total, ceil($tax_class_total / $this->config->get('config_limit_admin')));

		$data['sort'] = $sort;
		$data['order'] = $order;

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('localisation/tax_class_list', $data));
	}

	protected function getForm() {
		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_form'] = !isset($this->request->get['tax_class_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');
		$data['text_shipping'] = $this->language->get('text_shipping');
		$data['text_payment'] = $this->language->get('text_payment');
		$data['text_store'] = $this->language->get('text_store');

		$data['entry_title'] = $this->language->get('entry_title');
		$data['entry_description'] = $this->language->get('entry_description');
		$data['entry_rate'] = $this->language->get('entry_rate');
		$data['entry_based'] = $this->language->get('entry_based');
		$data['entry_priority'] = $this->language->get('entry_priority');

		$data['button_save'] = $this->language->get('button_save');
		$data['button_cancel'] = $this->language->get('button_cancel');
		$data['button_rule_add'] = $this->language->get('button_rule_add');
		$data['button_remove'] = $this->language->get('button_remove');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->error['title'])) {
			$data['error_title'] = $this->error['title'];
		} else {
			$data['error_title'] = '';
		}

		if (isset($this->error['description'])) {
			$data['error_description'] = $this->error['description'];
		} else {
			$data['error_description'] = '';
		}

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('localisation/tax_class', 'token=' . $this->session->data['token'] . $url, true)
		);

		if (!isset($this->request->get['tax_class_id'])) {
			$data['action'] = $this->url->link('localisation/tax_class/add', 'token=' . $this->session->data['token'] . $url, true);
		} else {
			$data['action'] = $this->url->link('localisation/tax_class/edit', 'token=' . $this->session->data['token'] . '&tax_class_id=' . $this->request->get['tax_class_id'] . $url, true);
		}

		$data['cancel'] = $this->url->link('localisation/tax_class', 'token=' . $this->session->data['token'] . $url, true);

		if (isset($this->request->get['tax_class_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$tax_class_info = $this->model_localisation_tax_class->getTaxClass($this->request->get['tax_class_id']);
		}

		if (isset($this->request->post['title'])) {
			$data['title'] = $this->request->post['title'];
		} elseif (!empty($tax_class_info)) {
			$data['title'] = $tax_class_info['title'];
		} else {
			$data['title'] = '';
		}

		if (isset($this->request->post['description'])) {
			$data['description'] = $this->request->post['description'];
		} elseif (!empty($tax_class_info)) {
			$data['description'] = $tax_class_info['description'];
		} else {
			$data['description'] = '';
		}

		$this->load->model('localisation/tax_rate');

		$data['tax_rates'] = $this->model_localisation_tax_rate->getTaxRates();

		if (isset($this->request->post['tax_rule'])) {
			$data['tax_rules'] = $this->request->post['tax_rule'];
		} elseif (isset($this->request->get['tax_class_id'])) {
			$data['tax_rules'] = $this->model_localisation_tax_class->getTaxRules($this->request->get['tax_class_id']);
		} else {
			$data['tax_rules'] = array();
		}

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('localisation/tax_class_form', $data));
	}

	protected function validateForm() {
		if (!$this->user->hasPermission('modify', 'localisation/tax_class')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if ((utf8_strlen($this->request->post['title']) < 3) || (utf8_strlen($this->request->post['title']) > 32)) {
			$this->error['title'] = $this->language->get('error_title');
		}

		if ((utf8_strlen($this->request->post['description']) < 3) || (utf8_strlen($this->request->post['description']) > 255)) {
			$this->error['description'] = $this->language->get('error_description');
		}

		return !$this->error;
	}

	protected function validateDelete() {
		if (!$this->user->hasPermission('modify', 'localisation/tax_class')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		$this->load->model('catalog/product');

		foreach ($this->request->post['selected'] as $tax_class_id) {
			$product_total = $this->model_catalog_product->getTotalProductsByTaxClassId($tax_class_id);

			if ($product_total) {
				$this->error['warning'] = sprintf($this->language->get('error_product'), $product_total);
			}
		}

		return !$this->error;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Collections;
using System.Security.Cryptography;
using System.Drawing.Imaging;

namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdprfx
{

    /// <summary>
    /// The image tile in RGB format.
    /// </summary>
    public class RgbTile
    {
        #region RGB data
        /// <summary>
        /// Red component
        /// </summary>
        public byte[,] RSet;

        /// <summary>
        /// Green component
        /// </summary>
        public byte[,] GSet;

        /// <summary>
        /// Blue component
        /// </summary>
        public byte[,] BSet;

        /// <summary>
        /// The fixed tile size
        /// </summary>
        public const int TileSize = 64;

        #endregion

        private byte[] hash = null;

        /// <summary>
        /// Create a RGB tile from a given bitmap
        /// </summary>
        /// <param name="orgImg">The given bitmap</param>
        /// <param name="leftOffset">The left offset of the tile to the bitmap</param>
        /// <param name="topOffset">The top offset of the tile to the bitmap</param>
        /// <returns></returns>
        public static RgbTile GetFromImage(Bitmap orgImg, int leftOffset, int topOffset)
        {
            RgbTile tile = new RgbTile();
            tile.RSet = new byte[TileSize, TileSize];
            tile.GSet = new byte[TileSize, TileSize];
            tile.BSet = new byte[TileSize, TileSize];

            int right = Math.Min(orgImg.Width - 1, leftOffset + TileSize - 1);
            int bottom = Math.Min(orgImg.Height - 1, topOffset + TileSize - 1);
            Rectangle bmpRect = new Rectangle(leftOffset, topOffset, right - leftOffset + 1, bottom - topOffset + 1);
            BitmapData bmpData = orgImg.LockBits(bmpRect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            unsafe
            {
                byte* cusor = (byte*)bmpData.Scan0.ToPointer();

                for (int y = topOffset; y <= bottom; y++)
                {
                    for (int x = leftOffset; x <= right; x++)
                    {
                        int tileX = x - leftOffset;
                        int tileY = y - topOffset;
                        tile.BSet[tileX, tileY] = cusor[0];
                        tile.GSet[tileX, tileY] = cusor[1];
                        tile.RSet[tileX, tileY] = cusor[2];
                        cusor += 3;
                    }
                    cusor += (bmpData.Stride - 3 * (bmpData.Width));
                }
            }
            orgImg.UnlockBits(bmpData);

            return tile;
        }

        /// <summary>
        /// Reander RGB data to a bitmap
        /// </summary>
        /// <returns>Bitmap of the tile.</returns>
        public  Bitmap ToImage()
        {
            Bitmap bmp = new Bitmap(TileSize, TileSize);
            BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            unsafe
            {
                byte* cusor = (byte*)bmpData.Scan0.ToPointer();
                for (int y = 0; y < bmpData.Height; y++)
                {
                    for (int x = 0; x < bmpData.Width; x++)
                    {
                        cusor[0] = this.BSet[x, y];
                        cusor[1] = this.GSet[x, y];
                        cusor[2] = this.RSet[x, y];
                        cusor += 3;
                    }
                    cusor += (bmpData.Stride - 3 * (bmpData.Width));
                }
            }
            bmp.UnlockBits(bmpData);
            return bmp;
        }

        /// <summary>
        /// Compare if equals with the given RGB tile
        /// </summary>
        /// <param name="cpTile">The given RGB tile</param>
        /// <returns>True if equals, otherwise false</returns>
        public bool EqualsWith(RgbTile cpTile)
        {
            byte[] lastHash = this.HashValue;
            byte[] newHash = cpTile.HashValue;
            for (int i = 0; i < lastHash.Length; i++)
            {
                if (lastHash[i] != newHash[i]) return false;
            }
            return true;
        }

        private bool ByteArrayEquals(byte[,] a, byte[,] b)
        {
            if (a == null && b == null) return true;
            if (a == null || b == null) return false;
            if (a.Length != b.Length) return false;

            for (int x = 0; x < TileSize; x++)
            {
                for (int y = 0; y < TileSize; y++)
                {
                    if (a[x, y] != b[x, y]) return false;
                }
            }
            return true;
        }

        /// <summary>
        /// Get Hash value of this tile.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security.Cryptography", "CA5350:MD5CannotBeUsed")]
        public byte[] HashValue
        {
            get
            {
                if (hash == null)
                {
                    // Suppress "CA5350:MD5CannotBeUsed" message, since MD5 here is only for get hash value, not for securit.
                    MD5 hasher = MD5.Create();
                    byte[] temp = new byte[this.RSet.Length * 3];
                    Buffer.BlockCopy(this.RSet, 0, temp, 0, RSet.Length * sizeof(byte));
                    Buffer.BlockCopy(this.GSet, 0, temp, RSet.Length, RSet.Length * sizeof(byte));
                    Buffer.BlockCopy(this.BSet, 0, temp, RSet.Length * 2, RSet.Length * sizeof(byte));
                    hasher.ComputeHash(temp);
                    hash = hasher.Hash;
                }
                return hash;
            }
        }
    }

}


text:
"""Run the webpages_playback automation script."""

import os
import subprocess
import sys

sys.path.insert(0, os.getcwd())

from common.py.utils import gs_utils
from common.py.utils import shell_utils

SKP_VERSION_FILE = 'SKP_VERSION'

def _get_skp_version():
  """Find an unused SKP version."""
  current_skp_version = None
  with open(SKP_VERSION_FILE) as f:
    current_skp_version = int(f.read().rstrip())

  # Find the first SKP version which has no uploaded SKPs.
  new_version = current_skp_version + 1
  while True:
    gs_path = 'playback_%d/skps' % new_version
    if not gs_utils.GSUtils().does_storage_object_exist('chromium-skia-gm',
                                                        gs_path):
      return new_version
    new_version += 1

def main(chrome_src_path, browser_executable):
  browser_executable = os.path.realpath(browser_executable)
  skp_version = _get_skp_version()
  print 'SKP_VERSION=%d' % skp_version

  if os.environ.get('CHROME_HEADLESS'):
    # Start Xvfb if running on a bot.
    try:
      shell_utils.run('sudo Xvfb :0 -screen 0 1280x1024x24 &', shell=True)
    except Exception:
      # It is ok if the above command fails, it just means that DISPLAY=:0
      # is already up.
      pass

  upload_dir = 'playback_%d' % skp_version
  webpages_playback_cmd = [
    'python', os.path.join(os.path.dirname(os.path.realpath(__file__)),
                           'webpages_playback.py'),
    '--page_sets', 'all',
    '--browser_executable', browser_executable,
    '--non-interactive',
    '--upload',
    '--alternate_upload_dir', upload_dir,
    '--chrome_src_path', chrome_src_path,
  ]

  try:
    shell_utils.run(webpages_playback_cmd)

    # Temporary change to enable Slimming Paint runs. See skia:3763.
    skia_page_sets_path = os.path.join(
        os.path.dirname(os.path.realpath(__file__)), 'page_sets')
    sp_skia_page_sets = [
        os.path.join(skia_page_sets_path, 'skia_carsvg_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_chalkboard_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_css3gradients_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_espn_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_gmailthread_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_googlehome_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_googlespreadsheet_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_jsfiddlebigcar_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_mapsvg_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_nytimes_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_samoasvg_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_tigersvg_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_ugamsolutions_desktop.py'),
        os.path.join(skia_page_sets_path, 'skia_digg_nexus10.py'),
        os.path.join(skia_page_sets_path, 'skia_gmail_nexus10.py'),
        os.path.join(skia_page_sets_path, 'skia_pravda_nexus10.py'),
    ]
    webpages_playback_cmd.extend([
        '--skp_prefix', 'sp_',
        '--browser_extra_args', '--enable-slimming-paint',
        '--page_sets', '%s' % ','.join(sp_skia_page_sets),
    ])
    shell_utils.run(webpages_playback_cmd)
  finally:
    # Clean up any leftover browser instances. This can happen if there are
    # telemetry crashes, processes are not always cleaned up appropriately by
    # the webpagereplay and telemetry frameworks.
    procs = subprocess.check_output(['ps', 'ax'])
    for line in procs.splitlines():
      if browser_executable in line:
        pid = line.strip().split(' ')[0]
        if pid != str(os.getpid()) and not 'python' in line:
          try:
            shell_utils.run(['kill', '-9', pid])
          except shell_utils.CommandFailedException as e:
            print e
        else:
          print 'Refusing to kill self.'

  print 'writing %s: %s' % (SKP_VERSION_FILE, skp_version)
  with open(SKP_VERSION_FILE, 'w') as f:
    f.write(str(skp_version))

if '__main__' == __name__:
  if len(sys.argv) != 3:
    print >> sys.stderr, 'USAGE: %s <chrome src path> <browser executable>'
    sys.exit(1)
  main(*sys.argv[1:])


text:
cask 'font-eagle-lake' do
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/raw/master/ofl/eaglelake/EagleLake-Regular.ttf'
  name 'Eagle Lake'
  homepage 'https://www.google.com/fonts/specimen/Eagle+Lake'

  font 'EagleLake-Regular.ttf'
end


text:
package org.jetbrains.plugins.gradle.config;

import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.externalSystem.psi.search.ExternalModuleBuildGlobalSearchScope;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.NonClasspathClassFinder;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.EverythingGlobalScope;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.service.GradleBuildClasspathManager;
import org.jetbrains.plugins.groovy.GroovyFileType;

import java.util.List;

/**
 * @author peter
 */
public class GradleClassFinder extends NonClasspathClassFinder {

  @NotNull private final GradleBuildClasspathManager myBuildClasspathManager;

  public GradleClassFinder(Project project, @NotNull GradleBuildClasspathManager buildClasspathManager) {
    super(project, JavaFileType.DEFAULT_EXTENSION, GroovyFileType.DEFAULT_EXTENSION);
    myBuildClasspathManager = buildClasspathManager;
  }

  @Override
  protected List<VirtualFile> calcClassRoots() {
    // do not use default NonClasspathClassFinder caching strategy based on PSI change
    // the caching performed in GradleBuildClasspathManager
    throw new AssertionError();
  }

  @Override
  protected List<VirtualFile> getClassRoots() {
    return myBuildClasspathManager.getAllClasspathEntries();
  }

  @Override
  protected List<VirtualFile> getClassRoots(@Nullable GlobalSearchScope scope) {
    if (scope instanceof ExternalModuleBuildGlobalSearchScope) {
      ExternalModuleBuildGlobalSearchScope externalModuleBuildGlobalSearchScope = (ExternalModuleBuildGlobalSearchScope)scope;
      return myBuildClasspathManager.getModuleClasspathEntries(externalModuleBuildGlobalSearchScope.getExternalModulePath());
    }
    return myBuildClasspathManager.getAllClasspathEntries();
  }

  @Override
  public PsiClass findClass(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) {
    PsiClass aClass = super.findClass(qualifiedName, scope);
    if (aClass == null || scope instanceof ExternalModuleBuildGlobalSearchScope || scope instanceof EverythingGlobalScope) {
      return aClass;
    }

    PsiFile containingFile = aClass.getContainingFile();
    VirtualFile file = containingFile != null ? containingFile.getVirtualFile() : null;
    return (file != null && !ProjectFileIndex.SERVICE.getInstance(myProject).isInContent(file)) ? aClass : null;
  }
}


text:
package cloudfrontiface_test

import (
	"testing"

	"github.com/awslabs/aws-sdk-go/service/cloudfront"
	"github.com/awslabs/aws-sdk-go/service/cloudfront/cloudfrontiface"
	"github.com/stretchr/testify/assert"
)

func TestInterface(t *testing.T) {
	assert.Implements(t, (*cloudfrontiface.CloudFrontAPI)(nil), cloudfront.New(nil))
}


text:
layout: default
additional_css: rejoindre
title: Rejoindre la communauté
---

REJOIGNEZ
LA COMMUNAUTE D'AGENTS PUBLICS

        Télécharger le flyer

          Je m'inscris

Rencontrez la communauté le 3ème mardi de chaque mois, au 20 avenue de Ségur ou en ligne !