text:
HDP_VERSION=2.2.4.2-2
HDFS_HDP_BASE_DIR=/hdp/apps/$HDP_VERSION
DT=`date +%Y%m%d-%H%M`

REQUIRED_FILES="hadoop/mapreduce.tar.gz tez/lib/tez.tar.gz hive/hive.tar.gz pig/pig.tar.gz sqoop/sqoop.tar.gz"
echo ""
echo ""
echo "Installing/Validating Libraries for HDP Version: ${HDP_VERSION}"
echo ""
echo ""
echo "Checking for required files in:"
echo "    - /usr/hdp/current"

# Ensure that the needed files exists on this host
if [ -f /tmp/mapreduce.tar.gz ]; then
    rm /tmp/mapreduce.tar.gz
fi
if [ -f /tmp/tez.tar.gz ]; then
    rm /tmp/tez.tar.gz
fi
if [ -f /tmp/hive.tar.gz ]; then
    rm /tmp/hive.tar.gz
fi
if [ -f /tmp/pig.tar.gz ]; then
    rm /tmp/pig.tar.gz
fi
if [ -f /tmp/sqoop.tar.gz ]; then
    rm /tmp/sqoop.tar.gz
fi

cd /usr/hdp/current
tar cfL /tmp/mapreduce.tar.gz hadoop
tar cfL /tmp/tez.tar.gz tez
tar cfL /tmp/hive.tar.gz hive
tar cfL /tmp/pig.tar.gz pig
tar cfL /tmp/sqoop.tar.gz sqoop

cd `dirname $0`

hdfs dfs -test -d /user/$USER && echo "Directory for Superuser exists in HDFS" || hdfs dfs -mkdir -p /user/$USER
hdfs dfs -test -d /user/oozie && echo "Directory for Superuser exists in HDFS" || hdfs dfs -mkdir -p /user/oozie
hdfs dfs -test -d /apps/hive/warehouse && echo "Directory for Hive exists in HDFS" || hdfs dfs -mkdir -p /apps/hive/warehouse
hdfs dfs -test -d /hdp/apps/$HDP_VERSION && echo "Directory for Hive exists in HDFS" || hdfs dfs -mkdir -p /hdp/apps/$HDP_VERSION
hdfs dfs -test -d /tmp && echo "Directory for Hive exists in HDFS" || hdfs dfs -mkdir -p /tmp

hdfs dfs -chmod -R 755 /hdp

# MapReduce Framework
# "mapreduce.application.framework.path" : "/hdp/apps/${hdp.version}/mapreduce/mapreduce.tar.gz#mr-framework",
# /usr/hdp/$HDP_VERSION/hadoop/mapreduce.tar.gz
hdfs dfs -test -d $HDFS_HDP_BASE_DIR/mapreduce && echo "Directory ${HDFS_HDP_BASE_DIR}/mapreduce exists in HDFS" || hdfs dfs -mkdir -p $HDFS_HDP_BASE_DIR/mapreduce
hdfs dfs -test -f $HDFS_HDP_BASE_DIR/mapreduce/mapreduce.tar.gz && echo "File ${HDFS_HDP_BASE_DIR}/mapreduce/mapreduce.tar.gz exists in HDFS" || hdfs dfs -put /tmp/mapreduce.tar.gz $HDFS_HDP_BASE_DIR/mapreduce

# Tez Framework
# "tez.lib.uris" : "/hdp/apps/${hdp.version}/tez/tez.tar.gz",
# /usr/hdp/$HDP_VERSION/tez/lib/tez.tar.gz
hdfs dfs -test -d $HDFS_HDP_BASE_DIR/tez && echo "Directory ${HDFS_HDP_BASE_DIR}/tez exists in HDFS" || hdfs dfs -mkdir -p $HDFS_HDP_BASE_DIR/tez
hdfs dfs -test -f $HDFS_HDP_BASE_DIR/tez/tez.tar.gz && echo "File ${HDFS_HDP_BASE_DIR}/tez/tez.tar.gz exists in HDFS" || hdfs dfs -put /tmp/tez.tar.gz $HDFS_HDP_BASE_DIR/tez

# Templeton Hive Archive
# "templeton.hive.archive" : "hdfs:///hdp/apps/${hdp.version}/hive/hive.tar.gz",
# /usr/hdp/$HDP_VERSION/hive/hive.tar.gz
hdfs dfs -test -d $HDFS_HDP_BASE_DIR/hive && echo "Directory ${HDFS_HDP_BASE_DIR}/hive exists in HDFS" || hdfs dfs -mkdir -p $HDFS_HDP_BASE_DIR/hive
hdfs dfs -test -f $HDFS_HDP_BASE_DIR/hive/hive.tar.gz && echo "File ${HDFS_HDP_BASE_DIR}/hive/hive.tar.gz exists in HDFS" || hdfs dfs -put /tmp/hive.tar.gz $HDFS_HDP_BASE_DIR/hive

# Templeton Pig Archive
# "templeton.pig.archive" : "hdfs:///hdp/apps/${hdp.version}/pig/pig.tar.gz",
#/usr/hdp/$HDP_VERSION/pig/pig.tar.gz
hdfs dfs -test -d $HDFS_HDP_BASE_DIR/pig && echo "Directory ${HDFS_HDP_BASE_DIR}/pig exists in HDFS" || hdfs dfs -mkdir -p $HDFS_HDP_BASE_DIR/pig
hdfs dfs -test -f $HDFS_HDP_BASE_DIR/pig/pig.tar.gz && echo "File ${HDFS_HDP_BASE_DIR}/pig/pig.tar.gz exists in HDFS" || hdfs dfs -put /tmp/pig.tar.gz $HDFS_HDP_BASE_DIR/pig

# Templeton Sqoop Archive
# "templeton.sqoop.archive" : "hdfs:///hdp/apps/${hdp.version}/sqoop/sqoop.tar.gz",
#/usr/hdp/$HDP_VERSION/sqoop/sqoop.tar.gz
hdfs dfs -test -d $HDFS_HDP_BASE_DIR/sqoop && echo "Directory ${HDFS_HDP_BASE_DIR}/sqoop exists in HDFS" || hdfs dfs -mkdir -p $HDFS_HDP_BASE_DIR/sqoop
hdfs dfs -test -f $HDFS_HDP_BASE_DIR/sqoop/sqoop.tar.gz && echo "File ${HDFS_HDP_BASE_DIR}/sqoop/sqoop.tar.gz exists in HDFS" || hdfs dfs -put /tmp/sqoop.tar.gz $HDFS_HDP_BASE_DIR/sqoop

# Templeton Streaming Jar
# "templeton.streaming.jar" : "hdfs:///hdp/apps/${hdp.version}/mapreduce/hadoop-streaming.jar",
# /usr/hdp/$HDP_VERSION/hadoop-mapreduce/hadoop-streaming.jar
hdfs dfs -test -d $HDFS_HDP_BASE_DIR/mapreduce && echo "Directory ${HDFS_HDP_BASE_DIR}/mapreduce exists in HDFS" || hdfs dfs -mkdir -p $HDFS_HDP_BASE_DIR/mapreduce
hdfs dfs -test -f $HDFS_HDP_BASE_DIR/mapreduce/hadoop-streaming.jar && echo "File ${HDFS_HDP_BASE_DIR}/mapreduce/hadoop-streaming.jar exists in HDFS" || hdfs dfs -put /usr/hdp/current/hadoop/share/hadoop/tools/lib/hadoop-streaming-$HDP_VERSION.jar $HDFS_HDP_BASE_DIR/mapreduce/hadoop-streaming.jar

#/usr/hdp/current/hadoop/share/hadoop/tools/lib/hadoop-streaming-2.6.0.2.2.0.0-2041.jar
#/usr/hdp/current/oozie/oozie-sharelib-4.1.0.2.2.0.0-2041.tar.gz

# Reset the Oozie Libraries.
hdfs dfs -test -d /user/oozie/share && echo "Oozie share/lib exists. Backing up and reinstalling";hdfs dfs -mv /user/oozie/share /user/oozie/share.$DT || echo "Oozie share/lib doesn't exist, rebuilding..."

if [ -d /tmp/share ]; then
    rm -rf /tmp/share
fi

echo "Making a copy of the Oozie Sharelib tarball"
cp /usr/hdp/current/oozie/oozie-sharelib-4.1.0.$HDP_VERSION.tar.gz /tmp
cd /tmp
echo "Expanding Oozie ShareLib tarball"
tar xfz oozie-sharelib-4.1.0.$HDP_VERSION.tar.gz

echo "Installing Oozie Sharelib onto HDFS"
hdfs dfs -put /tmp/share /user/oozie/

echo "Setting Oozie Sharelib permissions on HDFS"
# Validate Permissions
hdfs dfs -chmod -R o+rx /user/oozie/share


text:
package org.openehealth.ipf.commons.ihe.fhir.iti65;

import org.openehealth.ipf.commons.audit.AuditContext;
import org.openehealth.ipf.commons.audit.codes.ParticipantObjectIdTypeCode;
import org.openehealth.ipf.commons.audit.codes.ParticipantObjectTypeCodeRole;
import org.openehealth.ipf.commons.audit.model.AuditMessage;
import org.openehealth.ipf.commons.ihe.core.atna.event.PHIImportBuilder;
import org.openehealth.ipf.commons.ihe.fhir.audit.codes.FhirEventTypeCode;

import java.util.Collections;

/**
 * @author Christian Ohr
 */
public class Iti65ServerAuditStrategy extends Iti65AuditStrategy {

    public Iti65ServerAuditStrategy() {
        super(true);
    }

    @Override
    public AuditMessage[] makeAuditMessage(AuditContext auditContext, Iti65AuditDataset auditDataset) {
        return new PHIImportBuilder<>(auditContext, auditDataset, FhirEventTypeCode.ProvideDocumentBundle)
                .setPatient(auditDataset.getPatientId())
                .addImportedEntity(
                        auditDataset.getDocumentManifestUuid(),
                        ParticipantObjectIdTypeCode.XdsMetadata,
                        ParticipantObjectTypeCodeRole.Job,
                        Collections.emptyList())
                .getMessages();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * RakLib network library
 *
 *
 * This project is not affiliated with Jenkins Software LLC nor RakNet.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 */

namespace raklib\server;

use raklib\protocol\ACK;
use raklib\protocol\CLIENT_CONNECT_DataPacket;
use raklib\protocol\CLIENT_DISCONNECT_DataPacket;
use raklib\protocol\CLIENT_HANDSHAKE_DataPacket;
use raklib\protocol\DATA_PACKET_0;
use raklib\protocol\DATA_PACKET_4;
use raklib\protocol\DataPacket;
use raklib\protocol\EncapsulatedPacket;
use raklib\protocol\NACK;
use raklib\protocol\OPEN_CONNECTION_REPLY_1;
use raklib\protocol\OPEN_CONNECTION_REPLY_2;
use raklib\protocol\OPEN_CONNECTION_REQUEST_1;
use raklib\protocol\OPEN_CONNECTION_REQUEST_2;
use raklib\protocol\Packet;
use raklib\protocol\PacketReliability;
use raklib\protocol\PING_DataPacket;
use raklib\protocol\PONG_DataPacket;
use raklib\protocol\SERVER_HANDSHAKE_DataPacket;
use raklib\RakLib;

class Session{
	const STATE_UNCONNECTED = 0;
	const STATE_CONNECTING_1 = 1;
	const STATE_CONNECTING_2 = 2;
	const STATE_CONNECTED = 3;

	const MAX_SPLIT_SIZE = 128;
	const MAX_SPLIT_COUNT = 4;

	public static $WINDOW_SIZE = 2048;

	private $messageIndex = 0;
	private $channelIndex = [];

	/** @var SessionManager */
	private $sessionManager;
	private $address;
	private $port;
	private $state = self::STATE_UNCONNECTED;
	private $mtuSize = 548; //Min size
	private $id = 0;
	private $splitID = 0;

	private $sendSeqNumber = 0;
	private $lastSeqNumber = -1;

	private $lastUpdate;
	private $startTime;

	private $isTemporal = true;

	/** @var DataPacket[] */
	private $packetToSend = [];

	private $isActive;

	/** @var int[] */
	private $ACKQueue = [];
	/** @var int[] */
	private $NACKQueue = [];

	/** @var DataPacket[] */
	private $recoveryQueue = [];

	/** @var DataPacket[][] */
	private $splitPackets = [];

	/** @var int[][] */
	private $needACK = [];

	/** @var DataPacket */
	private $sendQueue;

	private $windowStart;
	private $receivedWindow = [];
	private $windowEnd;

	private $reliableWindowStart;
	private $reliableWindowEnd;
	private $reliableWindow = [];
	private $lastReliableIndex = -1;

	public function __construct(SessionManager $sessionManager, $address, $port){
		$this->sessionManager = $sessionManager;
		$this->address = $address;
		$this->port = $port;
		$this->sendQueue = new DATA_PACKET_4();
		$this->lastUpdate = microtime(true);
		$this->startTime = microtime(true);
		$this->isActive = false;
		$this->windowStart = -1;
		$this->windowEnd = self::$WINDOW_SIZE;

		$this->reliableWindowStart = 0;
		$this->reliableWindowEnd = self::$WINDOW_SIZE;

		for($i = 0; $i < 32; ++$i){
			$this->channelIndex[$i] = 0;
		}
	}

	public function getAddress(){
		return $this->address;
	}

	public function getPort(){
		return $this->port;
	}

	public function getID(){
		return $this->id;
	}

	public function update($time){
		if(!$this->isActive and ($this->lastUpdate + 10) < $time){
			$this->disconnect("timeout");

			return;
		}
		$this->isActive = false;

		if(count($this->ACKQueue) > 0){
			$pk = new ACK();
			$pk->packets = $this->ACKQueue;
			$this->sendPacket($pk);
			$this->ACKQueue = [];
		}

		if(count($this->NACKQueue) > 0){
			$pk = new NACK();
			$pk->packets = $this->NACKQueue;
			$this->sendPacket($pk);
			$this->NACKQueue = [];
		}

		if(count($this->packetToSend) > 0){
			$limit = 16;
			foreach($this->packetToSend as $k => $pk){
				$pk->sendTime = $time;
				$pk->encode();
				$this->recoveryQueue[$pk->seqNumber] = $pk;
				unset($this->packetToSend[$k]);
				$this->sendPacket($pk);

				if(--$limit <= 0){
					break;
				}
			}

			if(count($this->packetToSend) > self::$WINDOW_SIZE){
				$this->packetToSend = [];
			}
		}

		if(count($this->needACK) > 0){
			foreach($this->needACK as $identifierACK => $indexes){
				if(count($indexes) === 0){
					unset($this->needACK[$identifierACK]);
					$this->sessionManager->notifyACK($this, $identifierACK);
				}
			}
		}

		foreach($this->recoveryQueue as $seq => $pk){
			if($pk->sendTime < (time() - 8)){
				$this->packetToSend[] = $pk;
				unset($this->recoveryQueue[$seq]);
			}else{
				break;
			}
		}

		foreach($this->receivedWindow as $seq => $bool){
			if($seq < $this->windowStart){
				unset($this->receivedWindow[$seq]);
			}else{
				break;
			}
		}

		$this->sendQueue();
	}

	public function disconnect($reason = "unknown"){
		$this->sessionManager->removeSession($this, $reason);
	}

	private function sendPacket(Packet $packet){
		$this->sessionManager->sendPacket($packet, $this->address, $this->port);
	}

	public function sendQueue(){
		if(count($this->sendQueue->packets) > 0){
			$this->sendQueue->seqNumber = $this->sendSeqNumber++;
			$this->sendPacket($this->sendQueue);
			$this->sendQueue->sendTime = microtime(true);
			$this->recoveryQueue[$this->sendQueue->seqNumber] = $this->sendQueue;
			$this->sendQueue = new DATA_PACKET_4();
		}
	}

	/**
	 * @param EncapsulatedPacket $pk
	 * @param int                $flags
	 */
	private function addToQueue(EncapsulatedPacket $pk, $flags = RakLib::PRIORITY_NORMAL){
		$priority = $flags & 0b00000111;
		if($pk->needACK and $pk->messageIndex !== null){
			$this->needACK[$pk->identifierACK][$pk->messageIndex] = $pk->messageIndex;
		}
		if($priority === RakLib::PRIORITY_IMMEDIATE){ //Skip queues
			$packet = new DATA_PACKET_0();
			$packet->seqNumber = $this->sendSeqNumber++;
			if($pk->needACK){
				$packet->packets[] = clone $pk;
				$pk->needACK = false;
			}else{
				$packet->packets[] = $pk->toBinary();
			}

			$this->sendPacket($packet);
			$packet->sendTime = microtime(true);
			$this->recoveryQueue[$packet->seqNumber] = $packet;

			return;
		}
		$length = $this->sendQueue->length();
		if($length + $pk->getTotalLength() > $this->mtuSize){
			$this->sendQueue();
		}

		if($pk->needACK){
			$this->sendQueue->packets[] = clone $pk;
			$pk->needACK = false;
		}else{
			$this->sendQueue->packets[] = $pk->toBinary();
		}
	}

	/**
	 * @param EncapsulatedPacket $packet
	 * @param int                $flags
	 */
	public function addEncapsulatedToQueue(EncapsulatedPacket $packet, $flags = RakLib::PRIORITY_NORMAL){

		if(($packet->needACK = ($flags & RakLib::FLAG_NEED_ACK) > 0) === true){
			$this->needACK[$packet->identifierACK] = [];
		}

		if(
			$packet->reliability === PacketReliability::RELIABLE or
			$packet->reliability === PacketReliability::RELIABLE_ORDERED or
			$packet->reliability === PacketReliability::RELIABLE_SEQUENCED or
			$packet->reliability === PacketReliability::RELIABLE_WITH_ACK_RECEIPT or
			$packet->reliability === PacketReliability::RELIABLE_ORDERED_WITH_ACK_RECEIPT
		){
			$packet->messageIndex = $this->messageIndex++;

			if($packet->reliability === PacketReliability::RELIABLE_ORDERED){
				$packet->orderIndex = $this->channelIndex[$packet->orderChannel]++;
			}
		}

		if($packet->getTotalLength() + 4 > $this->mtuSize){
			//IP header size (20 bytes) + UDP header size (8 bytes) + RakNet weird (8 bytes) + datagram header size (4 bytes) + max encapsulated packet header size (20 bytes)
			$buffers = str_split($packet->buffer, $this->mtuSize - 60);
			$splitID = ++$this->splitID % 65536;
			foreach($buffers as $count => $buffer){
				$pk = new EncapsulatedPacket();
				$pk->splitID = $splitID;
				$pk->hasSplit = true;
				$pk->splitCount = count($buffers);
				$pk->reliability = $packet->reliability;
				$pk->splitIndex = $count;
				$pk->buffer = $buffer;
				if($count > 0){
					$pk->messageIndex = $this->messageIndex++;
				}else{
					$pk->messageIndex = $packet->messageIndex;
				}
				if($pk->reliability === PacketReliability::RELIABLE_ORDERED){
					$pk->orderChannel = $packet->orderChannel;
					$pk->orderIndex = $packet->orderIndex;
				}
				$this->addToQueue($pk, $flags | RakLib::PRIORITY_IMMEDIATE);
			}
		}else{
			$this->addToQueue($packet, $flags);
		}
	}

	private function handleSplit(EncapsulatedPacket $packet){
		if($packet->splitCount >= self::MAX_SPLIT_SIZE or $packet->splitIndex >= self::MAX_SPLIT_SIZE or $packet->splitIndex < 0){
			return;
		}

		if(!isset($this->splitPackets[$packet->splitID])){
			if(count($this->splitPackets) >= self::MAX_SPLIT_COUNT){
				return;
			}
			$this->splitPackets[$packet->splitID] = [$packet->splitIndex => $packet];
		}else{
			$this->splitPackets[$packet->splitID][$packet->splitIndex] = $packet;
		}

		if(count($this->splitPackets[$packet->splitID]) === $packet->splitCount){
			$pk = new EncapsulatedPacket();
			$pk->buffer = "";
			for($i = 0; $i < $packet->splitCount; ++$i){
				$pk->buffer .= $this->splitPackets[$packet->splitID][$i]->buffer;
			}

			$pk->length = strlen($pk->buffer);
			unset($this->splitPackets[$packet->splitID]);

			$this->handleEncapsulatedPacketRoute($pk);
		}
	}

	private function handleEncapsulatedPacket(EncapsulatedPacket $packet){
		if($packet->messageIndex === null){
			$this->handleEncapsulatedPacketRoute($packet);
		}else{
			if($packet->messageIndex < $this->reliableWindowStart or $packet->messageIndex > $this->reliableWindowEnd){
				return;
			}

			if(($packet->messageIndex - $this->lastReliableIndex) === 1){
				$this->lastReliableIndex++;
				$this->reliableWindowStart++;
				$this->reliableWindowEnd++;
				$this->handleEncapsulatedPacketRoute($packet);

				if(count($this->reliableWindow) > 0){
					ksort($this->reliableWindow);

					foreach($this->reliableWindow as $index => $pk){
						if(($index - $this->lastReliableIndex) !== 1){
							break;
						}
						$this->lastReliableIndex++;
						$this->reliableWindowStart++;
						$this->reliableWindowEnd++;
						$this->handleEncapsulatedPacketRoute($pk);
						unset($this->reliableWindow[$index]);
					}
				}
			}else{
				$this->reliableWindow[$packet->messageIndex] = $packet;
			}
		}

	}

	public function getState(){
		return $this->state;
	}

	public function isTemporal(){
		return $this->isTemporal;
	}

	private function handleEncapsulatedPacketRoute(EncapsulatedPacket $packet){
		if($this->sessionManager === null){
			return;
		}

		if($packet->hasSplit){
			if($this->state === self::STATE_CONNECTED){
				$this->handleSplit($packet);
			}

			return;
		}

		$id = ord($packet->buffer{0});
		if($id < 0x80){ //internal data packet
			if($this->state === self::STATE_CONNECTING_2){
				if($id === CLIENT_CONNECT_DataPacket::$ID){
					$dataPacket = new CLIENT_CONNECT_DataPacket;
					$dataPacket->buffer = $packet->buffer;
					$dataPacket->decode();
					$pk = new SERVER_HANDSHAKE_DataPacket;
					$pk->address = $this->address;
					$pk->port = $this->port;
					$pk->sendPing = $dataPacket->sendPing;
					$pk->sendPong = bcadd($pk->sendPing, "1000");
					$pk->encode();

					$sendPacket = new EncapsulatedPacket();
					$sendPacket->reliability = PacketReliability::UNRELIABLE;
					$sendPacket->buffer = $pk->buffer;
					$this->addToQueue($sendPacket, RakLib::PRIORITY_IMMEDIATE);
				}elseif($id === CLIENT_HANDSHAKE_DataPacket::$ID){
					$dataPacket = new CLIENT_HANDSHAKE_DataPacket;
					$dataPacket->buffer = $packet->buffer;
					$dataPacket->decode();

					if($dataPacket->port === $this->sessionManager->getPort() or !$this->sessionManager->portChecking){
						$this->state = self::STATE_CONNECTED; //FINALLY!
						$this->isTemporal = false;
						$this->sessionManager->openSession($this);
					}
				}
			}elseif($id === CLIENT_DISCONNECT_DataPacket::$ID){
				$this->disconnect("client disconnect");
			}elseif($id === PING_DataPacket::$ID){
				$dataPacket = new PING_DataPacket;
				$dataPacket->buffer = $packet->buffer;
				$dataPacket->decode();

				$pk = new PONG_DataPacket;
				$pk->pingID = $dataPacket->pingID;
				$pk->encode();

				$sendPacket = new EncapsulatedPacket();
				$sendPacket->reliability = PacketReliability::UNRELIABLE;
				$sendPacket->buffer = $pk->buffer;
				$this->addToQueue($sendPacket);
			}//TODO: add PING/PONG (0x00/0x03) automatic latency measure
		}elseif($this->state === self::STATE_CONNECTED){
			$this->sessionManager->streamEncapsulated($this, $packet);

			//TODO: stream channels
		}else{
			//$this->sessionManager->getLogger()->notice("Received packet before connection: " . bin2hex($packet->buffer));
		}
	}

	public function handlePacket(Packet $packet){
		$this->isActive = true;
		$this->lastUpdate = microtime(true);
		if($this->state === self::STATE_CONNECTED or $this->state === self::STATE_CONNECTING_2){
			if($packet::$ID >= 0x80 and $packet::$ID <= 0x8f and $packet instanceof DataPacket){ //Data packet
				$packet->decode();

				if($packet->seqNumber < $this->windowStart or $packet->seqNumber > $this->windowEnd or isset($this->receivedWindow[$packet->seqNumber])){
					return;
				}

				$diff = $packet->seqNumber - $this->lastSeqNumber;

				unset($this->NACKQueue[$packet->seqNumber]);
				$this->ACKQueue[$packet->seqNumber] = $packet->seqNumber;
				$this->receivedWindow[$packet->seqNumber] = $packet->seqNumber;

				if($diff !== 1){
					for($i = $this->lastSeqNumber + 1; $i < $packet->seqNumber; ++$i){
						if(!isset($this->receivedWindow[$i])){
							$this->NACKQueue[$i] = $i;
						}
					}
				}

				if($diff >= 1){
					$this->lastSeqNumber = $packet->seqNumber;
					$this->windowStart += $diff;
					$this->windowEnd += $diff;
				}

				foreach($packet->packets as $pk){
					$this->handleEncapsulatedPacket($pk);
				}
			}else{
				if($packet instanceof ACK){
					$packet->decode();
					foreach($packet->packets as $seq){
						if(isset($this->recoveryQueue[$seq])){
							foreach($this->recoveryQueue[$seq]->packets as $pk){
								if($pk instanceof EncapsulatedPacket and $pk->needACK and $pk->messageIndex !== null){
									unset($this->needACK[$pk->identifierACK][$pk->messageIndex]);
								}
							}
							unset($this->recoveryQueue[$seq]);
						}
					}
				}elseif($packet instanceof NACK){
					$packet->decode();
					foreach($packet->packets as $seq){
						if(isset($this->recoveryQueue[$seq])){
							$pk = $this->recoveryQueue[$seq];
							$pk->seqNumber = $this->sendSeqNumber++;
							$this->packetToSend[] = $pk;
							unset($this->recoveryQueue[$seq]);
						}
					}
				}
			}

		}elseif($packet::$ID > 0x00 and $packet::$ID < 0x80){ //Not Data packet :)
			$packet->decode();
			if($packet instanceof OPEN_CONNECTION_REQUEST_1){
				$packet->protocol; //TODO: check protocol number and refuse connections
				$pk = new OPEN_CONNECTION_REPLY_1();
				$pk->mtuSize = $packet->mtuSize;
				$pk->serverID = $this->sessionManager->getID();
				$this->sendPacket($pk);
				$this->state = self::STATE_CONNECTING_1;
			}elseif($this->state === self::STATE_CONNECTING_1 and $packet instanceof OPEN_CONNECTION_REQUEST_2){
				$this->id = $packet->clientID;
				if($packet->serverPort === $this->sessionManager->getPort() or !$this->sessionManager->portChecking){
					$this->mtuSize = min(abs($packet->mtuSize), 1464); //Max size, do not allow creating large buffers to fill server memory
					$pk = new OPEN_CONNECTION_REPLY_2();
					$pk->mtuSize = $this->mtuSize;
					$pk->serverID = $this->sessionManager->getID();
					$pk->clientAddress = $this->address;
					$pk->clientPort = $this->port;
					$this->sendPacket($pk);
					$this->state = self::STATE_CONNECTING_2;
				}
			}
		}
	}

	public function close(){
		$data = "\x60\x00\x08\x00\x00\x00\x00\x00\x00\x00\x15";
		$this->addEncapsulatedToQueue(EncapsulatedPacket::fromBinary($data)); //CLIENT_DISCONNECT packet 0x15
		$this->sendQueue();
		$this->sessionManager = null;
	}
}


text:
<?php

namespace Drupal\KernelTests\Core\Entity;

use Drupal\language\Entity\ConfigurableLanguage;

/**
 * Tests correct field method invocation order.
 *
 * @group Entity
 */
class ContentEntityFieldMethodInvocationOrderTest extends EntityKernelTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  protected static $modules = ['language', 'system', 'entity_test'];

  /**
   * The EntityTest entity type storage.
   *
   * @var \Drupal\Core\Entity\ContentEntityStorageInterface
   */
  protected $entityTestFieldMethodsStorage;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    // Enable an additional language.
    ConfigurableLanguage::createFromLangcode('de')->save();
    ConfigurableLanguage::createFromLangcode('fr')->save();

    $this->installEntitySchema('entity_test_field_methods');

    $this->entityTestFieldMethodsStorage = $this->entityTypeManager->getStorage('entity_test_field_methods');
  }

  /**
   * Tests correct field method invocation order.
   */
  public function testFieldMethodInvocationOrder() {

    // Create a test entity.
    $entity = $this->entityTestFieldMethodsStorage->create([
      'name' => $this->randomString(),
      'langcode' => 'de',
    ]);
    $entity->save();

    $entity->addTranslation('fr')
      ->save();

    // Reset the current value of the test field.
    foreach (['de', 'fr'] as $langcode) {
      $entity->getTranslation($langcode)->test_invocation_order->value = 0;
    }
    $entity->getTranslation('de')
      ->save();
    // Verify that the field presave method has been invoked in the correct
    // entity translation order.
    $this->assertGreaterThan($entity->getTranslation('de')->test_invocation_order->value, $entity->getTranslation('fr')->test_invocation_order->value);

    // Reset the current value of the test field.
    foreach (['de', 'fr'] as $langcode) {
      $entity->getTranslation($langcode)->test_invocation_order->value = 0;
    }
    $entity->getTranslation('fr')
      ->save();
    // Verify that the field presave method has been invoked in the correct
    // entity translation order.
    $this->assertGreaterThan($entity->getTranslation('fr')->test_invocation_order->value, $entity->getTranslation('de')->test_invocation_order->value);
  }

}


text:
/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * MILR.java
 * Copyright (C) 2005 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.classifiers.mi;

import weka.classifiers.Classifier;
import weka.core.Capabilities;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.MultiInstanceCapabilitiesHandler;
import weka.core.Optimization;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.SelectedTag;
import weka.core.Tag;
import weka.core.Utils;
import weka.core.Capabilities.Capability;

import java.util.Enumeration;
import java.util.Vector;

/**

 * Uses either standard or collective multi-instance assumption, but within linear regression. For the collective assumption, it offers arithmetic or geometric mean for the posteriors.
 *

 *

 * Valid options are:

 *
 *
 -D
 *  Turn on debugging output.

 *
 *
 -R <ridge>
 *  Set the ridge in the log-likelihood.

 *
 *
 -A [0|1|2]
 *  Defines the type of algorithm:
 *   0. standard MI assumption
 *   1. collective MI assumption, arithmetic mean for posteriors
 *   2. collective MI assumption, geometric mean for posteriors

 *

 *
 * @author Eibe Frank (eibe@cs.waikato.ac.nz)
 * @author Xin Xu (xx5@cs.waikato.ac.nz)
 * @version $Revision: 9144 $
 */
public class MILR
  extends Classifier
  implements OptionHandler, MultiInstanceCapabilitiesHandler {

  /** for serialization */
  static final long serialVersionUID = 1996101190172373826L;

  protected double[] m_Par;

  /** The number of the class labels */
  protected int m_NumClasses;

  /** The ridge parameter. */
  protected double m_Ridge = 1e-6;

  /** Class labels for each bag */
  protected int[] m_Classes;

  /** MI data */
  protected double[][][] m_Data;

  /** All attribute names */
  protected Instances m_Attributes;

  protected double[] xMean = null, xSD = null;

  /** the type of processing */
  protected int m_AlgorithmType = ALGORITHMTYPE_DEFAULT;

  /** standard MI assumption */
  public static final int ALGORITHMTYPE_DEFAULT = 0;
  /** collective MI assumption, arithmetic mean for posteriors */
  public static final int ALGORITHMTYPE_ARITHMETIC = 1;
  /** collective MI assumption, geometric mean for posteriors */
  public static final int ALGORITHMTYPE_GEOMETRIC = 2;
  /** the types of algorithms */
  public static final Tag [] TAGS_ALGORITHMTYPE = {
    new Tag(ALGORITHMTYPE_DEFAULT, "standard MI assumption"),
    new Tag(ALGORITHMTYPE_ARITHMETIC, "collective MI assumption, arithmetic mean for posteriors"),
    new Tag(ALGORITHMTYPE_GEOMETRIC, "collective MI assumption, geometric mean for posteriors"),
  };

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for
   * displaying in the explorer/experimenter gui
   */
  public String globalInfo() {
    return
        "Uses either standard or collective multi-instance assumption, but "
      + "within linear regression. For the collective assumption, it offers "
      + "arithmetic or geometric mean for the posteriors.";
  }

  /**
   * Returns an enumeration describing the available options
   *
   * @return an enumeration of all the available options
   */
  public Enumeration listOptions() {
    Vector result = new Vector();

    result.addElement(new Option(
          "\tTurn on debugging output.",
          "D", 0, "-D"));

    result.addElement(new Option(
        "\tSet the ridge in the log-likelihood.",
        "R", 1, "-R <ridge>"));

    result.addElement(new Option(
        "\tDefines the type of algorithm:\n"
        + "\t 0. standard MI assumption\n"
        + "\t 1. collective MI assumption, arithmetic mean for posteriors\n"
        + "\t 2. collective MI assumption, geometric mean for posteriors",
        "A", 1, "-A [0|1|2]"));

    return result.elements();
  }

  /**
   * Parses a given list of options.
   *
   * @param options the list of options as an array of strings
   * @throws Exception if an option is not supported
   */
  public void setOptions(String[] options) throws Exception {
    String      tmpStr;

    setDebug(Utils.getFlag('D', options));

    tmpStr = Utils.getOption('R', options);
    if (tmpStr.length() != 0)
      setRidge(Double.parseDouble(tmpStr));
    else
      setRidge(1.0e-6);

    tmpStr = Utils.getOption('A', options);
    if (tmpStr.length() != 0) {
      setAlgorithmType(new SelectedTag(Integer.parseInt(tmpStr), TAGS_ALGORITHMTYPE));
    } else {
      setAlgorithmType(new SelectedTag(ALGORITHMTYPE_DEFAULT, TAGS_ALGORITHMTYPE));
    }
  }

  /**
   * Gets the current settings of the classifier.
   *
   * @return an array of strings suitable for passing to setOptions
   */
  public String[] getOptions() {
    Vector        result;

    result = new Vector();

    if (getDebug())
      result.add("-D");

    result.add("-R");
    result.add("" + getRidge());

    result.add("-A");
    result.add("" + m_AlgorithmType);

    return (String[]) result.toArray(new String[result.size()]);
  }

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for
   * displaying in the explorer/experimenter gui
   */
  public String ridgeTipText() {
    return "The ridge in the log-likelihood.";
  }

  /**
   * Sets the ridge in the log-likelihood.
   *
   * @param ridge the ridge
   */
  public void setRidge(double ridge) {
    m_Ridge = ridge;
  }

  /**
   * Gets the ridge in the log-likelihood.
   *
   * @return the ridge
   */
  public double getRidge() {
    return m_Ridge;
  }

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for
   * displaying in the explorer/experimenter gui
   */
  public String algorithmTypeTipText() {
    return "The mean type for the posteriors.";
  }

  /**
   * Gets the type of algorithm.
   *
   * @return the algorithm type
   */
  public SelectedTag getAlgorithmType() {
    return new SelectedTag(m_AlgorithmType, TAGS_ALGORITHMTYPE);
  }

  /**
   * Sets the algorithm type.
   *
   * @param newType the new algorithm type
   */
  public void setAlgorithmType(SelectedTag newType) {
    if (newType.getTags() == TAGS_ALGORITHMTYPE) {
      m_AlgorithmType = newType.getSelectedTag().getID();
    }
  }

  private class OptEng
    extends Optimization {

    /** the type to use
     * @see MILR#TAGS_ALGORITHMTYPE */
    private int m_Type;

    /**
     * initializes the object
     *
     * @param type      the type top use
     * @see MILR#TAGS_ALGORITHMTYPE
     */
    public OptEng(int type) {
      super();

      m_Type = type;
    }

    /**
     * Evaluate objective function
     * @param x the current values of variables
     * @return the value of the objective function
     */
    protected double objectiveFunction(double[] x){
      double nll = 0; // -LogLikelihood

      switch (m_Type) {
        case ALGORITHMTYPE_DEFAULT:
          for(int i=0; i<m_Classes.length; i++){ // ith bag
            int nI = m_Data[i][0].length; // numInstances in ith bag
            double bag = 0.0, // NLL of each bag
                   prod = 0.0;   // Log-prob.

            for(int j=0; j<nI; j++){
              double exp=0.0;
              for(int k=m_Data[i].length-1; k>=0; k--)
                exp += m_Data[i][k][j]*x[k+1];
              exp += x[0];
              exp = Math.exp(exp);

              if(m_Classes[i]==1)
                prod -= Math.log(1.0+exp);
              else
                bag += Math.log(1.0+exp);
            }

            if(m_Classes[i]==1)
              bag = -Math.log(1.0-Math.exp(prod));

            nll += bag;
          }
          break;

        case ALGORITHMTYPE_ARITHMETIC:
          for(int i=0; i<m_Classes.length; i++){ // ith bag
            int nI = m_Data[i][0].length; // numInstances in ith bag
            double bag = 0;  // NLL of each bag

            for(int j=0; j<nI; j++){
              double exp=0.0;
              for(int k=m_Data[i].length-1; k>=0; k--)
                exp += m_Data[i][k][j]*x[k+1];
              exp += x[0];
              exp = Math.exp(exp);

              if(m_Classes[i] == 1)
                bag += 1.0-1.0/(1.0+exp); // To avoid exp infinite
              else
                bag += 1.0/(1.0+exp);
            }
            bag /= (double)nI;

            nll -= Math.log(bag);
          }
          break;

        case ALGORITHMTYPE_GEOMETRIC:
          for(int i=0; i<m_Classes.length; i++){ // ith bag
            int nI = m_Data[i][0].length; // numInstances in ith bag
            double bag = 0;   // Log-prob.

            for(int j=0; j<nI; j++){
              double exp=0.0;
              for(int k=m_Data[i].length-1; k>=0; k--)
                exp += m_Data[i][k][j]*x[k+1];
              exp += x[0];

              if(m_Classes[i]==1)
                bag -= exp/(double)nI;
              else
                bag += exp/(double)nI;
            }

            nll += Math.log(1.0+Math.exp(bag));
          }
          break;
      }

      // ridge: note that intercepts NOT included
      for(int r=1; r<x.length; r++)
        nll += m_Ridge*x[r]*x[r];

      return nll;
    }

    /**
     * Evaluate Jacobian vector
     * @param x the current values of variables
     * @return the gradient vector
     */
    protected double[] evaluateGradient(double[] x){
      double[] grad = new double[x.length];

      switch (m_Type) {
        case ALGORITHMTYPE_DEFAULT:
          for(int i=0; i<m_Classes.length; i++){ // ith bag
            int nI = m_Data[i][0].length; // numInstances in ith bag

            double denom = 0.0; // denominator, in log-scale
            double[] bag = new double[grad.length]; //gradient update with ith bag

            for(int j=0; j<nI; j++){
              // Compute exp(b0+b1*Xi1j+...)/[1+exp(b0+b1*Xi1j+...)]
              double exp=0.0;
              for(int k=m_Data[i].length-1; k>=0; k--)
                exp += m_Data[i][k][j]*x[k+1];
              exp += x[0];
              exp = Math.exp(exp)/(1.0+Math.exp(exp));

              if(m_Classes[i]==1)
                // Bug fix: it used to be denom += Math.log(1.0+exp);
                // Fixed 21 Jan 2005 (Eibe)
                denom -= Math.log(1.0-exp);

              // Instance-wise update of dNLL/dBk
              for(int p=0; p<x.length; p++){  // pth variable
                double m = 1.0;
                if(p>0) m=m_Data[i][p-1][j];
                bag[p] += m*exp;
              }
            }

            denom = Math.exp(denom);

            // Bag-wise update of dNLL/dBk
            for(int q=0; q<grad.length; q++){
              if(m_Classes[i]==1)
                grad[q] -= bag[q]/(denom-1.0);
              else
                grad[q] += bag[q];
            }
          }
          break;

        case ALGORITHMTYPE_ARITHMETIC:
          for(int i=0; i<m_Classes.length; i++){ // ith bag
            int nI = m_Data[i][0].length; // numInstances in ith bag

            double denom=0.0;
            double[] numrt = new double[x.length];

            for(int j=0; j<nI; j++){
              // Compute exp(b0+b1*Xi1j+...)/[1+exp(b0+b1*Xi1j+...)]
              double exp=0.0;
              for(int k=m_Data[i].length-1; k>=0; k--)
                exp += m_Data[i][k][j]*x[k+1];
              exp += x[0];
              exp = Math.exp(exp);
              if(m_Classes[i]==1)
                denom += exp/(1.0+exp);
              else
                denom += 1.0/(1.0+exp);

              // Instance-wise update of dNLL/dBk
              for(int p=0; p<x.length; p++){  // pth variable
                double m = 1.0;
                if(p>0) m=m_Data[i][p-1][j];
                numrt[p] += m*exp/((1.0+exp)*(1.0+exp));
              }
            }

            // Bag-wise update of dNLL/dBk
            for(int q=0; q<grad.length; q++){
              if(m_Classes[i]==1)
                grad[q] -= numrt[q]/denom;
              else
                grad[q] += numrt[q]/denom;
            }
          }
          break;

        case ALGORITHMTYPE_GEOMETRIC:
          for(int i=0; i<m_Classes.length; i++){ // ith bag
            int nI = m_Data[i][0].length; // numInstances in ith bag
            double bag = 0;
            double[] sumX = new double[x.length];
            for(int j=0; j<nI; j++){
              // Compute exp(b0+b1*Xi1j+...)/[1+exp(b0+b1*Xi1j+...)]
              double exp=0.0;
              for(int k=m_Data[i].length-1; k>=0; k--)
                exp += m_Data[i][k][j]*x[k+1];
              exp += x[0];

              if(m_Classes[i]==1){
                bag -= exp/(double)nI;
                for(int q=0; q<grad.length; q++){
                  double m = 1.0;
                  if(q>0) m=m_Data[i][q-1][j];
                  sumX[q] -= m/(double)nI;
                }
              }
              else{
                bag += exp/(double)nI;
                for(int q=0; q<grad.length; q++){
                  double m = 1.0;
                  if(q>0) m=m_Data[i][q-1][j];
                  sumX[q] += m/(double)nI;
                }
              }
            }

            for(int p=0; p<x.length; p++)
              grad[p] += Math.exp(bag)*sumX[p]/(1.0+Math.exp(bag));
          }
          break;
      }

      // ridge: note that intercepts NOT included
      for(int r=1; r<x.length; r++){
        grad[r] += 2.0*m_Ridge*x[r];
      }

      return grad;
    }

    /**
     * Returns the revision string.
     *
     * @return		the revision
     */
    public String getRevision() {
      return RevisionUtils.extract("$Revision: 9144 $");
    }
  }

  /**
   * Returns default capabilities of the classifier.
   *
   * @return      the capabilities of this classifier
   */
  public Capabilities getCapabilities() {
    Capabilities result = super.getCapabilities();
    result.disableAll();

    // attributes
    result.enable(Capability.NOMINAL_ATTRIBUTES);
    result.enable(Capability.RELATIONAL_ATTRIBUTES);

    // class
    result.enable(Capability.BINARY_CLASS);
    result.enable(Capability.MISSING_CLASS_VALUES);

    // other
    result.enable(Capability.ONLY_MULTIINSTANCE);

    return result;
  }

  /**
   * Returns the capabilities of this multi-instance classifier for the
   * relational data.
   *
   * @return            the capabilities of this object
   * @see               Capabilities
   */
  public Capabilities getMultiInstanceCapabilities() {
    Capabilities result = super.getCapabilities();
    result.disableAll();

    // attributes
    result.enable(Capability.NOMINAL_ATTRIBUTES);
    result.enable(Capability.NUMERIC_ATTRIBUTES);
    result.enable(Capability.DATE_ATTRIBUTES);
    result.enable(Capability.MISSING_VALUES);

    // class
    result.disableAllClasses();
    result.enable(Capability.NO_CLASS);

    return result;
  }

  /**
   * Builds the classifier
   *
   * @param train the training data to be used for generating the
   * boosted classifier.
   * @throws Exception if the classifier could not be built successfully
   */
  public void buildClassifier(Instances train) throws Exception {
    // can classifier handle the data?
    getCapabilities().testWithFail(train);

    // remove instances with missing class
    train = new Instances(train);
    train.deleteWithMissingClass();

    m_NumClasses = train.numClasses();

    int nR = train.attribute(1).relation().numAttributes();
    int nC = train.numInstances();

    m_Data  = new double [nC][nR][];              // Data values
    m_Classes  = new int [nC];                    // Class values
    m_Attributes = train.attribute(1).relation();

    xMean = new double [nR];             // Mean of mean
    xSD   = new double [nR];             // Mode of stddev

    double sY1=0, sY0=0, totIns=0;                          // Number of classes
    int[] missingbags = new int[nR];

    if (m_Debug) {
      System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +"Extracting data...");
    }

    for(int h=0; h<m_Data.length; h++){
      Instance current = train.instance(h);
      m_Classes[h] = (int)current.classValue();  // Class value starts from 0
      Instances currInsts = current.relationalValue(1);
      int nI = currInsts.numInstances();
      totIns += (double)nI;

      for (int i = 0; i < nR; i++) {
        // initialize m_data[][][]
        m_Data[h][i] = new double[nI];
        double avg=0, std=0, num=0;
        for (int k=0; k<nI; k++){
          if(!currInsts.instance(k).isMissing(i)){
            m_Data[h][i][k] = currInsts.instance(k).value(i);
            avg += m_Data[h][i][k];
            std += m_Data[h][i][k]*m_Data[h][i][k];
            num++;
          }
          else
            m_Data[h][i][k] = Double.NaN;
        }

        if(num > 0){
          xMean[i] += avg/num;
          xSD[i] += std/num;
        }
        else
          missingbags[i]++;
      }

      // Class count
      if (m_Classes[h] == 1)
        sY1++;
      else
        sY0++;
    }

    for (int j = 0; j < nR; j++) {
      xMean[j] = xMean[j]/(double)(nC-missingbags[j]);
      xSD[j] = Math.sqrt(Math.abs(xSD[j]/((double)(nC-missingbags[j])-1.0)
            -xMean[j]*xMean[j]*(double)(nC-missingbags[j])/
            ((double)(nC-missingbags[j])-1.0)));
    }

    if (m_Debug) {
      // Output stats about input data
      System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +"Descriptives...");
      System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +sY0 + " bags have class 0 and " +
          sY1 + " bags have class 1");
      System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +"\n Variable     Avg       SD    ");
      for (int j = 0; j < nR; j++)
        System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +Utils.doubleToString(j,8,4)
            + Utils.doubleToString(xMean[j], 10, 4)
            + Utils.doubleToString(xSD[j], 10,4));
    }

    // Normalise input data and remove ignored attributes
    for (int i = 0; i < nC; i++) {
      for (int j = 0; j < nR; j++) {
        for(int k=0; k < m_Data[i][j].length; k++){
          if(xSD[j] != 0){
            if(!Double.isNaN(m_Data[i][j][k]))
              m_Data[i][j][k] = (m_Data[i][j][k] - xMean[j]) / xSD[j];
            else
              m_Data[i][j][k] = 0;
          }
        }
      }
    }

    if (m_Debug) {
      System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +"\nIteration History..." );
    }

    double x[] = new double[nR + 1];
    x[0] =  Math.log((sY1+1.0) / (sY0+1.0));
    double[][] b = new double[2][x.length];
    b[0][0] = Double.NaN;
    b[1][0] = Double.NaN;
    for (int q=1; q < x.length;q++){
      x[q] = 0.0;
      b[0][q] = Double.NaN;
      b[1][q] = Double.NaN;
    }

    OptEng opt = new OptEng(m_AlgorithmType);
    opt.setDebug(m_Debug);
    m_Par = opt.findArgmin(x, b);
    while(m_Par==null){
      m_Par = opt.getVarbValues();
      if (m_Debug)
        System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +"200 iterations finished, not enough!");
      m_Par = opt.findArgmin(m_Par, b);
    }
    if (m_Debug)
      System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +" -------------<Converged>--------------");

    // feature selection use
    if (m_AlgorithmType == ALGORITHMTYPE_ARITHMETIC) {
      double[] fs = new double[nR];
      for(int k=1; k<nR+1; k++)
        fs[k-1] = Math.abs(m_Par[k]);
      int[] idx = Utils.sort(fs);
      double max = fs[idx[idx.length-1]];
      for(int k=idx.length-1; k>=0; k--)
        System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +m_Attributes.attribute(idx[k]).name()+"\t"+(fs[idx[k]]*100/max));
    }

    // Convert coefficients back to non-normalized attribute units
    for(int j = 1; j < nR+1; j++) {
      if (xSD[j-1] != 0) {
        m_Par[j] /= xSD[j-1];
        m_Par[0] -= m_Par[j] * xMean[j-1];
      }
    }
  }

  /**
   * Computes the distribution for a given exemplar
   *
   * @param exmp the exemplar for which distribution is computed
   * @return the distribution
   * @throws Exception if the distribution can't be computed successfully
   */
  public double[] distributionForInstance(Instance exmp)
    throws Exception {

    // Extract the data
    Instances ins = exmp.relationalValue(1);
    int nI = ins.numInstances(), nA = ins.numAttributes();
    double[][] dat = new double [nI][nA+1];
    for(int j=0; j<nI; j++){
      dat[j][0]=1.0;
      int idx=1;
      for(int k=0; k<nA; k++){
        if(!ins.instance(j).isMissing(k))
          dat[j][idx] = ins.instance(j).value(k);
        else
          dat[j][idx] = xMean[idx-1];
        idx++;
      }
    }

    // Compute the probability of the bag
    double [] distribution = new double[2];
    switch (m_AlgorithmType) {
      case ALGORITHMTYPE_DEFAULT:
        distribution[0]=0.0;  // Log-Prob. for class 0

        for(int i=0; i<nI; i++){
          double exp = 0.0;
          for(int r=0; r<m_Par.length; r++)
            exp += m_Par[r]*dat[i][r];
          exp = Math.exp(exp);

          // Prob. updated for one instance
          distribution[0] -= Math.log(1.0+exp);
        }

        // Prob. for class 0
        distribution[0] = Math.exp(distribution[0]);
        // Prob. for class 1
        distribution[1] = 1.0 - distribution[0];
        break;

      case ALGORITHMTYPE_ARITHMETIC:
        distribution[0]=0.0;  // Prob. for class 0

        for(int i=0; i<nI; i++){
          double exp = 0.0;
          for(int r=0; r<m_Par.length; r++)
            exp += m_Par[r]*dat[i][r];
          exp = Math.exp(exp);

          // Prob. updated for one instance
          distribution[0] += 1.0/(1.0+exp);
        }

        // Prob. for class 0
        distribution[0] /= (double)nI;
        // Prob. for class 1
        distribution[1] = 1.0 - distribution[0];
        break;

      case ALGORITHMTYPE_GEOMETRIC:
        for(int i=0; i<nI; i++){
          double exp = 0.0;
          for(int r=0; r<m_Par.length; r++)
            exp += m_Par[r]*dat[i][r];
          distribution[1] += exp/(double)nI;
        }

        // Prob. for class 1
        distribution[1] = 1.0/(1.0+Math.exp(-distribution[1]));
        // Prob. for class 0
        distribution[0] = 1-distribution[1];
        break;
    }

    return distribution;
  }

  /**
   * Gets a string describing the classifier.
   *
   * @return a string describing the classifer built.
   */
  public String toString() {

    String result = "Modified Logistic Regression";
    if (m_Par == null) {
      return result + ": No model built yet.";
    }

    result += "\nMean type: " + getAlgorithmType().getSelectedTag().getReadable() + "\n";
    result += "\nCoefficients...\n"
      + "Variable      Coeff.\n";
    for (int j = 1, idx=0; j < m_Par.length; j++, idx++) {
      result += m_Attributes.attribute(idx).name();
      result += " "+Utils.doubleToString(m_Par[j], 12, 4);
      result += "\n";
    }

    result += "Intercept:";
    result += " "+Utils.doubleToString(m_Par[0], 10, 4);
    result += "\n";

    result += "\nOdds Ratios...\n"
      + "Variable         O.R.\n";
    for (int j = 1, idx=0; j < m_Par.length; j++, idx++) {
      result += " " + m_Attributes.attribute(idx).name();
      double ORc = Math.exp(m_Par[j]);
      result += " " + ((ORc > 1e10) ?  "" + ORc : Utils.doubleToString(ORc, 12, 4));
    }
    result += "\n";
    return result;
  }

  /**
   * Returns the revision string.
   *
   * @return		the revision
   */
  public String getRevision() {
    return RevisionUtils.extract("$Revision: 9144 $");
  }

  /**
   * Main method for testing this class.
   *
   * @param argv should contain the command line arguments to the
   * scheme (see Evaluation)
   */
  public static void main(String[] argv) {
    runClassifier(new MILR(), argv);
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Consp. fung. (Leipzig) 222 (1805)

#### Original name
Agaricus epichysium var. communis Alb. & Schwein.

### Remarks
null


text:
@implementation TNKCollectionsTitleButton

- (CGSize)sizeThatFits:(CGSize)size
{
    size = [super sizeThatFits:size];

    size.width += self.titleEdgeInsets.right + self.titleEdgeInsets.left + self.imageEdgeInsets.right + self.imageEdgeInsets.left;

    return size;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGRect frame = [super imageRectForContentRect:contentRect];
    frame.origin.x = CGRectGetMaxX(contentRect) - CGRectGetWidth(frame) - self.imageEdgeInsets.right + self.imageEdgeInsets.left;
    return frame;
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGRect frame = [super titleRectForContentRect:contentRect];
    frame.origin.x = CGRectGetMinX(frame) - CGRectGetWidth([self imageRectForContentRect:contentRect]);
    return frame;
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.lonepulse.icklebot.test"
    android:versionCode="1"
    android:versionName="1.1.5-SNAPSHOT" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15"
        tools:ignore="OldTargetApi" />

    <application
        android:name="com.lonepulse.icklebot.test.app.ApplicationServiceImpl"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="android.test.runner" />
    </application>

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.lonepulse.icklebot.test" />

</manifest>


text:
package com.texasgamer.zephyr.model.api;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Zephyr desktop configuration.
 */
public class ZephyrDesktopConfig {

    @Expose
    @SerializedName("type")
    private String mType;
    @Expose
    @SerializedName("updatesEnabled")
    private Boolean mUpdatesEnabled;
    @Expose
    @SerializedName("port")
    private Integer mPort;

    public String getType() {
        return mType;
    }

    public Boolean getUpdatesEnabled() {
        return mUpdatesEnabled;
    }

    public Integer getPort() {
        return mPort;
    }
}


text:
title:  Daily Lesson
date:   01/05/2017
---

### We are working on this lesson
Please come back later


text:
System.register('wiseclock/flarum-ext-post-copyright/components/PostCopyrightSettingsModal', ['flarum/components/SettingsModal', 'flarum/components/Switch', 'flarum/app'], function (_export) {
    'use strict';

    var SettingsModal, Switch, app, PostCopyrightSettingsModal;
    return {
        setters: [function (_flarumComponentsSettingsModal) {
            SettingsModal = _flarumComponentsSettingsModal['default'];
        }, function (_flarumComponentsSwitch) {
            Switch = _flarumComponentsSwitch['default'];
        }, function (_flarumApp) {
            app = _flarumApp['default'];
        }],
        execute: function () {
            PostCopyrightSettingsModal = (function (_SettingsModal) {
                babelHelpers.inherits(PostCopyrightSettingsModal, _SettingsModal);

                function PostCopyrightSettingsModal() {
                    babelHelpers.classCallCheck(this, PostCopyrightSettingsModal);
                    babelHelpers.get(Object.getPrototypeOf(PostCopyrightSettingsModal.prototype), 'constructor', this).apply(this, arguments);
                }

                babelHelpers.createClass(PostCopyrightSettingsModal, [{
                    key: 'className',
                    value: function className() {
                        return 'WiseClockPostCopyrightSettingsModal Modal--medium';
                    }
                }, {
                    key: 'title',
                    value: function title() {
                        return app.translator.trans('wiseclock-post-copyright.admin.settings.title');
                    }
                }, {
                    key: 'getStored',
                    value: function getStored() {
                        var values = this.setting('wiseclock.post-copyright.defaults', '[true, true, true, true]')();
                        return JSON.parse(values);
                    }
                }, {
                    key: 'getDefaults',
                    value: function getDefaults(index) {
                        return this.getStored()[index];
                    }
                }, {
                    key: 'setDefaults',
                    value: function setDefaults(index, value) {
                        var values = this.getStored();
                        values[index] = value;
                        var valueString = JSON.stringify(values);
                        this.setting('wiseclock.post-copyright.defaults')(valueString);
                    }
                }, {
                    key: 'form',
                    value: function form() {
                        var _this = this;

                        return [m('div', { className: 'WiseClockPostCopyright' }, [m('fieldset', { className: 'WiseClockPostCopyright-default-ui' }, [m('legend', {}, app.translator.trans('wiseclock-post-copyright.admin.settings.ui.title')), Switch.component({
                            state: JSON.parse(this.setting('wiseclock.post-copyright.primary_color', 0)()),
                            onchange: this.setting('wiseclock.post-copyright.primary_color'),
                            children: app.translator.trans('wiseclock-post-copyright.admin.settings.ui.primary_color')
                        }), Switch.component({
                            state: JSON.parse(this.setting('wiseclock.post-copyright.discussions_only', 0)()),
                            onchange: this.setting('wiseclock.post-copyright.discussions_only'),
                            children: app.translator.trans('wiseclock-post-copyright.admin.settings.ui.discussions_only')
                        }), Switch.component({
                            state: JSON.parse(this.setting('wiseclock.post-copyright.align_right', 0)()),
                            onchange: this.setting('wiseclock.post-copyright.align_right'),
                            children: app.translator.trans('wiseclock-post-copyright.admin.settings.ui.align_right')
                        }), m('label', {}, app.translator.trans('wiseclock-post-copyright.admin.settings.ui.copyright')), m('input', { className: 'FormControl', bidi: this.setting('wiseclock.post-copyright.icon', '© ') })]), m('fieldset', { className: 'WiseClockPostCopyright-default-edit' }, [m('legend', {}, app.translator.trans('wiseclock-post-copyright.admin.settings.edit.title')), Switch.component({
                            state: JSON.parse(this.setting('wiseclock.post-copyright.allow_trespass', 0)()),
                            onchange: this.setting('wiseclock.post-copyright.allow_trespass'),
                            children: app.translator.trans('wiseclock-post-copyright.admin.settings.edit.allow_trespass')
                        })]), m('fieldset', { className: 'WiseClockPostCopyright-default-switch' }, [m('legend', {}, app.translator.trans('wiseclock-post-copyright.admin.settings.defaults.title')), m('div', { className: 'helpText' }, app.translator.trans('wiseclock-post-copyright.admin.settings.defaults.help')), Switch.component({
                            state: this.getDefaults(0),
                            onchange: function onchange(value) {
                                _this.setDefaults(0, value);
                            },
                            children: app.translator.trans('wiseclock-post-copyright.admin.settings.defaults.authorized')
                        }), Switch.component({
                            state: this.getDefaults(1),
                            onchange: function onchange(value) {
                                _this.setDefaults(1, value);
                            },
                            children: app.translator.trans('wiseclock-post-copyright.admin.settings.defaults.sourced')
                        }), Switch.component({
                            state: this.getDefaults(2),
                            onchange: function onchange(value) {
                                _this.setDefaults(2, value);
                            },
                            children: app.translator.trans('wiseclock-post-copyright.admin.settings.defaults.paid')
                        }), Switch.component({
                            state: this.getDefaults(3),
                            onchange: function onchange(value) {
                                _this.setDefaults(3, value);
                            },
                            children: app.translator.trans('wiseclock-post-copyright.admin.settings.defaults.prohibited')
                        })]), m('fieldset', { className: 'WiseClockPostCopyright-addition' }, [m('legend', {}, app.translator.trans('wiseclock-post-copyright.admin.settings.addition.title')), m('div', { className: 'helpText' }, app.translator.trans('wiseclock-post-copyright.admin.settings.addition.help')), m('pre', 'mit,MIT License,You have to follow The MIT License in order to reproduce this post.'), m('div', { className: 'helpText' }, app.translator.trans('wiseclock-post-copyright.admin.settings.addition.notes')), m('textarea', {
                            className: 'FormControl',
                            rows: 6,
                            value: this.setting('wiseclock.post-copyright.addition')(),
                            oninput: m.withAttr('value', this.setting('wiseclock.post-copyright.addition'))
                        })])])];
                    }
                }]);
                return PostCopyrightSettingsModal;
            })(SettingsModal);

            _export('default', PostCopyrightSettingsModal);
        }
    };
});;
System.register('wiseclock/flarum-ext-post-copyright/main', ['flarum/extend', 'flarum/app', 'wiseclock/flarum-ext-post-copyright/components/PostCopyrightSettingsModal'], function (_export) {
    'use strict';

    var extend, app, PostCopyrightSettingsModal;
    return {
        setters: [function (_flarumExtend) {
            extend = _flarumExtend.extend;
        }, function (_flarumApp) {
            app = _flarumApp['default'];
        }, function (_wiseclockFlarumExtPostCopyrightComponentsPostCopyrightSettingsModal) {
            PostCopyrightSettingsModal = _wiseclockFlarumExtPostCopyrightComponentsPostCopyrightSettingsModal['default'];
        }],
        execute: function () {

            app.initializers.add('wiseclock-post-copyright', function () {
                app.extensionSettings['wiseclock-post-copyright'] = function () {
                    return app.modal.show(new PostCopyrightSettingsModal());
                };
            });
        }
    };
});


text:
@interface WTSelectBarView : UIView

@property (assign, nonatomic) id<UISearchBarDelegate> delegate;

@end


text:
ACCEPTED

#### According to
IRMNG Homonym List

#### Published in
Rev Palaeobot Palynol 84 (1-2), December: 92.

#### Original name
null

### Remarks
null


text:
package com.geth1b.coding.skills.lc;

import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;

/**
 * @author geth1b
 */
public class _305_NumberOfIslandsII_Test {
  private _305_NumberOfIslandsII solution;

  @Before public void setUp() {
    solution = new _305_NumberOfIslandsII();
  }

  @Test public void numIslands2() {
    int[][] positions = new int[][]{{0,0},{0,1},{1,2},{2,1}};
    List<Integer> expected = Arrays.asList(1,1,2,3);
    assertEquals(expected, solution.numIslands2(3, 3, positions));
  }

}


text:
<#
The MIT License (MIT)

Copyright (c) 2015 Objectivity Bespoke Software Specialists

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#>

<#
This file contains tokens, i.e. variables that can be different across environments or nodes.
Resolved $Tokens variable is available in configurations (DSC and functions).
Tokens are inherited from parent environments, so e.g. all Tokens defined in 'Default' environment (default parent of all environments) are available in 'Local' environment,
and child tokens can override parent tokens.

If token value is a string, you can use placeholders ${TokenName} where TokenName is another token name, or predefined 'Node' (destination node name).
If token value is a scriptblock, you can use variables $Tokens, $Node and $Environment.
#>

Environment Default {

    Tokens WindowsFeaturesTestRole @{
        IsClientWindows = $true
        WindowsFeatures = 'IIS-WebServerRole', 'IIS-ASPNET45', 'IIS-WindowsAuthentication'
    }

    Tokens CustomWindowsFeatures @{
        IsClientWindows = $true
        WindowsFeatures = 'IIS-WebServerRole', 'IIS-ASPNET45', 'IIS-WindowsAuthentication'
    }

    Tokens UploadDirectoriesTestRole @{
        UploadDirectories = @{ 'UploadDirectoriesTest' = 'c:\PSCIUploadTest' }
    }

    Tokens IISConfigTestRole @{
        IISConfig = @{
            ApplicationPool = @( @{ Name = 'PSCITestAppPool1'; Identity = 'ApplicationPoolIdentity' },
                                 @{ Name = 'PSCITestAppPool2'; Identity = 'ApplicationPoolIdentity' }
                              )
            Website = @( @{ Name = 'PSCITestWebsite1'; Binding = @{ Port = 801 }; PhysicalPath = 'c:\inetpub\wwwroot\PSCITestWebsite'; ApplicationPool = 'PSCITestAppPool1' },
                         @{ Name = 'PSCITestWebsite2'; Binding = @{ Port = 802 }; PhysicalPath = 'c:\inetpub\wwwroot\PSCITestWebsite2'; ApplicationPool = 'PSCITestAppPool2' }
                           )
            WebApplication = @{ Name = 'PSCITestWebApp'; PhysicalPath = 'c:\inetpub\wwwroot\PSCIMyApp'; Website = 'PSCITestWebsite1'; ApplicationPool = 'PSCITestAppPool1' }
        }

    }
}

Environment Test {
    Tokens WindowsFeaturesTestRole @{
        IsClientWindows = $false
        WindowsFeatures = 'Web-Server', 'Web-Asp-Net45', 'Web-Windows-Auth'
    }

    Tokens CustomWindowsFeatures @{
        IsClientWindows = $false
        WindowsFeatures = 'Web-Server', 'Web-Asp-Net45', 'Web-Windows-Auth'
    }
}


text:
package framework

import (
	"time"

	v1 "k8s.io/api/core/v1"
	storagev1 "k8s.io/api/storage/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/kubernetes/test/e2e/framework"
	e2evolume "k8s.io/kubernetes/test/e2e/framework/volume"
)

// TestDriver represents an interface for a driver to be tested in TestSuite.
// Except for GetDriverInfo, all methods will be called at test runtime and thus
// can use e2eskipper.Skipf, framework.Fatal, Gomega assertions, etc.
type TestDriver interface {
	// GetDriverInfo returns DriverInfo for the TestDriver. This must be static
	// information.
	GetDriverInfo() *DriverInfo

	// SkipUnsupportedTest skips test if Testpattern is not
	// suitable to test with the TestDriver. It gets called after
	// parsing parameters of the test suite and before the
	// framework is initialized. Cheap tests that just check
	// parameters like the cloud provider can and should be
	// done in SkipUnsupportedTest to avoid setting up more
	// expensive resources like framework.Framework. Tests that
	// depend on a connection to the cluster can be done in
	// PrepareTest once the framework is ready.
	SkipUnsupportedTest(TestPattern)

	// PrepareTest is called at test execution time each time a new test case is about to start.
	// It sets up all necessary resources and returns the per-test configuration
	// plus a cleanup function that frees all allocated resources.
	PrepareTest(f *framework.Framework) (*PerTestConfig, func())
}

// TestVolume is the result of PreprovisionedVolumeTestDriver.CreateVolume.
// The only common functionality is to delete it. Individual driver interfaces
// have additional methods that work with volumes created by them.
type TestVolume interface {
	DeleteVolume()
}

// PreprovisionedVolumeTestDriver represents an interface for a TestDriver that has pre-provisioned volume
type PreprovisionedVolumeTestDriver interface {
	TestDriver
	// CreateVolume creates a pre-provisioned volume of the desired volume type.
	CreateVolume(config *PerTestConfig, volumeType TestVolType) TestVolume
}

// InlineVolumeTestDriver represents an interface for a TestDriver that supports InlineVolume
type InlineVolumeTestDriver interface {
	PreprovisionedVolumeTestDriver

	// GetVolumeSource returns a volumeSource for inline volume.
	// It will set readOnly and fsType to the volumeSource, if TestDriver supports both of them.
	// It will return nil, if the TestDriver doesn't support either of the parameters.
	GetVolumeSource(readOnly bool, fsType string, testVolume TestVolume) *v1.VolumeSource
}

// PreprovisionedPVTestDriver represents an interface for a TestDriver that supports PreprovisionedPV
type PreprovisionedPVTestDriver interface {
	PreprovisionedVolumeTestDriver
	// GetPersistentVolumeSource returns a PersistentVolumeSource with volume node affinity for pre-provisioned Persistent Volume.
	// It will set readOnly and fsType to the PersistentVolumeSource, if TestDriver supports both of them.
	// It will return nil, if the TestDriver doesn't support either of the parameters.
	GetPersistentVolumeSource(readOnly bool, fsType string, testVolume TestVolume) (*v1.PersistentVolumeSource, *v1.VolumeNodeAffinity)
}

// DynamicPVTestDriver represents an interface for a TestDriver that supports DynamicPV
type DynamicPVTestDriver interface {
	TestDriver
	// GetDynamicProvisionStorageClass returns a StorageClass dynamic provision Persistent Volume.
	// The StorageClass must be created in the current test's namespace and have
	// a unique name inside that namespace because GetDynamicProvisionStorageClass might
	// be called more than once per test.
	// It will set fsType to the StorageClass, if TestDriver supports it.
	// It will return nil, if the TestDriver doesn't support it.
	GetDynamicProvisionStorageClass(config *PerTestConfig, fsType string) *storagev1.StorageClass
}

// EphemeralTestDriver represents an interface for a TestDriver that supports ephemeral inline volumes.
type EphemeralTestDriver interface {
	TestDriver

	// GetVolume returns the volume attributes for a certain
	// inline ephemeral volume, enumerated starting with #0. Some
	// tests might require more than one volume. They can all be
	// the same or different, depending what the driver supports
	// and/or wants to test.
	//
	// For each volume, the test driver can return volume attributes,
	// whether the resulting volume is shared between different pods (i.e.
	// changes made in one pod are visible in another), and whether the
	// volume can be mounted read/write or only read-only.
	GetVolume(config *PerTestConfig, volumeNumber int) (attributes map[string]string, shared bool, readOnly bool)

	// GetCSIDriverName returns the name that was used when registering with
	// kubelet. Depending on how the driver was deployed, this can be different
	// from DriverInfo.Name. Starting with Kubernetes 1.16, there must also
	// be a CSIDriver object under the same name with a "mode" field that enables
	// usage of the driver for ephemeral inline volumes.
	GetCSIDriverName(config *PerTestConfig) string
}

// SnapshottableTestDriver represents an interface for a TestDriver that supports DynamicSnapshot
type SnapshottableTestDriver interface {
	TestDriver
	// GetSnapshotClass returns a SnapshotClass to create snapshot.
	// It will return nil, if the TestDriver doesn't support it.
	GetSnapshotClass(config *PerTestConfig, parameters map[string]string) *unstructured.Unstructured
}

// CustomTimeoutsTestDriver represents an interface fo a TestDriver that supports custom timeouts.
type CustomTimeoutsTestDriver interface {
	TestDriver
	GetTimeouts() *framework.TimeoutContext
}

// GetDriverTimeouts returns the timeout of the driver operation
func GetDriverTimeouts(driver TestDriver) *framework.TimeoutContext {
	if d, ok := driver.(CustomTimeoutsTestDriver); ok {
		return d.GetTimeouts()
	}
	return framework.NewTimeoutContextWithDefaults()
}

// Capability represents a feature that a volume plugin supports
type Capability string

// Constants related to capabilities and behavior of the driver.
const (
	CapPersistence        Capability = "persistence"        // data is persisted across pod restarts
	CapBlock              Capability = "block"              // raw block mode
	CapFsGroup            Capability = "fsGroup"            // volume ownership via fsGroup
	CapVolumeMountGroup   Capability = "volumeMountGroup"   // Driver has the VolumeMountGroup CSI node capability. Because this is a FSGroup feature, the fsGroup capability must also be set to true.
	CapExec               Capability = "exec"               // exec a file in the volume
	CapSnapshotDataSource Capability = "snapshotDataSource" // support populate data from snapshot
	CapPVCDataSource      Capability = "pvcDataSource"      // support populate data from pvc

	// multiple pods on a node can use the same volume concurrently;
	// for CSI, see:
	// - https://github.com/container-storage-interface/spec/pull/150
	// - https://github.com/container-storage-interface/spec/issues/178
	// - NodeStageVolume in the spec
	CapMultiPODs Capability = "multipods"

	CapRWX                 Capability = "RWX"                 // support ReadWriteMany access modes
	CapControllerExpansion Capability = "controllerExpansion" // support volume expansion for controller
	CapNodeExpansion       Capability = "nodeExpansion"       // support volume expansion for node

	// offlineExpansion and onlineExpansion both default to true when
	// controllerExpansion is true. The only reason to set offlineExpansion
	// to false is when a CSI driver can only expand a volume while it's
	// attached to a pod. Conversely, onlineExpansion can be set to false
	// if the driver can only expand a volume while it is detached.
	CapOfflineExpansion Capability = "offlineExpansion" // supports offline volume expansion (default: true)
	CapOnlineExpansion  Capability = "onlineExpansion"  // supports online volume expansion (default: true)

	CapVolumeLimits     Capability = "volumeLimits"     // support volume limits (can be *very* slow)
	CapSingleNodeVolume Capability = "singleNodeVolume" // support volume that can run on single node (like hostpath)
	CapTopology         Capability = "topology"         // support topology

	// The driver publishes storage capacity information: when the storage class
	// for dynamic provisioning exists, the driver is expected to provide
	// capacity information for it.
	CapCapacity Capability = "capacity"
)

// DriverInfo represents static information about a TestDriver.
type DriverInfo struct {
	// Internal name of the driver, this is used as a display name in the test
	// case and test objects
	Name string
	// Fully qualified plugin name as registered in Kubernetes of the in-tree
	// plugin if it exists and is empty if this DriverInfo represents a CSI
	// Driver
	InTreePluginName string
	FeatureTag       string // FeatureTag for the driver

	// Maximum single file size supported by this driver
	MaxFileSize int64
	// The range of disk size supported by this driver
	SupportedSizeRange e2evolume.SizeRange
	// Map of string for supported fs type
	SupportedFsType sets.String
	// Map of string for supported mount option
	SupportedMountOption sets.String
	// [Optional] Map of string for required mount option
	RequiredMountOption sets.String
	// Map that represents plugin capabilities
	Capabilities map[Capability]bool
	// [Optional] List of access modes required for provisioning, defaults to
	// RWO if unset
	RequiredAccessModes []v1.PersistentVolumeAccessMode
	// [Optional] List of topology keys driver supports
	TopologyKeys []string
	// [Optional] Number of allowed topologies the driver requires.
	// Only relevant if TopologyKeys is set. Defaults to 1.
	// Example: multi-zonal disk requires at least 2 allowed topologies.
	NumAllowedTopologies int
	// [Optional] Scale parameters for stress tests.
	// TODO(#96241): Rename this field to reflect the tests that consume it.
	StressTestOptions *StressTestOptions
	// [Optional] Scale parameters for volume snapshot stress tests.
	VolumeSnapshotStressTestOptions *VolumeSnapshotStressTestOptions
	// [Optional] Parameters for performance tests
	PerformanceTestOptions *PerformanceTestOptions
}

// StressTestOptions contains parameters used for stress tests.
type StressTestOptions struct {
	// Number of pods to create in the test. This may also create
	// up to 1 volume per pod.
	NumPods int
	// Number of times to restart each Pod.
	NumRestarts int
}

// VolumeSnapshotStressTestOptions contains parameters used for volume snapshot stress tests.
type VolumeSnapshotStressTestOptions struct {
	// Number of pods to create in the test. This may also create
	// up to 1 volume per pod.
	NumPods int
	// Number of snapshots to create for each volume.
	NumSnapshots int
}

// Metrics to evaluate performance of an operation
// TODO: Add metrics like median, mode, standard deviation, percentile
type Metrics struct {
	AvgLatency time.Duration
	Throughput float64
}

// PerformanceTestProvisioningOptions contains parameters for
// testing provisioning operation performance.
type PerformanceTestProvisioningOptions struct {
	VolumeSize string
	Count      int
	// Expected metrics from PVC creation till PVC being Bound.
	ExpectedMetrics *Metrics
}

// PerformanceTestOptions contains parameters used for performance tests
type PerformanceTestOptions struct {
	ProvisioningOptions *PerformanceTestProvisioningOptions
}


text:
/* display */
p {
    background-color: purple;
    display: inline;
    margin: 30px;
    visibility: hidden;
}

span {
    background-color: red;
    display: block;
}

div.first {
    background-color: green;
    display: none;
}

div.second {
    background-color: purple;
    display: inline-block;
    width: 200px;
    height: 100px;
    margin: 30px;
    opacity: 0.5
}


text:
package jo.vecmath.logic;

import jo.vecmath.AxisAngle4f;
import jo.vecmath.Matrix3f;
import jo.vecmath.Quat4f;
import jo.vecmath.Tuple3f;

public class Quat4fLogic extends MathUtils
{
    // angles in degrees
    public static Quat4f makeRotateEuler(Tuple3f angles)
    {
        return makeRotateEuler(angles.x, angles.y, angles.z);
    }

    // angles in degrees
    public static Quat4f makeRotateEuler(float x, float y, float z)
    {
        return makeRotate(x*DEG_TO_RAD, y*DEG_TO_RAD, z*DEG_TO_RAD);
    }

    // angles in degrees
    public static Quat4f makeRotate(Tuple3f angles)
    {
        return makeRotate(angles.x, angles.y, angles.z);
    }

    // angles in degrees
    public static Quat4f makeRotate(float x, float y, float z)
    {
        Quat4f xRot = makeRotX(x);
        Quat4f yRot = makeRotY(y);
        Quat4f zRot = makeRotZ(z);
        Quat4f m = new Quat4f();
        m.mul(xRot, yRot);
        m.mul(zRot);
        return m;
    }

    public static Quat4f makeRotate(float x, float y, float z, float a)
    {
        return makeRotate(new AxisAngle4f(x, y, z, a));
    }

    public static Quat4f makeRotate(AxisAngle4f axis)
    {
        Quat4f m = new Quat4f();
        m.set(axis);
        return m;
    }

    public static Quat4f makeRotate(Matrix3f rot)
    {
        Quat4f m = new Quat4f();
        m.set(rot);
        m.normalize();
        return m;
    }

    public static Quat4f makeRotX(float radians)
    {
        return makeRotate(1, 0, 0, radians);
    }

    public static Quat4f makeRotY(float radians)
    {
        return makeRotate(0, 1, 0, radians);
    }

    public static Quat4f makeRotZ(float radians)
    {
        return makeRotate(0, 0, 1, radians);
    }

    public static Quat4f makeIdentity()
    {
        Matrix3f m = new Matrix3f();
        m.setIdentity();
        return makeRotate(m);
    }
}


text:
body {background: #F5F8FA; color: #777;}
#app {position: relative; padding-left: 0; cursor: default;}
#content {max-width: 800px; margin: 4em auto; padding: 0 2em; line-height: 1.5em;}
.pure-form input[type=text], button.pure-button {padding-top: 0.6em; padding-bottom: 0.5em}
button.pure-button {border: 1px solid #0078E7; border-radius: 4px; margin-left: 5px;}
ul {list-style: none; margin: 0; padding: 0;}
a, a:focus, a:active {outline: none;}
.thin {font-weight: 200;}


text:
'use strict';

require('mocha');
require('should');
var util = require('util');
var assert = require('assert');
var Boilerplate = require('..');
var boilerplate;

describe('scaffolds', function() {
  beforeEach(function() {
    boilerplate = new Boilerplate();
  });

  describe('.expand', function() {
    it('should expose an "options" property', function() {
      boilerplate.expand({});
      assert(boilerplate.options);
    });

    it('should expose an expand method', function() {
      assert.strictEqual(typeof boilerplate.expand, 'function');
    });

    it('should detect scaffolds', function() {
      boilerplate.expand({foo: {a: {src: '*'}}});
      assert(boilerplate.scaffolds);
    });

    it('should add scaffolds to the `scaffolds` property', function() {
      boilerplate.expand({
        foo: {a: {src: '*'}},
        bar: {a: {src: '*'}}
      });
      assert(boilerplate.scaffolds.foo);
      assert(boilerplate.scaffolds.bar);
    });

    it('should emit `scaffold`', function() {
      var count = 0;
      boilerplate.on('scaffold', function(scaffold) {
        count++;
      });

      boilerplate.expand({
        foo: {a: {src: '*'}},
        bar: {a: {src: '*'}}
      });
      assert(boilerplate.scaffolds.foo);
      assert(boilerplate.scaffolds.bar);
      assert.equal(count, 2);
    });

    it('should expand src patterns in targets', function() {
      boilerplate.expand({
        foo: {a: {src: '*.md'}},
        bar: {a: {src: '*.js'}},
      });
      assert(Array.isArray(boilerplate.scaffolds.foo.targets.a.files));
      assert(Array.isArray(boilerplate.scaffolds.foo.targets.a.files[0].src));
      assert(boilerplate.scaffolds.foo.targets.a.files[0].src.length);
    });

    it('should use scaffold options on targets', function() {
      boilerplate.expand({
        options: {cwd: 'test/fixtures'},
        foo: {a: {src: 'a.*'}},
        bar: {a: {src: 'one.*'}},
      });
      assert.strictEqual(boilerplate.scaffolds.foo.targets.a.files[0].src[0], 'a.txt');
      assert.strictEqual(boilerplate.scaffolds.bar.targets.a.files[0].src[0], 'one.md');
    });

    it('should retain arbitrary properties on scaffolds', function() {
      boilerplate.expand({
        foo: {a: {src: '*.md', data: {title: 'My Blog'}}},
        bar: {a: {src: '*.js'}},
      });
      assert(boilerplate.scaffolds.foo.targets.a.files[0].data);
      assert(boilerplate.scaffolds.foo.targets.a.files[0].data.title);
      assert.strictEqual(boilerplate.scaffolds.foo.targets.a.files[0].data.title, 'My Blog');
    });

    it('should use plugins on scaffolds', function() {
      boilerplate.use(function(boilerplate) {
        return function fn(node) {
          if (boilerplate.options.data && !node.data) {
            node.data = boilerplate.options.data;
          }
          return fn;
        }
      });

      boilerplate.expand({
        options: {data: {title: 'My Site'}},
        foo: {a: {src: '*.md', data: {title: 'My Blog'}}},
        bar: {a: {src: '*.js'}},
      });

      assert(boilerplate.scaffolds.foo.targets.a.files[0].data);
      assert(boilerplate.scaffolds.foo.targets.a.files[0].data.title);
      assert.strictEqual(boilerplate.scaffolds.foo.targets.a.files[0].data.title, 'My Blog');

      assert(boilerplate.scaffolds.bar.targets.a.options.data);
      assert.strictEqual(boilerplate.scaffolds.bar.targets.a.options.data.title, 'My Site');
      assert(boilerplate.scaffolds.bar.targets.a.files[0].data);
      assert(boilerplate.scaffolds.bar.targets.a.files[0].data.title);
      assert.strictEqual(boilerplate.scaffolds.bar.targets.a.files[0].data.title, 'My Site');
    });
  });

  describe('.expand', function() {
    it('should expose an "options" property', function() {
      boilerplate.expand({});
      assert(boilerplate.options);
    });

    it('should expose an expand method', function() {
      assert.strictEqual(typeof boilerplate.expand, 'function');
    });

    it('should detect scaffolds', function() {
      boilerplate.expand({foo: {a: {src: '*'}}});
      assert(boilerplate.scaffolds);
    });

    it('should add scaffolds to the `scaffolds` property', function() {
      boilerplate.expand({
        foo: {a: {src: '*'}},
        bar: {a: {src: '*'}}
      });
      assert(boilerplate.scaffolds.foo);
      assert(boilerplate.scaffolds.bar);
    });

    it('should emit `scaffold`', function() {
      var count = 0;
      boilerplate.on('scaffold', function(scaffold) {
        count++;
      });

      boilerplate.expand({
        foo: {a: {src: '*'}},
        bar: {a: {src: '*'}}
      });
      assert(boilerplate.scaffolds.foo);
      assert(boilerplate.scaffolds.bar);
      assert.equal(count, 2);
    });

    it('should expand src patterns in targets', function() {
      boilerplate.expand({
        foo: {a: {src: '*.md'}},
        bar: {a: {src: '*.js'}},
      });
      assert(Array.isArray(boilerplate.scaffolds.foo.targets.a.files));
      assert(Array.isArray(boilerplate.scaffolds.foo.targets.a.files[0].src));
      assert(boilerplate.scaffolds.foo.targets.a.files[0].src.length);
    });

    it('should use scaffold options on targets', function() {
      boilerplate.expand({
        options: {cwd: 'test/fixtures'},
        foo: {a: {src: 'a.*'}},
        bar: {a: {src: 'one.*'}},
      });
      assert.strictEqual(boilerplate.scaffolds.foo.targets.a.files[0].src[0], 'a.txt');
      assert.strictEqual(boilerplate.scaffolds.bar.targets.a.files[0].src[0], 'one.md');
    });

    it('should retain arbitrary properties on scaffolds', function() {
      boilerplate.expand({
        foo: {a: {src: '*.md', data: {title: 'My Blog'}}},
        bar: {a: {src: '*.js'}},
      });
      assert(boilerplate.scaffolds.foo.targets.a.files[0].data);
      assert(boilerplate.scaffolds.foo.targets.a.files[0].data.title);
      assert.strictEqual(boilerplate.scaffolds.foo.targets.a.files[0].data.title, 'My Blog');
    });

    it('should use plugins on scaffolds', function() {
      boilerplate.use(function(boilerplate) {
        return function fn(node) {
          if (boilerplate.options.data && !node.data) {
            node.data = boilerplate.options.data;
          }
          return fn;
        }
      });

      boilerplate.expand({
        options: {data: {title: 'My Site'}},
        foo: {a: {src: '*.md', data: {title: 'My Blog'}}},
        bar: {a: {src: '*.js'}},
      });

      assert(boilerplate.scaffolds.foo.targets.a.files[0].data);
      assert(boilerplate.scaffolds.foo.targets.a.files[0].data.title);
      assert.strictEqual(boilerplate.scaffolds.foo.targets.a.files[0].data.title, 'My Blog');

      assert(boilerplate.scaffolds.bar.targets.a.options.data);
      assert.strictEqual(boilerplate.scaffolds.bar.targets.a.options.data.title, 'My Site');
      assert(boilerplate.scaffolds.bar.targets.a.files[0].data);
      assert(boilerplate.scaffolds.bar.targets.a.files[0].data.title);
      assert.strictEqual(boilerplate.scaffolds.bar.targets.a.files[0].data.title, 'My Site');
    });
  });
});


text:
class AddIndexesToRemoteMirror < ActiveRecord::Migration
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  disable_ddl_transaction!

  def up
    add_concurrent_index :remote_mirrors, :last_successful_update_at unless index_exists?(:remote_mirrors, :last_successful_update_at)
  end

  def down
    # rubocop:disable Migration/RemoveIndex
    remove_index :remote_mirrors, :last_successful_update_at if index_exists? :remote_mirrors, :last_successful_update_at
  end
end


text:
indicator-git
=============

See develop branch


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

namespace Microsoft.Azure.Commands.LogicApp.Test.ScenarioTests
{
    using Microsoft.WindowsAzure.Commands.ScenarioTest;
    using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
    using Xunit;

    /// <summary>
    /// Scenario tests for the Workflow trigger commands
    /// </summary>
    public class WorkflowTriggerTests : RMTestBase
    {

        /// <summary>
        /// Test Test-GetAzureLogicAppTrigger command to verify the trigger in the workflow.
        /// </summary>
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestGetAzureLogicAppTrigger()
        {
            WorkflowController.NewInstance.RunPowerShellTest("Test-GetAzureLogicAppTrigger");
        }

        /// <summary>
        /// Test Get-AzureLogicAppTriggerHistory command to verify the trigger history for the workflow.
        /// </summary>
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestGetAzureLogicAppTriggerHistory()
        {
            WorkflowController.NewInstance.RunPowerShellTest("Test-GetAzureLogicAppTriggerHistory");
        }

        /// <summary>
        /// Test Start-AzureLogicAppTrigger command to run the trigger of the workflow.
        /// </summary>
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestStartAzureLogicAppTrigger()
        {
            WorkflowController.NewInstance.RunPowerShellTest("Test-StartAzureLogicAppTrigger");
        }
    }
}


text:
using System;

namespace Internal.Runtime.CompilerServices
{
    public unsafe struct FixupRuntimeTypeHandle
    {
        private IntPtr _value;

        public FixupRuntimeTypeHandle(RuntimeTypeHandle runtimeTypeHandle)
        {
            _value = *(IntPtr*)&runtimeTypeHandle;
        }

        public RuntimeTypeHandle RuntimeTypeHandle
        {
            get
            {
                // Managed debugger uses this logic to figure out the interface's type
                // Update managed debugger too whenever this is changed.
                // See CordbObjectValue::WalkPtrAndTypeData in debug\dbi\values.cpp

                if (((_value.ToInt64()) & 0x1) != 0)
                {
                    return *(RuntimeTypeHandle*)(_value.ToInt64() - 0x1);
                }
                else
                {
                    RuntimeTypeHandle returnValue = default(RuntimeTypeHandle);
                    *(IntPtr*)&returnValue = _value;
                    return returnValue;
                }
            }
        }
    }
}


text:
=head1 NAME

ldifdiff.pl -- Generates LDIF change diff between two sorted LDIF files.

=head1 DESCRIPTION

ldifdiff.pl takes as input two sorted LDIF files, source and target, and
generates on standard output the LDIF changes needed to transform the target
into the source.

=head1 SYNOPSIS

ldifdiff.pl B<-k|--keyattr keyattr> [B<-a|--sourceattrs attr1,attr2,...>] [B<-c|--ciscmp attr1,...>] [B<-n|--numcmp attr1,...>] [B<--dnattrs attr1,...>] [B<--sharedattrs attr1,...>] B<sourcefile> B<targetfile>

=head1 OPTIONS

=over 4

=item B<-k|--keyattr> keyattr

Specifies the key attribute to use when comparing source and target entries.
Entries in both LDIF files must be sorted by this attribute for comparisons to
be meaningful. F<ldifsort.pl> can be used to sort LDIF files by a given
attribute.

=item B<-a|--sourceattrs attr1,attr2,...>

(Optional) Specifies a list of attributes to consider when comparing
source and target entries. By default, all attributes are considered.

=item B<-c|--ciscmp attr1,...>

(Optional) Compare values of the specified attributes case-insensitively. The
default set is: mail manager member objectclass owner uid uniqueMember

=item B<-n|--numcmp attr1,...>

(Optional) Compare values of the specified attributes numerically. The
default set is: employeeNumber

=item B<--dnattrs attr1,...>

(Optional) Specifies a list of attributes to be treated as DNs when being
compared. The default set is: manager member owner uniqueMember

=item B<--sharedattrs attr1,...>

(Optional) Specifies a list of attribues to be treated as "shared" attributes,
where the source may not be a sole authoritative source. When modifying
these attributes, separate "delete" and "add" LDIF changes are generated,
instead of a single "replace" change. The default set is objectClass.

=item B<sourcefile>

Specifies the source LDIF file.

=item B<targetfile>

Specifies the target LDIF file.

=back

=cut

use Net::LDAP;
use Net::LDAP::LDIF;
use Net::LDAP::Util qw(canonical_dn);
use Getopt::Long;

use strict;

my @sourceattrs;
my (%ciscmp, %numcmp, %dnattrs, %sharedattrs);
my $keyattr;
GetOptions('a|sourceattrs=s' => sub { @sourceattrs = split(/,/, $_[1]) },
	'c|ciscmp=s' => sub { my @a = split(/,/,lc $_[1]); @ciscmp{@a} = (1) x @a },
	'dnattrs=s' => sub { my @a = split(/,/,lc $_[1]); @dnattrs{@a} = (1) x @a },
	'k|keyattr=s' => \$keyattr,
	'n|numcmp=s' => sub { my @a = split(/,/,lc $_[1]); @numcmp{@a} = (1) x @a },
	'sharedattrs=s' => sub {my @a=split(/,/,lc $_[1]);@sharedattrs{@a}=(1) x @a}
	);
unless (keys %ciscmp) {
	foreach (qw(cn mail manager member o ou objectclass owner uid uniquemember))
	{ $ciscmp{$_} = 1 }
}
unless (keys %numcmp) {
	foreach (qw(employeenumber))
	{ $numcmp{$_} = 1 }
}
unless (keys %dnattrs) {
	foreach (qw(manager member owner uniquemember))
	{ $dnattrs{$_} = 1 }
}
%sharedattrs = (objectclass => 1)
	unless keys %sharedattrs;

my ($sourcefile, $targetfile);
$sourcefile = shift; $targetfile = shift;

die "usage: $0 -k|--keyattr keyattr [-a|--sourceattrs attr1,attr2,...] [-c|--ciscmp attr1,...] [--dnattrs attr1,...] [--sharedattrs attr1,...] sourcefile targetfile\n"
	unless $keyattr && $sourcefile && $targetfile;

my $source = Net::LDAP::LDIF->new($sourcefile)
	or die "Can't open LDIF file $sourcefile: $!\n";

my $target = Net::LDAP::LDIF->new($targetfile)
	or die "Can't open LDIF file $targetfile: $!\n";

my $ldifout = Net::LDAP::LDIF->new('-', 'w');
$ldifout->{change} = 1;
$ldifout->{wrap} = 78;

diff($source, $target);
exit;

# Gets the relative distinguished name (RDN) attribute
sub rdnattr { ($_[0] =~ /^(.*?)=/)[0] }

# Gets the relative distinguished name (RDN) value
sub rdnval { my $rv = ($_[0] =~ /=(.*)/)[0]; $rv =~ s/(?<!\\),.*//; $rv }

# Gets the rest of the DN (the part after the RDN)
sub dnsuperior { my $rv = ($_[0] =~ /^.*?(?<!\\),(.*)/)[0]; $rv }

sub cmpDNs
{
	my ($adn, $bdn) = @_;
	my $cadn = canonical_dn($adn, casefold => 'lower');
	my $cbdn = canonical_dn($bdn, casefold => 'lower');
	my $rdnattr = lc rdnattr($cadn);
	if ($ciscmp{$rdnattr}) { $cadn = lc($cadn), $cbdn = lc($cbdn) }

	return $numcmp{$rdnattr} ? $cadn <=> $cbdn : $cadn cmp $cbdn;
}

sub cmpEntries
{
	my ($a, $b) = @_;
	my $dncmp = cmpDNs($a->dn, $b->dn);

	if (lc($keyattr) eq 'dn') {
		return ($dncmp, $dncmp);
	}
	else {
		my $aval = $a->get_value($keyattr);
		my $bval = $b->get_value($keyattr);
		if ($ciscmp{$keyattr}) {
			$aval = lc($aval);
			$bval = lc($bval);
		}
		return($numcmp{$keyattr} ? $aval <=> $bval : $aval cmp $bval, $dncmp);
	}
}

# Diffs two LDIF data sources
sub diff
{
	my ($source, $target) = @_;
	my ($sourceentry, $targetentry, $incr_source, $incr_target, @ldifchanges);

	$sourceentry = $source->read_entry();
	$targetentry = $target->read_entry();

	while () {
		# End of all data
		last if !$sourceentry && !$targetentry;

		# End of source data, but more target data. Delete.
		if (!$sourceentry && $targetentry) {
			$targetentry->delete;
			$ldifout->write_entry($targetentry);
			$incr_target = 1, next;
		}

		# End of target data, but more data in source. Add.
		if ($sourceentry && !$targetentry) {
			$ldifout->write_entry($sourceentry);
            $incr_source = 1, next;
		}

		my ($entrycmp, $dncmp) = cmpEntries($sourceentry, $targetentry);

		# Check if the current source entry has a higher sort position than
		# the current target. If so, we interpret this to mean that the
		# target entry no longer exists on the source. Issue a delete to LDAP.
		if ($entrycmp > 0) {
			$targetentry->delete;
			$ldifout->write_entry($targetentry);
            $incr_target = 1, next;
		}
		# Check if the current source entry has a lower sort position than
		# the current target entry. If so, we interpret this to mean that the
		# source entry doesn't exist on the target. Issue an add to LDAP.
		elsif ($entrycmp < 0) {
			$ldifout->write_entry($sourceentry);
            $incr_source = 1, next;
		}

		# When we get here, we're dealing with the same person in $sourceentry
		# and $targetentry. Compare the data and generate the update.

		# If a mod{R}DN is necessary, it needs to happen before other mods
		if ($dncmp) {
			my $rdnattr = rdnattr($sourceentry->dn);
			my $rdnval = rdnval($sourceentry->dn);
			my $newsuperior = dnsuperior($sourceentry->dn);
			my $oldsuperior = dnsuperior($targetentry->dn);
			my $changetype;

			if (cmpDNs($oldsuperior, $newsuperior)) {
				$changetype = 'moddn';
				$targetentry->add(newsuperior => $newsuperior);
			}
			else { $changetype = 'modrdn' }
			$targetentry->{changetype} = $changetype;
			$targetentry->add(newrdn => "$rdnattr=$rdnval",
							  deleteoldrdn => '1');
			$ldifout->write_entry($targetentry);
			$targetentry->delete('newrdn');
			$targetentry->delete('deleteoldrdn');
			$targetentry->delete('newsuperior') if $changetype eq 'moddn';
			delete($targetentry->{changetype});

			$targetentry->dn($sourceentry->dn);
			$targetentry->replace($rdnattr, $sourceentry->get_value($rdnattr))
				if $sourceentry->exists($rdnattr);
		}

		# Check for differences and generate LDIF as appropriate
		updateFromEntry($sourceentry, $targetentry, @sourceattrs);
		$ldifout->write_entry($targetentry) if @{$targetentry->{changes}};
		$incr_source = 1, $incr_target = 1, next;

    } continue {
		if ($incr_source) {
			$sourceentry = $source->read_entry(); $incr_source = 0;
		}
		if ($incr_target) {
			$targetentry = $target->read_entry(); $incr_target = 0;
		}
    }
}

# Generate LDIF to update $target with information in $source.
# Optionally restrict the set of attributes to consider.
sub updateFromEntry
{
	my ($source, $target, @attrs) = @_;
	my ($attr, $val, $ldifstr);

	unless (@attrs) {
		# add all source entry attributes
		@attrs = $source->attributes;
		# add any other attributes we haven't seen from the target entry
		foreach my $tattr ($target->attributes) {
			push(@attrs, $tattr) unless grep(/^$tattr$/i, @attrs)
		}
	}

	$target->{changetype} = 'modify';

	foreach $attr (@attrs) {
		my $lcattr = lc $attr;
		next if $lcattr eq 'dn'; # Can't handle modrdn here

		# Build lists of unique values in the source and target, to
		# speed up comparisons.
		my @sourcevals = $source->get_value($attr);
		my @targetvals = $target->get_value($attr);
		my (%sourceuniqvals, %targetuniqvals);
		foreach (@sourcevals) {
			my ($origval, $val) = ($_, $_);
			$val = lc $val if $ciscmp{$lcattr};
			# Get rid of spaces after non-escaped commas in DN attrs
			$val =~ s/(?<!\\),\s+/,/g if $dnattrs{$lcattr};
			$sourceuniqvals{$val} = $origval;
		}
		foreach (@targetvals) {
			my ($origval, $val) = ($_, $_);
			$val = lc $val if $ciscmp{$lcattr};
			# Get rid of spaces after non-escaped commas in DN attrs
			$val =~ s/(?<!\\),\s+/,/g if $dnattrs{$lcattr};
			$targetuniqvals{$val} = $origval;
		}
		foreach my $val (keys %sourceuniqvals) {
			if (exists $targetuniqvals{$val}) {
				delete $sourceuniqvals{$val};
				delete $targetuniqvals{$val};
			}
		}

		# Move on if there are no differences
		next unless keys(%sourceuniqvals) || keys(%targetuniqvals);

		# Make changes as appropriate
		if ($sharedattrs{$lcattr}) {
			# For 'shared' attributes (e.g. objectclass) where $source may not
			# be a sole authoritative source, we issue separate delete and
			# add modifications instead of a single replace.
			$target->delete($attr => [ values(%targetuniqvals) ])
				if keys(%targetuniqvals);
			$target->add($attr => [ values(%sourceuniqvals) ])
				if keys(%sourceuniqvals);
		}
		else {
			# Issue a replace or delete as needed
			if (@sourcevals) { $target->replace($attr => [ @sourcevals ]) }
			else { $target->delete($attr) }
		}
	}

	# Get rid of the "changetype: modify" if there were no changes
	delete($target->{changetype}) unless @{$target->{changes}};
}

=head1 AUTHOR

Kartik Subbarao E<lt>subbarao@computer.orgE<gt>

=cut