text:
package nom.bdezonia.zorbage.type.quaternion.float32;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;

import nom.bdezonia.zorbage.misc.BigList;
import nom.bdezonia.zorbage.misc.LongUtils;
import nom.bdezonia.zorbage.sampling.IntegerIndex;
import nom.bdezonia.zorbage.sampling.SamplingIterator;
import nom.bdezonia.zorbage.storage.Storage;
import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.algebra.GetAsFloatArray;
import nom.bdezonia.zorbage.algebra.Gettable;
import nom.bdezonia.zorbage.algebra.SetFromFloat;
import nom.bdezonia.zorbage.algebra.Settable;
import nom.bdezonia.zorbage.algebra.StorageConstruction;
import nom.bdezonia.zorbage.algebra.TensorMember;
import nom.bdezonia.zorbage.algebra.ThreadAccess;
import nom.bdezonia.zorbage.algorithm.GridIterator;
import nom.bdezonia.zorbage.data.IndexUtils;
import nom.bdezonia.zorbage.type.universal.OctonionRepresentation;
import nom.bdezonia.zorbage.type.universal.PrimitiveConversion;
import nom.bdezonia.zorbage.type.universal.PrimitiveRepresentation;
import nom.bdezonia.zorbage.type.universal.TensorOctonionRepresentation;
import nom.bdezonia.zorbage.type.universal.TensorStringRepresentation;
import nom.bdezonia.zorbage.type.universal.UniversalRepresentation;
import nom.bdezonia.zorbage.misc.Hasher;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;
import nom.bdezonia.zorbage.datasource.RawData;

// TODO:
//   rank 0 tensor getting and setting 1 value instead of 0
//   upper and lower indices: only if not CartesianTensors

/**
 *
 * @author Barry DeZonia
 *
 */
public final class QuaternionFloat32CartesianTensorProductMember
	implements
		TensorMember<QuaternionFloat32Member>,
		Gettable<QuaternionFloat32CartesianTensorProductMember>,
		Settable<QuaternionFloat32CartesianTensorProductMember>,
		PrimitiveConversion, UniversalRepresentation,
		RawData<QuaternionFloat32Member>,
		SetFromFloat, GetAsFloatArray,
		ThreadAccess
{
	private static final QuaternionFloat32Member ZERO = new QuaternionFloat32Member();

	private int rank;
	private long dimCount;
	private IndexedDataSource<QuaternionFloat32Member> storage;
	private long[] dims;
	private long[] multipliers;
	private StorageConstruction s;

	// rank() is also numDimensions(). Confusing. TODO - fix

	@Override
	public int rank() { return lowerRank() + upperRank(); }

	@Override
	public int lowerRank() {
		return rank;
	}

	@Override
	public int upperRank() {
		return 0;
	}

	@Override
	public boolean indexIsLower(int index) {
		if (index < 0 || index >= rank())
			throw new IllegalArgumentException("index of tensor component is outside bounds");
		return true;
	}

	@Override
	public boolean indexIsUpper(int index) {
		if (index < 0 || index >= rank())
			throw new IllegalArgumentException("index of tensor component is outside bounds");
		return false;
	}

	@Override
	public long dimension() { return dimCount; }

	public QuaternionFloat32CartesianTensorProductMember() {
		rank = 0;
		dimCount = 0;
		dims = new long[0];
		s = StorageConstruction.MEM_ARRAY;
		storage = Storage.allocate(s, new QuaternionFloat32Member(), 1);
		this.multipliers = IndexUtils.calcMultipliers(dims);
	}

	public QuaternionFloat32CartesianTensorProductMember(int rank, long dimCount) {
		if (rank < 0)
			throw new IllegalArgumentException("bad rank in tensor constructor");
		if (dimCount < 0)
			throw new IllegalArgumentException("bad dimensionality in tensor constructor");
		this.rank = rank;
		this.dimCount = dimCount;
		dims = new long[rank];
		for (int i = 0; i < rank; i++) {
			dims[i] = dimCount;
		}
		long numElems = LongUtils.numElements(this.dims);
		if (numElems == 0) numElems = 1;
		s = StorageConstruction.MEM_ARRAY;
		storage = Storage.allocate(s, new QuaternionFloat32Member(), numElems);
		this.multipliers = IndexUtils.calcMultipliers(dims);
	}

	public QuaternionFloat32CartesianTensorProductMember(int rank, long dimCount, float... vals) {
		this(rank, dimCount);
		setFromFloat(vals);
	}

	public QuaternionFloat32CartesianTensorProductMember(QuaternionFloat32CartesianTensorProductMember other) {
		set(other);
	}

	public QuaternionFloat32CartesianTensorProductMember(String s) {
		TensorStringRepresentation rep = new TensorStringRepresentation(s);
		BigList<OctonionRepresentation> data = rep.values();
		long[] tmpDims = rep.dimensions().clone();
		this.rank = tmpDims.length;
		if (tmpDims.length == 0) {
			this.dimCount = 1;
		}
		else {
			long d0 = tmpDims[0];
			for (int i = 1; i < tmpDims.length; i++) {
				if (tmpDims[i] != d0)
					throw new IllegalArgumentException("tensors must be the same in all dimensions");
			}
			this.dimCount = d0;
		}
		this.dims = new long[rank];
		for (int i = 0; i < rank; i++) {
			this.dims[i] = dimCount;
		}
		long numElems = LongUtils.numElements(this.dims);
		if (numElems == 0) numElems = 1;
		this.s = StorageConstruction.MEM_ARRAY;
		this.storage = Storage.allocate(this.s, new QuaternionFloat32Member(), numElems);
		this.multipliers = IndexUtils.calcMultipliers(dims);
		QuaternionFloat32Member value = new QuaternionFloat32Member();
		if (numElems == 1) {
			// TODO: does a rank 0 tensor have any values from a parsing?
			OctonionRepresentation val = data.get(0);
			value.setR(val.r().floatValue());
			value.setI(val.i().floatValue());
			value.setJ(val.j().floatValue());
			value.setK(val.k().floatValue());
			storage.set(0, value);
		}
		else {
			long i = 0;
			SamplingIterator<IntegerIndex> iter = GridIterator.compute(tmpDims);
			IntegerIndex index = new IntegerIndex(dims.length);
			while (iter.hasNext()) {
				iter.next(index);
				OctonionRepresentation val = data.get(i);
				value.setR(val.r().floatValue());
				value.setI(val.i().floatValue());
				value.setJ(val.j().floatValue());
				value.setK(val.k().floatValue());
				long idx = IndexUtils.indexToLong(dims, index);
				storage.set(idx, value);
				i++;
			}
		}
	}

	@Override
	public StorageConstruction storageType() {
		return s;
	}

	@Override
	public void set(QuaternionFloat32CartesianTensorProductMember other) {
		if (this == other) return;
		rank = other.rank;
		dimCount = other.dimCount;
		dims = other.dims.clone();
		multipliers = other.multipliers.clone();
		storage = other.storage.duplicate();
		s = other.s;
	}

	@Override
	public void get(QuaternionFloat32CartesianTensorProductMember other) {
		if (this == other) return;
		other.rank = rank;
		other.dimCount = dimCount;
		other.dims = dims.clone();
		other.multipliers = multipliers.clone();
		other.storage = storage.duplicate();
		other.s = s;
	}

	@Override
	public boolean alloc(long[] newDims) {
		boolean theSame = true;
		if (newDims.length != dims.length)
			theSame = false;
		else {
			for (int i = 0; i < newDims.length; i++) {
				if (newDims[i] != dims[i]) {
					theSame = false;
					break;
				}
			}
		}
		if (theSame)
			return false;
		this.rank = newDims.length;
		if (rank == 0) {
			this.dimCount = 1;
		}
		else {
			long d0 = newDims[0];
			for (int i = 1; i < newDims.length; i++) {
				if (newDims[i] != d0)
					throw new IllegalArgumentException("tensors must be the same in all dimensions");
			}
			this.dimCount = d0;
		}
		this.dims = new long[rank];
		for (int i = 0; i < rank; i++) {
			this.dims[i] = dimCount;
		}
		this.multipliers = IndexUtils.calcMultipliers(dims);
		long newCount = LongUtils.numElements(this.dims);
		if (newCount == 0) newCount = 1;
		if (storage == null || newCount != storage.size()) {
			storage = Storage.allocate(s, new QuaternionFloat32Member(), newCount);
			return true;
		}
		return false;
	}

	@Override
	public void init(long[] newDims) {
		if (!alloc(newDims)) {
			long storageSize = storage.size();
			for (long i = 0; i < storageSize; i++) {
				storage.set(i, ZERO);
			}
		}
	}

	public long numElems() {
		return storage.size();
	}

	void v(long index, QuaternionFloat32Member value) {
		storage.get(index, value);
	}

	@Override
	public void getV(IntegerIndex index, QuaternionFloat32Member value) {
		long idx = IndexUtils.safeIndexToLong(dims, index);
		storage.get(idx, value);
	}

	void setV(long index, QuaternionFloat32Member value) {
		storage.set(index, value);
	}

	@Override
	public void setV(IntegerIndex index, QuaternionFloat32Member value) {
		long idx = IndexUtils.safeIndexToLong(dims, index);
		storage.set(idx, value);
	}

	@Override
	public void toRep(TensorOctonionRepresentation rep) {
		long storageSize = storage.size();
		QuaternionFloat32Member value = new QuaternionFloat32Member();
		BigList<OctonionRepresentation> values = new BigList<OctonionRepresentation>(storageSize, new OctonionRepresentation());
		for (long i = 0; i < storageSize; i++) {
			storage.get(i, value);
			BigDecimal re = BigDecimal.valueOf(value.r());
			BigDecimal im = BigDecimal.valueOf(value.i());
			BigDecimal j = BigDecimal.valueOf(value.j());
			BigDecimal k = BigDecimal.valueOf(value.k());
			OctonionRepresentation o = values.get(i);
			o.setR(re);
			o.setI(im);
			o.setJ(j);
			o.setK(k);
			o.setL(BigDecimal.ZERO);
			o.setI0(BigDecimal.ZERO);
			o.setJ0(BigDecimal.ZERO);
			o.setK0(BigDecimal.ZERO);
		}
		rep.setTensor(dims, values);
	}

	@Override
	public void fromRep(TensorOctonionRepresentation rep) {
		QuaternionFloat32Member value = new QuaternionFloat32Member();
		BigList<OctonionRepresentation> tensor = rep.getTensor();
		init(rep.getTensorDims());
		long tensorSize = tensor.size();
		for (long i = 0; i < tensorSize; i++) {
			OctonionRepresentation o = tensor.get(i);
			value.setR(o.r().floatValue());
			value.setI(o.i().floatValue());
			value.setJ(o.j().floatValue());
			value.setK(o.k().floatValue());
			storage.set(i, value);
		}
	}

	// TODO: finish me
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		// iterate values/indices and write numbers, brackets, and commas in correct order
		// something recursive?
		QuaternionFloat32Member tmp = new QuaternionFloat32Member();
		IntegerIndex index = new IntegerIndex(this.dims.length);
		// [2,2,2] dims
		// [0,0,0]  [[[num
		// [1,0,0]  [[[num,num
		// [0,1,0]  [[[num,num][num
		// [1,1,0]  [[[num,num][num,num
		// [0,0,1]  [[[num,num][num,num]][[num
		// [1,0,1]  [[[num,num][num,num]][[num,num
		// [0,1,1]  [[[num,num][num,num]][[num,num][num
		// [1,1,1]  [[[num,num][num,num]][[num,num][num,num]]]
		long storageSize = storage.size();
		for (long i = 0; i < storageSize; i++) {
			storage.get(i, tmp);
			IndexUtils.longToIntegerIndex(multipliers, dims.length, storageSize, i, index);
			int j = 0;
			while (j < index.numDimensions() && index.get(j++) == 0)
				builder.append('[');
			if (index.get(0) != 0)
				builder.append(',');
			builder.append('{');
			builder.append(tmp.r());
			builder.append(',');
			builder.append(tmp.i());
			builder.append(',');
			builder.append(tmp.j());
			builder.append(',');
			builder.append(tmp.k());
			builder.append('}');
			j = 0;
			while (j < index.numDimensions() && index.get(j) == (dims[j++]-1))
				builder.append(']');
		}
		return builder.toString();
	}

	@Override
	public int numDimensions() {
		return dims.length;
	}

	@Override
	public void reshape(long[] dims) {
		// the idea here is to change dims and preserve values that
		// overlap old dims / new dims.
		if (Arrays.equals(this.dims, dims)) return;
		// the previous line makes sure that tensor add(a,a,a) will work
		// TODO
		throw new IllegalArgumentException("to implement");
	}

	@Override
	public long dimension(int d) {
		if (d < 0)
			throw new IllegalArgumentException("can't query negative dimension");
		if (d >= dims.length) return 1;
		return dims[d];
	}

	private static final ThreadLocal<QuaternionFloat32Member> tmpQuat =
			new ThreadLocal<QuaternionFloat32Member>()
	{
		protected QuaternionFloat32Member initialValue() {
			return new QuaternionFloat32Member();
		};

	};

	@Override
	public PrimitiveRepresentation preferredRepresentation() {
		return PrimitiveRepresentation.FLOAT;
	}

	@Override
	public int componentCount() {
		return 4;
	}

	@Override
	public void primComponentSetByte(IntegerIndex index, int component, byte v) {
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				tmp.setR(v);
			else
				tmp.setI(v);
		}
		else { // component >= 2
			if (component == 2)
				tmp.setJ(v);
			else
				tmp.setK(v);
		}
		setV(index, tmp);
	}

	@Override
	public void primComponentSetShort(IntegerIndex index, int component, short v) {
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				tmp.setR(v);
			else
				tmp.setI(v);
		}
		else { // component >= 2
			if (component == 2)
				tmp.setJ(v);
			else
				tmp.setK(v);
		}
		setV(index, tmp);
	}

	@Override
	public void primComponentSetInt(IntegerIndex index, int component, int v) {
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				tmp.setR(v);
			else
				tmp.setI(v);
		}
		else { // component >= 2
			if (component == 2)
				tmp.setJ(v);
			else
				tmp.setK(v);
		}
		setV(index, tmp);
	}

	@Override
	public void primComponentSetLong(IntegerIndex index, int component, long v) {
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				tmp.setR(v);
			else
				tmp.setI(v);
		}
		else { // component >= 2
			if (component == 2)
				tmp.setJ(v);
			else
				tmp.setK(v);
		}
		setV(index, tmp);
	}

	@Override
	public void primComponentSetFloat(IntegerIndex index, int component, float v) {
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				tmp.setR(v);
			else
				tmp.setI(v);
		}
		else { // component >= 2
			if (component == 2)
				tmp.setJ(v);
			else
				tmp.setK(v);
		}
		setV(index, tmp);
	}

	@Override
	public void primComponentSetDouble(IntegerIndex index, int component, double v) {
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				tmp.setR((float) v);
			else
				tmp.setI((float) v);
		}
		else { // component >= 2
			if (component == 2)
				tmp.setJ((float) v);
			else
				tmp.setK((float) v);
		}
		setV(index, tmp);
	}

	@Override
	public void primComponentSetBigInteger(IntegerIndex index, int component, BigInteger v) {
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				tmp.setR(v.floatValue());
			else
				tmp.setI(v.floatValue());
		}
		else { // component >= 2
			if (component == 2)
				tmp.setJ(v.floatValue());
			else
				tmp.setK(v.floatValue());
		}
		setV(index, tmp);
	}

	@Override
	public void primComponentSetBigDecimal(IntegerIndex index, int component, BigDecimal v) {
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				tmp.setR(v.floatValue());
			else
				tmp.setI(v.floatValue());
		}
		else { // component >= 2
			if (component == 2)
				tmp.setJ(v.floatValue());
			else
				tmp.setK(v.floatValue());
		}
		setV(index, tmp);
	}

	@Override
	public void primComponentSetByteSafe(IntegerIndex index, int component, byte v) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					tmp.setR(v);
				else
					tmp.setI(v);
			}
			else { // component >= 2
				if (component == 2)
					tmp.setJ(v);
				else
					tmp.setK(v);
			}
			setV(index, tmp);
		}
	}

	@Override
	public void primComponentSetShortSafe(IntegerIndex index, int component, short v) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					tmp.setR(v);
				else
					tmp.setI(v);
			}
			else { // component >= 2
				if (component == 2)
					tmp.setJ(v);
				else
					tmp.setK(v);
			}
			setV(index, tmp);
		}
	}

	@Override
	public void primComponentSetIntSafe(IntegerIndex index, int component, int v) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					tmp.setR(v);
				else
					tmp.setI(v);
			}
			else { // component >= 2
				if (component == 2)
					tmp.setJ(v);
				else
					tmp.setK(v);
			}
			setV(index, tmp);
		}
	}

	@Override
	public void primComponentSetLongSafe(IntegerIndex index, int component, long v) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					tmp.setR(v);
				else
					tmp.setI(v);
			}
			else { // component >= 2
				if (component == 2)
					tmp.setJ(v);
				else
					tmp.setK(v);
			}
			setV(index, tmp);
		}
	}

	@Override
	public void primComponentSetFloatSafe(IntegerIndex index, int component, float v) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					tmp.setR(v);
				else
					tmp.setI(v);
			}
			else { // component >= 2
				if (component == 2)
					tmp.setJ(v);
				else
					tmp.setK(v);
			}
			setV(index, tmp);
		}
	}

	@Override
	public void primComponentSetDoubleSafe(IntegerIndex index, int component, double v) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					tmp.setR((float) v);
				else
					tmp.setI((float) v);
			}
			else { // component >= 2
				if (component == 2)
					tmp.setJ((float) v);
				else
					tmp.setK((float) v);
			}
			setV(index, tmp);
		}
	}

	@Override
	public void primComponentSetBigIntegerSafe(IntegerIndex index, int component, BigInteger v) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			if (v.signum() != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					tmp.setR(v.floatValue());
				else
					tmp.setI(v.floatValue());
			}
			else { // component >= 2
				if (component == 2)
					tmp.setJ(v.floatValue());
				else
					tmp.setK(v.floatValue());
			}
		}
	}

	@Override
	public void primComponentSetBigDecimalSafe(IntegerIndex index, int component, BigDecimal v) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			if (v.signum() != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					tmp.setR(v.floatValue());
				else
					tmp.setI(v.floatValue());
			}
			else { // component >= 2
				if (component == 2)
					tmp.setJ(v.floatValue());
				else
					tmp.setK(v.floatValue());
			}
			setV(index, tmp);
		}
	}

	@Override
	public byte primComponentGetAsByte(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				return (byte) tmp.r();
			else
				return (byte) tmp.i();
		}
		else { // component >= 2
			if (component == 2)
				return (byte) tmp.j();
			else
				return (byte) tmp.k();
		}
	}

	@Override
	public short primComponentGetAsShort(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				return (short) tmp.r();
			else
				return (short) tmp.i();
		}
		else { // component >= 2
			if (component == 2)
				return (short) tmp.j();
			else
				return (short) tmp.k();
		}
	}

	@Override
	public int primComponentGetAsInt(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				return (int) tmp.r();
			else
				return (int) tmp.i();
		}
		else { // component >= 2
			if (component == 2)
				return (int) tmp.j();
			else
				return (int) tmp.k();
		}
	}

	@Override
	public long primComponentGetAsLong(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				return (long) tmp.r();
			else
				return (long) tmp.i();
		}
		else { // component >= 2
			if (component == 2)
				return (long) tmp.j();
			else
				return (long) tmp.k();
		}
	}

	@Override
	public float primComponentGetAsFloat(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				return tmp.r();
			else
				return tmp.i();
		}
		else { // component >= 2
			if (component == 2)
				return tmp.j();
			else
				return tmp.k();
		}
	}

	@Override
	public double primComponentGetAsDouble(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				return tmp.r();
			else
				return tmp.i();
		}
		else { // component >= 2
			if (component == 2)
				return tmp.j();
			else
				return tmp.k();
		}
	}

	@Override
	public BigInteger primComponentGetAsBigInteger(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				return BigDecimal.valueOf(tmp.r()).toBigInteger();
			else
				return BigDecimal.valueOf(tmp.i()).toBigInteger();
		}
		else { // component >= 2
			if (component == 2)
				return BigDecimal.valueOf(tmp.j()).toBigInteger();
			else
				return BigDecimal.valueOf(tmp.k()).toBigInteger();
		}
	}

	@Override
	public BigDecimal primComponentGetAsBigDecimal(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		QuaternionFloat32Member tmp = tmpQuat.get();
		getV(index, tmp);
		if (component < 2) {
			if (component == 0)
				return BigDecimal.valueOf(tmp.r());
			else
				return BigDecimal.valueOf(tmp.i());
		}
		else { // component >= 2
			if (component == 2)
				return BigDecimal.valueOf(tmp.j());
			else
				return BigDecimal.valueOf(tmp.k());
		}
	}

	@Override
	public byte primComponentGetAsByteSafe(IntegerIndex index, int component) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			return 0;
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					return (byte) tmp.r();
				else
					return (byte) tmp.i();
			}
			else { // component >= 2
				if (component == 2)
					return (byte) tmp.j();
				else
					return (byte) tmp.k();
			}
		}
	}

	@Override
	public short primComponentGetAsShortSafe(IntegerIndex index, int component) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			return 0;
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					return (short) tmp.r();
				else
					return (short) tmp.i();
			}
			else { // component >= 2
				if (component == 2)
					return (short) tmp.j();
				else
					return (short) tmp.k();
			}
		}
	}

	@Override
	public int primComponentGetAsIntSafe(IntegerIndex index, int component) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			return 0;
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					return (int) tmp.r();
				else
					return (int) tmp.i();
			}
			else { // component >= 2
				if (component == 2)
					return (int) tmp.j();
				else
					return (int) tmp.k();
			}
		}
	}

	@Override
	public long primComponentGetAsLongSafe(IntegerIndex index, int component) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			return 0;
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					return (long) tmp.r();
				else
					return (long) tmp.i();
			}
			else { // component >= 2
				if (component == 2)
					return (long) tmp.j();
				else
					return (long) tmp.k();
			}
		}
	}

	@Override
	public float primComponentGetAsFloatSafe(IntegerIndex index, int component) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			return 0;
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					return tmp.r();
				else
					return tmp.i();
			}
			else { // component >= 2
				if (component == 2)
					return tmp.j();
				else
					return tmp.k();
			}
		}
	}

	@Override
	public double primComponentGetAsDoubleSafe(IntegerIndex index, int component) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			return 0;
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					return tmp.r();
				else
					return tmp.i();
			}
			else { // component >= 2
				if (component == 2)
					return tmp.j();
				else
					return tmp.k();
			}
		}
	}

	@Override
	public BigInteger primComponentGetAsBigIntegerSafe(IntegerIndex index, int component) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			return BigInteger.ZERO;
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					return BigDecimal.valueOf(tmp.r()).toBigInteger();
				else
					return BigDecimal.valueOf(tmp.i()).toBigInteger();
			}
			else { // component >= 2
				if (component == 2)
					return BigDecimal.valueOf(tmp.j()).toBigInteger();
				else
					return BigDecimal.valueOf(tmp.k()).toBigInteger();
			}
		}
	}

	@Override
	public BigDecimal primComponentGetAsBigDecimalSafe(IntegerIndex index, int component) {
		if (IndexUtils.componentOob(dims, index, component, 4)) {
			return BigDecimal.ZERO;
		}
		else {
			QuaternionFloat32Member tmp = tmpQuat.get();
			getV(index, tmp);
			if (component < 2) {
				if (component == 0)
					return BigDecimal.valueOf(tmp.r());
				else
					return BigDecimal.valueOf(tmp.i());
			}
			else { // component >= 2
				if (component == 2)
					return BigDecimal.valueOf(tmp.j());
				else
					return BigDecimal.valueOf(tmp.k());
			}
		}
	}

	@Override
	public void primitiveInit() {
		long storageSize = storage.size();
		for (long i = 0; i < storageSize; i++)
			storage.set(i, ZERO);
	}

	@Override
	public IndexedDataSource<QuaternionFloat32Member> rawData() {
		return storage;
	}

	@Override
	public int hashCode() {
		QuaternionFloat32Member tmp = G.QFLT.construct();
		long len = dimension(0);
		int v = 1;
		v = Hasher.PRIME * v + Hasher.hashCode(len);
		if (len > 0) {
			storage.get(0, tmp);
			v = Hasher.PRIME * v + tmp.hashCode();
		}
		return v;
	}

	@Override
	public boolean equals(Object o) {
		if (o instanceof QuaternionFloat32CartesianTensorProductMember) {
			return G.QFLT_TEN.isEqual().call(this, (QuaternionFloat32CartesianTensorProductMember) o);
		}
		return false;
	}

	@Override
	public void setFromFloat(float... vals) {
		int componentCount = 4;
		if (vals.length/componentCount != storage.size()) {
			throw new IllegalArgumentException(
					"number of elements passed in do not fit allocated storage");
		}
		QuaternionFloat32Member value = G.QFLT.construct();
		for (int i = 0; i < vals.length; i += componentCount) {
			value.setR(  vals[i + 0] );
			value.setI(  vals[i + 1] );
			value.setJ(  vals[i + 2] );
			value.setK(  vals[i + 3] );
			storage.set(i/componentCount, value);
		}
	}

	@Override
	public float[] getAsFloatArray() {
		if (storage.size() > (Integer.MAX_VALUE / 4))
			throw new IllegalArgumentException(
					"internal data too large to be encoded in an array");
		QuaternionFloat32Member value = G.QFLT.construct();
		float[] values = new float[4 * (int) storage.size()];
		for (int i = 0, k = 0; i < storage.size(); i++) {
			storage.get(i, value);
			values[k++] = value.r();
			values[k++] = value.i();
			values[k++] = value.j();
			values[k++] = value.k();
		}
		return values;
	}

	@Override
	public boolean accessWithOneThread() {

		return storage.accessWithOneThread();
	}
}


text:
package uk.theretiredprogrammer.accesscontrolmanager.nodes;

import java.util.List;
import java.util.function.Supplier;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Node;
import uk.theretiredprogrammer.accesscontrolmanager.dataobjects.User;

/**
 * UserRootNodeChildFactory.
 *
 * (Class generated by NetBeans Platform Code Generator tools using script.xml.
 * Do not edit this file. Apply any changes to the definition file and
 * regenerate all files.)
 *
 * @author Richard Linsdale (richard at theretiredprogrammer.uk)
 */
public class UserRootNodeChildFactory extends ChildFactory<User> {

    private final Supplier<Users> creator;
    private Users model;

    /**
     * Constructor
     *
     * @param creator the child model creator function
     */
    public UserRootNodeChildFactory(Supplier<Users> creator) {
        this.creator = creator;
    }

    public void clearChildren() {
        model = null;
        refresh(true);
    }

    /**
     * Add a new User, link to parent if required and refresh the child nodes
     */
    public void add(User e) {
        if (model == null) {
            model = creator.get();
        }
        model.add(e);
        refresh(true);
    }

    /**
     * Remove a User from the child list and refresh the child nodes
     */
    public void remove(User e) {
        if (model == null) {
            return;
        }
        model.remove(e);
        refresh(true);
    }

    /**
     * Create the list of Child Nodes
     *
     * @param list the list into which child nodes are to be added
     * @return true
     */
    @Override
    protected boolean createKeys(List<User> list) {
        if (model == null) {
            model = creator.get();
        }
        list.addAll(model);
        return true;
    }

    /**
     * Create a Child Node from a given Child Entity
     *
     * @param e the Child Entity
     * @return the Child Node
     */
    @Override
    protected Node createNodeForKey(User e) {
        return new UserNode(e);
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. Bot. , Lond. , n. s. 14: 280 (1950)

#### Original name
Rhizophydium sphaerocystidis Canter

### Remarks
null


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Uragoga grosourdieana Baill.

### Remarks
null


text:
layout: public.njk
---

Login

Silahkan pilih kategori akun anda

          Mahasiswa
          Penyedia Beasiswa


text:
// Copy from spark

package com.github.cloudml.zen.ml.util

import java.nio.ByteBuffer
import java.util.{Random => JavaRandom}

import scala.util.hashing.MurmurHash3

/**
 * This class implements a XORShift random number generator algorithm
 * Source:
 * Marsaglia, G. (2003). Xorshift RNGs. Journal of Statistical Software, Vol. 8, Issue 14.
 * @see Paper
 *      This implementation is approximately 3.5 times faster than
 *      { @link java.util.Random java.util.Random}, partly because of the algorithm, but also due
 *              to renouncing thread safety. JDK's implementation uses an AtomicLong seed, this class
 *              uses a regular Long. We can forgo thread safety since we use a new instance of the RNG
 *              for each thread.
 */
private[zen] class XORShiftRandom(init: Long) extends JavaRandom(init) {

  def this() = this(System.nanoTime)

  private var seed = XORShiftRandom.hashSeed(init)

  // we need to just override next - this will be called by nextInt, nextDouble,
  // nextGaussian, nextLong, etc.
  override protected def next(bits: Int): Int = {
    var nextSeed = seed ^ (seed << 21)
    nextSeed ^= (nextSeed >>> 35)
    nextSeed ^= (nextSeed << 4)
    seed = nextSeed
    (nextSeed & ((1L << bits) - 1)).asInstanceOf[Int]
  }

  override def setSeed(s: Long) {
    seed = XORShiftRandom.hashSeed(s)
  }
}

/** Contains benchmark method and main method to run benchmark of the RNG */
private[zen] object XORShiftRandom {

  /** Hash seeds to have 0/1 bits throughout. */
  private def hashSeed(seed: Long): Long = {
    val bytes = ByteBuffer.allocate(java.lang.Long.SIZE).putLong(seed).array()
    MurmurHash3.bytesHash(bytes)
  }

}


text:
from __future__ import unicode_literals

import logging
import os

from django.conf import settings
from django.core.management import execute_from_command_line
from django.core.management.base import BaseCommand

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    """Command that loads all of the fixtures into the database
    """

    help = 'Loads all of the fixtures into the database'

    def handle(self, *args, **options):
        """See :meth:`django.core.management.base.BaseCommand.handle`.

        This method loads all of the fixtures into the database.
        """
        logger.info('Command starting: load_all_data')
        fixture_names = []
        manage_path = os.path.join(settings.BASE_DIR, 'manage.py')

        for app_dir in os.listdir(settings.BASE_DIR):
            app_dir_path = os.path.join(settings.BASE_DIR, app_dir)
            if not os.path.isdir(app_dir_path):
                continue
            sub_dirs = os.listdir(app_dir_path)
            if 'fixtures' in sub_dirs:
                fixture_dir_path = os.path.join(app_dir_path, 'fixtures')
                for entry in os.listdir(fixture_dir_path):
                    if os.path.isfile(os.path.join(fixture_dir_path, entry)):
                        if entry.endswith('.json'):
                            logger.info('Discovered: %s -> %s', app_dir, entry)
                            fixture_names.append(entry)

        for name in fixture_names:
            cmd_list = [manage_path, 'loaddata', name]
            logger.info('Executing: %s', ' '.join(cmd_list))
            execute_from_command_line(cmd_list)
        logger.info('Command completed: load_all_data')


text: package pinpointemail


text:
HRESULT HostEnvironment::TryLoadCoreCLR() {

    m_coreCLRModule = ::LoadLibraryEx(coreCLRDll, NULL, 0);
    if (!m_coreCLRModule) {
        return HRESULT_FROM_WIN32(GetLastError());
    }

    // Pin the module - CoreCLR.dll does not support being unloaded.
    // N.B.: HostEnvironment is not calling ::FreeLibrary on this loaded module since we're pinning it anyway.
    // If unloading CoreCLR is ever supported and the pinning below is to be removed please make sure that
    // the ::FreeLibrary is called appropriately.
    HMODULE dummy_coreCLRModule;
    if (!::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, coreCLRDll, &dummy_coreCLRModule))
    {
        return HRESULT_FROM_WIN32(GetLastError());
    }

    if (!GetModuleFileNameW(m_coreCLRModule, m_coreCLRInstallDirectory, MAX_PATH))
    {
        return HRESULT_FROM_WIN32(GetLastError());
    }
    // Find out where the last backslash is, and trim the path to get the directory containing coreclr.dll
    wchar_t *lastBackSlash = wcsrchr(m_coreCLRInstallDirectory, L'\\');
    if (lastBackSlash != nullptr)
    {
        *(lastBackSlash+1) = L'\0';
    }
    else
    {
        memset(m_coreCLRInstallDirectory, 0, MAX_PATH * sizeof(wchar_t));
        return E_FAIL;
    }

    return S_OK;
}

HRESULT HostEnvironment::Initialize()
{
    HRESULT hr = S_OK;
    //
    // Get the package root.
    // This is also our check for the App to be an AppX app.
    // TODO: Not all AppX apps are UWP apps. Add validation for UWP apps.
    //
    UINT32 length = 0;
    LONG rc = GetCurrentPackagePath(&length, NULL);
    if (rc != ERROR_INSUFFICIENT_BUFFER)
    {
        return HRESULT_FROM_WIN32(rc);
    }

    m_packageRoot = (PWSTR) malloc(length * sizeof(*m_packageRoot));
    if (m_packageRoot == NULL)
    {
        return E_FAIL;
    }

    // Get the actual path to the package root from the path to the current module.
    rc = GetCurrentPackagePath(&length, m_packageRoot);
    IfFailWin32Ret(rc);

    m_fIsAppXPackage = true;

    //
    // Query the package full name
    //
    length = 0;
    rc = GetCurrentPackageFullName(&length, NULL);
    if (rc != ERROR_INSUFFICIENT_BUFFER)
    {
        return HRESULT_FROM_WIN32(rc);
    }

    m_currentPackageFullName = (PWSTR) malloc(length * sizeof(*m_currentPackageFullName));
    if (m_currentPackageFullName == NULL)
    {
        return HRESULT_FROM_WIN32(rc);
    }

    rc = GetCurrentPackageFullName(&length, m_currentPackageFullName);
    IfFailWin32Ret(rc);

    // Try to load CoreCLR
    IfFailRet(TryLoadCoreCLR());

    PACKAGE_INFO_REFERENCE packageInfoReference = {0};
    rc = OpenPackageInfoByFullName(m_currentPackageFullName, 0 , &packageInfoReference);
    IfFailWin32Ret(rc);

    length = 0;
    rc = GetPackageInfo(packageInfoReference, PACKAGE_FILTER_DIRECT|PACKAGE_FILTER_IS_IN_RELATED_SET, &length, NULL, &m_dependentPackagesCount);
    IfFalseWin32Goto(rc == ERROR_INSUFFICIENT_BUFFER, rc, ErrExit2);

    BYTE* buffer = (BYTE *) malloc(length);
    IfFalseGoto(buffer != NULL, E_FAIL, ErrExit2);

    m_dependentPackagesRootPaths = (wchar_t**) malloc(m_dependentPackagesCount * sizeof(wchar_t*));
    IfFalseGo(m_dependentPackagesRootPaths != NULL, E_FAIL);
    memset(m_dependentPackagesRootPaths, 0, m_dependentPackagesCount * sizeof(wchar_t*));

    rc = GetPackageInfo(packageInfoReference, PACKAGE_FILTER_DIRECT|PACKAGE_FILTER_IS_IN_RELATED_SET, &length, buffer, &m_dependentPackagesCount);
    IfFailWin32Go(rc);

    const PACKAGE_INFO *packageInfo = (PACKAGE_INFO *) buffer;
    for (UINT32 i=0; i<m_dependentPackagesCount; i++, ++packageInfo)
    {
        length = 0;
        rc = GetPackagePathByFullName(packageInfo->packageFullName, &length, NULL);
        IfFalseWin32Go(rc == ERROR_INSUFFICIENT_BUFFER, rc);

        // +1 below is to append a '\' at the end of the string if it's not already ending with one.
        m_dependentPackagesRootPaths[i] = (wchar_t*) malloc((length+1) * sizeof(wchar_t));
        IfFalseGo(m_dependentPackagesRootPaths[i] != NULL, E_FAIL);

        rc = GetPackagePathByFullName(packageInfo->packageFullName, &length, m_dependentPackagesRootPaths[i]);
        IfFailWin32Go(rc);

        // Note: length includes the null-terminator. So the last char is at index (length-2)
        wchar_t* lastBackslash = wcsrchr(m_dependentPackagesRootPaths[i], L'\\');
        if ((lastBackslash != nullptr) && ((UINT32)(lastBackslash - m_dependentPackagesRootPaths[i] + 1) != length - 2))
        {
            wcsncat_s(m_dependentPackagesRootPaths[i], length+1, L"\\", 1);
        }
    }

    return S_OK;

ErrExit:
    free(buffer);
ErrExit2:
    ClosePackageInfo(packageInfoReference);
    return hr;
}

HostEnvironment::HostEnvironment()
    : m_CLRRuntimeHost(nullptr), m_coreCLRModule(NULL), m_fIsAppXPackage(false),
      m_dependentPackagesRootPaths(NULL), m_dependentPackagesCount(0)
{
}

HostEnvironment::~HostEnvironment()
{
    if (m_packageRoot)
    {
        free(m_packageRoot);
        m_packageRoot = NULL;
    }
    if (m_dependentPackagesCount > 0 && m_dependentPackagesRootPaths != NULL)
    {
        for (UINT32 i=0;i<m_dependentPackagesCount;i++)
        {
            if (m_dependentPackagesRootPaths[i] != NULL)
                free(m_dependentPackagesRootPaths[i]);
        }
        free(m_dependentPackagesRootPaths);
    }

    if (m_currentPackageFullName)
    {
        free(m_currentPackageFullName);
        m_currentPackageFullName = NULL;
    }
}

void HostEnvironment::InitializeTPAList(_In_reads_(tpaEntriesCount) wchar_t** tpaEntries, int tpaEntriesCount)
{
    wchar_t assemblyPath[MAX_PATH];
    wchar_t *targetPath = GetCoreCLRInstallPath();
    const size_t dirLength = wcslen(targetPath);

    for (int i= 0; i < tpaEntriesCount; i++)
    {
        wcscpy_s(assemblyPath, MAX_PATH, targetPath);

        wchar_t* const fileNameBuffer = assemblyPath + dirLength;
        const size_t fileNameBufferSize = MAX_PATH - dirLength;

        wcscat_s(assemblyPath, tpaEntries[i]);

        WIN32_FIND_DATA data;
        HANDLE findHandle = FindFirstFile(assemblyPath, &data);
        if (findHandle != INVALID_HANDLE_VALUE) {
            do {
                if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
                    wchar_t* fileName = data.cFileName;
                    const size_t fileLength = wcslen(data.cFileName);

                    m_tpaList.Append(targetPath, dirLength);
                    m_tpaList.Append(fileName, fileLength);
                    m_tpaList.Append(L";", 1);
                }
            } while (0 != FindNextFile(findHandle, &data));

            FindClose(findHandle);
        }
    }
}

// Returns the ICLRRuntimeHost2 instance, loading it from CoreCLR.dll if necessary, or nullptr on failure.
ICLRRuntimeHost2* HostEnvironment::GetCLRRuntimeHost(HRESULT &hResult) {
    if (!m_CLRRuntimeHost) {

        if (!m_coreCLRModule) {
            hResult = E_FAIL;
            return nullptr;
        }

        FnGetCLRRuntimeHost pfnGetCLRRuntimeHost =
            (FnGetCLRRuntimeHost)::GetProcAddress(m_coreCLRModule, "GetCLRRuntimeHost");
        if (!pfnGetCLRRuntimeHost) {
            hResult = E_INVALIDARG;
            return nullptr;
        }

        HRESULT hr = pfnGetCLRRuntimeHost(IID_ICLRRuntimeHost2, (IUnknown**)&m_CLRRuntimeHost);
        if (FAILED(hr)) {
            hResult = hr;
            return nullptr;
        }
    }

    hResult = S_OK;
    return m_CLRRuntimeHost;
}


text:
package proxy

import (
	"github.com/coredns/coredns/core/dnsserver"
	"github.com/coredns/coredns/plugin"
	"github.com/coredns/coredns/plugin/metrics"
	clog "github.com/coredns/coredns/plugin/pkg/log"

	"github.com/mholt/caddy"
)

var log = clog.NewWithPlugin("proxy")

func init() {
	caddy.RegisterPlugin("proxy", caddy.Plugin{
		ServerType: "dns",
		Action:     setup,
	})
}

func setup(c *caddy.Controller) error {
	upstreams, err := NewStaticUpstreams(&c.Dispenser)
	if err != nil {
		return plugin.Error("proxy", err)
	}

	t := dnsserver.GetConfig(c).Handler("trace")
	P := &Proxy{Trace: t}
	dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
		P.Next = next
		P.Upstreams = &upstreams
		return P
	})

	c.OnStartup(func() error {
		metrics.MustRegister(c, RequestCount, RequestDuration)
		return nil
	})

	for i := range upstreams {
		u := upstreams[i]
		c.OnStartup(func() error {
			return u.Exchanger().OnStartup(P)
		})
		c.OnShutdown(func() error {
			return u.Exchanger().OnShutdown(P)
		})
		// Register shutdown handlers.
		c.OnShutdown(u.Stop)
	}

	return nil
}


text:
package com.github.paolodenti.jsapp.core.command;

import com.github.paolodenti.jsapp.core.command.base.ISappCommandNoResult;
import com.github.paolodenti.jsapp.core.command.base.SappCommand;
import com.github.paolodenti.jsapp.core.util.SappByteBuffer;
import com.github.paolodenti.jsapp.core.util.SappUtils;

/**
 *
Sapp Command 0x7A - Set Input Status 32 WORD

 *
 * @author Paolo Denti
 */
public class Sapp7ACommand extends SappCommand implements ISappCommandNoResult {

	/**
	 *
0x7A command constructor.

	 *
	 * @param nmod  first module number
	 * @param len  number of virtual variables to write (max 32)
	 * @param values  values to save
	 */
	public Sapp7ACommand(byte nmod, byte len, int[] values) {

		super();

		SappByteBuffer buffer = new SappByteBuffer();
		buffer.addByte((byte) 0x7A);
		buffer.addBytes(SappUtils.getHexAsciiByte(nmod));
		buffer.addBytes(SappUtils.getHexAsciiByte(len));
		for (int i : values) {
			buffer.addBytes(SappUtils.getHexAsciiWord(i));
		}

		this.command = buffer.getArray();
	}
}


text:
layout:     post
title:      "WildArt talk with Prasad Natarajan-Wildlife Artist"
subtitle:   "Birds of Bangalore - Week 20"
author:     "Prasad Natarajan"
header-thumb-img: "img/2015-12-21/SpotbilledPelican_Prasad-Natarajan-thumb.jpg"
tags:       ["Bangalore Wildlife", "Birding Destinations"]
seo: 		["Birding Destinations", "Bangalore", "wildart"]
comments:   true
sharing-img: "img/2015-12-21/SpotbilledPelican_Prasad-Natarajan.jpg"
---

Title: Lake Punk!

Medium: Ink and water color on paper

Duration: 20 hours

December 18th, 2015

Welcome back to everyone, we know when winter is arriving, days get shorter and nights are longer. It is also great time to watch birds basking, I have been watching Green Bee-eaters and Black Drongo's sun basking and waiting for that dragonfly that strays in their path. Also, Sunbirds calls on my neem tree is a pleasant way to wake up in the morning, Palm squirrel is rebuilding his home in the earthen pots we put up for the birds, my morning fly's by with such daily visitors.

Last week when I visited Hoskote lake, was able to spot all our common friends there and was able to make few reference images as well. Tripod really helps to click at the right moment and of course added benefit is the sharpness as well. While I sat patiently on the last stone waiting for all the wading birds to wake up and start their routine. Since sun had not yet come out, I reflected back on how my mother used to wake me up before and prepare bread toast. I really miss her and more so when I head out solo. Mothers are truly nature's best gift in majority of the species. Lucky are those who enjoy the pampering and caring of mother.

The sun slowly made it out and the herons, coots, egrets made their way out. Hesitantly, our bird of this week finally made their way out as well.  Large bird with long bill, majority of its body is white, edge of their upper mandible is colored yellow one can see the spots on the upper mandible, which gives them their name. Their bill is mostly colored light pink. Eye is brownish with black iris. On top of the crown there is stokes of brown, breast and most of their neck are colored grey. Edge of the wings is with brown markings and so does the tail tips. They have webbed feet and tail is round. Young ones lack the grayish coloring and majority of their body is colored white and brown.

We are talking about none other than the Spot billed Pelican (Pelecanus philippensis) also know as grey pelican since the majority of their body is white and grey. They mainly feed on fishes. It is always a pleasure to watch them gulp water in their throat and you will be able to watch the struggling fish in their big pouch. It is also interesting to watch how they line up and dive one after the other. They prefer shallow wetlands; this colony of pelicans was about fifteen in number and had young ones as well.

The spot-billed pelican doesn't migrate but move locally and are more widely distributed in the non-breeding season. The nests are on low trees near wetlands and sometimes near human habitations. They build their nest in colonies and the nest is a thick platform of twigs placed on a low tree. The breeding season varies from October to May. The courtship display of the males involves a distention of the pouch with swinging motions of the head up and down followed by sideways swings followed by the head being held back over the back. Bill claps may also be produced during the head swaying movements. The nests are usually built alongside other colonial water birds like greater cormorants and painted storks.

Last year someone shot five pelicans at Hoskote Lake, which was reported to the forest department. He was arrested and heavily fined. Also there's been heavy fishing going on this Lake, which reduces their only food source. Sometimes these big birds get tangled in the fishing lines and loose their wings, which means slow painful death. I can't stress enough on the worst hit wetlands of Bangalore, we always wake up, try to take actions only when a disaster strikes, until then we prefer to keep blind eyed to all the assault. Lake fishing should also be regulated if not most of the water birds will go elsewhere and we are the one to lose!

With this I take leave. Until next week, keep watching!


text:
from django.utils import unittest
from fts_test.models import *
from pprint import pprint

class FTSTestCase(unittest.TestCase):
    def test_fts(self):
        b1 = Blog.objects.create(title='Berlusconi government abducted by aliens', body='In an unusual turn of events, the 34th government headed by now bicentenial italian playboy Silvio Berlusconi was abducted during an orgy at the royal palace')
        b2 = Blog.objects.create(title='bunga-bunga-bunga', body='A new game has been developed in the highest circles of the italian ruling class. It\'s an applied version of the famous "aristocrats" line of jokes. The use of alien costumes is optional.')
        b3 = Blog.objects.create(title='underage alien scandal', body='shocking developments in the so called "abduction". It seems it was all organized by Lele Mora. Dozens of underage girls dressed in "Shreck" costumes where simply participating to an erotic sharade. The so called "aliens" took Silvio Berlusconi in a hot-air baloon and started to undress while the national anthem was blasting from a perfectly configured hi-fi setup.')

        q1 = Blog.search_objects.search('abduction')
        self.assertIn(b1, q1)
        self.assertIn(b3, q1)
        self.assertEqual(len(q1), 2)

        q2 = Blog.search_objects.search('aliens')
        self.assertIn(b1, q2)
        self.assertIn(b2, q2)
        self.assertIn(b3, q2)
        self.assertEqual(len(q2), 3)

        # different order, word distance, and ranking
        q3 = Blog.search_objects.search('berlusconi alien', rank_field='rank')
        self.assertEqual(q3[0], b3)
        self.assertEqual(q3[1], b1)
        self.assertEqual(len(q3), 2)

        q4 = Blog.search_objects.search('italian', rank_field='rank')
        self.assertEqual(q4[0], b1)
        self.assertEqual(q4[1], b2)
        self.assertEqual(len(q4), 2)

        q5 = Blog.search_objects.search('alien', rank_field='rank', highlight_field='body')
        self.assertIn('aliens', q5[0].body_highlight)
        #for b in q5:
            #pprint(b.__dict__)


text:
package org.apache.eagle.log.entity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.eagle.log.entity.meta.EntityConstants;
import org.apache.eagle.log.entity.meta.EntityDefinition;
import org.apache.eagle.common.ByteUtil;

public class RowkeyBuilder {

    public static final int EMPTY_PARTITION_DEFAULT_HASH_CODE = 0;

    /**
     * Generate the internal sorted hashmap for tags. Please note the partition tags should not be included in
     * the result map.
     *
     * @param partitions array of partition tags in order
     * @param tags tags of the entity
     * @return the sorted hash map of the tags
     */
    public static SortedMap<Integer, Integer> generateSortedTagMap(String[] partitions,
                                                                   Map<String, String> tags) {
        final SortedMap<Integer, Integer> tagHashMap = new TreeMap<Integer, Integer>();
        for (Map.Entry<String, String> entry : tags.entrySet()) {
            final String tagName = entry.getKey();
            final String tagValue = entry.getValue();
            // If it's a partition tag, we need to remove it from tag hash list. It need to
            // put to the fix partition hash slot in rowkey.
            if (tagValue == null || isPartitionTag(partitions, tagName)) {
                continue;
            }
            tagHashMap.put(tagName.hashCode(), tagValue.hashCode());
        }
        return tagHashMap;
    }

    /**
     * build rowkey from InternalLog object
     *
     * @param log internal log entity to write
     * @return the rowkey of the entity
     */
    public static byte[] buildRowkey(InternalLog log) {
        final String[] partitions = log.getPartitions();
        final Map<String, String> tags = log.getTags();
        final SortedMap<Integer, Integer> tagHashMap = generateSortedTagMap(partitions, tags);

        // reverse timestamp
        long ts = Long.MAX_VALUE - log.getTimestamp();

        List<Integer> partitionHashValues = new ArrayList<Integer>();
        if (partitions != null) {
            for (String partition : partitions) {
                final String tagValue = tags.get(partition);
                if (tagValue != null) {
                    partitionHashValues.add(tagValue.hashCode());
                } else {
                    partitionHashValues.add(EMPTY_PARTITION_DEFAULT_HASH_CODE);
                }
            }
        }
        return buildRowkey(log.getPrefix().hashCode(), partitionHashValues, ts, tagHashMap);
    }

    /**
     * rowkey is: prefixHash:4 + (partitionValueHash:4)* + timestamp:8 + (tagnameHash:4 + tagvalueHash:4)*
     * partition fields are sorted by partition definition order, while tag fields are sorted by tag name's
     * hash code values.
     */
    private static byte[] buildRowkey(int prefixHash, List<Integer> partitionHashValues, long timestamp,
                                      SortedMap<Integer, Integer> tags) {
        // allocate byte array for rowkey
        final int len = 4 + 8 + tags.size() * (4 + 4) + (partitionHashValues.size() * 4);
        final byte[] rowkey = new byte[len];
        int offset = 0;

        // 1. set prefix
        ByteUtil.intToBytes(prefixHash, rowkey, offset);
        offset += 4;

        // 2. set partition
        for (Integer partHash : partitionHashValues) {
            ByteUtil.intToBytes(partHash, rowkey, offset);
            offset += 4;
        }

        // 3. set timestamp
        ByteUtil.longToBytes(timestamp, rowkey, offset);
        offset += 8;

        // 4. set tag key/value hashes
        for (Map.Entry<Integer, Integer> entry : tags.entrySet()) {
            ByteUtil.intToBytes(entry.getKey(), rowkey, offset);
            offset += 4;
            ByteUtil.intToBytes(entry.getValue(), rowkey, offset);
            offset += 4;
        }

        return rowkey;
    }

    public static long getTimestamp(byte[] rowkey, EntityDefinition ed) {
        if (!ed.isTimeSeries()) {
            return EntityConstants.FIXED_WRITE_TIMESTAMP;
        }
        final int offset = (ed.getPartitions() == null) ? 4 : (4 + ed.getPartitions().length * 4);
        return Long.MAX_VALUE - ByteUtil.bytesToLong(rowkey, offset);
    }

    /**
     * Check if the tagName is one of the partition tags
     *
     * @param partitions paritition tags of the entity
     * @param tagName the tag name that needs to check
     * @return
     */
    private static boolean isPartitionTag(String[] partitions, String tagName) {
        if (partitions != null) {
            for (String partition : partitions) {
                if (partition.equals(tagName)) {
                    return true;
                }
            }
        }
        return false;
    }

}


text:
package org.assertj.core.internal.bigintegers;

import static java.math.BigInteger.ONE;
import static java.math.BigInteger.TEN;
import static java.math.BigInteger.ZERO;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static org.assertj.core.api.Assertions.byLessThan;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assertions.within;
import static org.assertj.core.data.Offset.offset;
import static org.assertj.core.error.ShouldBeEqualWithinOffset.shouldBeEqual;
import static org.assertj.core.internal.ErrorMessages.offsetIsNull;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.mockito.Mockito.verify;

import java.math.BigInteger;

import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.BigIntegersBaseTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

/**
 * Tests for <code>{@link org.assertj.core.internal.BigIntegers#assertIsCloseTo(AssertionInfo, BigInteger, BigInteger, org.assertj.core.data.Offset)}</code>.
 */
class BigIntegers_assertIsCloseTo_Test extends BigIntegersBaseTest {

  private static final BigInteger TWO = new BigInteger("2");
  private static final BigInteger FIVE = new BigInteger("5");
  private static final BigInteger SIX = new BigInteger("6");
  private static final BigInteger NINE = new BigInteger("9");

  @Test
  void should_pass_if_difference_is_less_than_given_offset() {
    numbers.assertIsCloseTo(someInfo(), FIVE, SIX, offset(TWO));
    numbers.assertIsCloseTo(someInfo(), FIVE, SIX, byLessThan(TWO));
    numbers.assertIsCloseTo(someInfo(), ONE, ONE, within(ONE));
    numbers.assertIsCloseTo(someInfo(), ONE, ONE, byLessThan(ONE));
    numbers.assertIsCloseTo(someInfo(), ONE, TWO, within(TEN));
    numbers.assertIsCloseTo(someInfo(), ONE, TWO, byLessThan(TEN));
  }

  @ParameterizedTest
  @CsvSource({
      "1, 1, 0",
      "1, 0, 1",
      "-1, 0, 1",
      "-1, -1, 0",
      "-1, 1, 2",
      "0, 1, 1",
      "-1, -1, 0"
  })
  void should_pass_if_big_integers_difference_is_equal_to_given_offset(BigInteger actual, BigInteger expected,
                                                                       BigInteger offset) {
    numbers.assertIsCloseTo(someInfo(), actual, expected, offset(offset));
  }

  @ParameterizedTest
  @CsvSource({
      "1, 0, 1",
      "-1, 0, 1",
      "0, -1, 1",
      "-1, 1, 2",
      "0, 1, 1"
  })
  void should_fail_if_big_integers_difference_is_equal_to_given_strict_offset(BigInteger actual,
                                                                              BigInteger expected,
                                                                              BigInteger offset) {
    AssertionInfo info = someInfo();

    Throwable error = catchThrowable(() -> numbers.assertIsCloseTo(someInfo(), actual, expected, byLessThan(offset)));

    assertThat(error).isInstanceOf(AssertionError.class);
    verify(failures).failure(info, shouldBeEqual(actual, expected, byLessThan(offset), offset));
  }

  @Test
  void should_fail_if_actual_is_null() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsCloseTo(someInfo(), null, ONE, offset(ONE)))
                                                   .withMessage(actualIsNull());
  }

  @Test
  void should_fail_if__expected_value_is_null() {
    assertThatNullPointerException().isThrownBy(() -> numbers.assertIsCloseTo(someInfo(), ONE, null, within(ONE)));
  }

  @Test
  void should_fail_if_offset_is_null() {
    assertThatNullPointerException().isThrownBy(() -> numbers.assertIsCloseTo(someInfo(), ONE, ZERO, null));
  }

  // error or failure

  @Test
  void should_throw_error_if_actual_is_null() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsCloseTo(someInfo(), null, ONE, within(ONE)))
                                                   .withMessage(actualIsNull());
  }

  @Test
  void should_throw_error_if_expected_value_is_null() {
    assertThatNullPointerException().isThrownBy(() -> numbers.assertIsCloseTo(someInfo(), SIX, null, offset(ONE))).withMessage("The given number should not be null");
  }

  @Test
  void should_throw_error_if_offset_is_null() {
    assertThatNullPointerException().isThrownBy(() -> numbers.assertIsCloseTo(someInfo(), ONE, ZERO, null));
  }

  @Test
  void should_fail_if_actual_is_not_close_enough_to_expected_value() {
    AssertionInfo info = someInfo();

    Throwable error = catchThrowable(() -> numbers.assertIsCloseTo(info, ONE, TEN, within(ONE)));

    assertThat(error).isInstanceOf(AssertionError.class);
    verify(failures).failure(info, shouldBeEqual(ONE, TEN, within(ONE), NINE));
  }

  @Test
  void should_fail_if_actual_is_not_close_enough_to_expected_value_with_a_strict_offset() {
    AssertionInfo info = someInfo();

    Throwable error = catchThrowable(() -> numbers.assertIsCloseTo(info, ONE, TEN, byLessThan(ONE)));

    assertThat(error).isInstanceOf(AssertionError.class);
    verify(failures).failure(info, shouldBeEqual(ONE, TEN, byLessThan(ONE), NINE));
  }

  @Test
  void should_fail_if_difference_is_equal_to_the_given_strict_offset() {
    AssertionInfo info = someInfo();

    Throwable error = catchThrowable(() -> numbers.assertIsCloseTo(info, TWO, ONE, byLessThan(ONE)));

    assertThat(error).isInstanceOf(AssertionError.class);
    verify(failures).failure(info, shouldBeEqual(TWO, ONE, byLessThan(ONE), ONE));
  }

  // with comparison strategy

  @Test
  void should_pass_if_difference_is_less_than_given_offset_whatever_custom_comparison_strategy_is() {
    numbersWithAbsValueComparisonStrategy.assertIsCloseTo(someInfo(), ONE, ONE, within(ONE));
    numbersWithAbsValueComparisonStrategy.assertIsCloseTo(someInfo(), ONE, TWO, within(TEN));
    numbersWithAbsValueComparisonStrategy.assertIsCloseTo(someInfo(), ONE, TWO, byLessThan(TEN));
  }

  @Test
  void should_pass_if_difference_is_equal_to_given_offset_whatever_custom_comparison_strategy_is() {
    numbersWithAbsValueComparisonStrategy.assertIsCloseTo(someInfo(), ONE, ONE, within(ZERO));
    numbersWithAbsValueComparisonStrategy.assertIsCloseTo(someInfo(), ONE, ZERO, within(ONE));
    numbersWithAbsValueComparisonStrategy.assertIsCloseTo(someInfo(), ONE, TWO, within(ONE));
  }

  @Test
  void should_throw_error_if_offset_is_null_whatever_custom_comparison_strategy_is() {
    assertThatNullPointerException().isThrownBy(() -> numbersWithAbsValueComparisonStrategy.assertIsCloseTo(someInfo(), ONE, TWO, null)).withMessage(offsetIsNull());
  }

  @Test
  void should_fail_if_actual_is_not_close_enough_to_expected_value_whatever_custom_comparison_strategy_is() {
    AssertionInfo info = someInfo();

    Throwable error = catchThrowable(() -> numbersWithAbsValueComparisonStrategy.assertIsCloseTo(info, ONE, TEN, offset(ONE)));

    assertThat(error).isInstanceOf(AssertionError.class);
    verify(failures).failure(info, shouldBeEqual(ONE, TEN, offset(ONE), NINE));
  }

  @Test
  void should_fail_if_actual_is_not_strictly_close_enough_to_expected_value_whatever_custom_comparison_strategy_is() {
    AssertionInfo info = someInfo();

    Throwable error = catchThrowable(() -> numbersWithAbsValueComparisonStrategy.assertIsCloseTo(info, ONE, TEN, byLessThan(ONE)));

    assertThat(error).isInstanceOf(AssertionError.class);
    verify(failures).failure(info, shouldBeEqual(ONE, TEN, byLessThan(ONE), NINE));
  }

  @Test
  void should_throw_error_if_expected_value_is_null_whatever_custom_comparison_strategy_is() {
    assertThatNullPointerException().isThrownBy(() -> numbersWithAbsValueComparisonStrategy.assertIsCloseTo(someInfo(), TWO, null, offset(ONE))).withMessage("The given number should not be null");
  }

}


text:
#include <iosfwd>
#include "StringHash.h"

namespace VeritasEngine
{
	class IResourceManager;
	class ResourceData;
	struct Job;

	class IResourceLoader
	{
	public:
		virtual ~IResourceLoader() = default;

		virtual const char* GetExtension() const = 0;
		virtual VeritasEngine::StringHash GetExtensionHash() const = 0;
		virtual void LoadResource(IResourceManager& manager, Job* parentJob, std::istream& data, ResourceData& handle) = 0;
	};
}


text:
Generate random additions and substractions to use as homework

Output is an html file which can be printed. Just run the create_sums script.


text:
#include "mitkTestDICOMLoading.h"
#include "mitkTestingMacros.h"

#include "mitkDICOMTagCache.h"

bool CheckAllPropertiesAreInOtherList(const mitk::PropertyList* list, const mitk::PropertyList* otherList)
{
  MITK_TEST_CONDITION_REQUIRED(list && otherList, "Comparison is passed two non-empty property lists")

  const mitk::PropertyList::PropertyMap* listM = list->GetMap();
  const mitk::PropertyList::PropertyMap* otherListM = otherList->GetMap();

  bool equal = true;
  for ( mitk::PropertyList::PropertyMap::const_iterator iter = listM->begin();
        iter != listM->end();
        ++iter )
  {
    std::string key = iter->first;
    mitk::BaseProperty* property = iter->second;

    mitk::PropertyList::PropertyMap::const_iterator otherEntry = otherListM->find( key );
    MITK_TEST_CONDITION( otherEntry != otherListM->end(), "  Property '" << key << "' is contained in other list" )

    mitk::BaseProperty* otherProperty = otherEntry->second;
    MITK_TEST_CONDITION( equal &= (*property == *otherProperty), "  Property '" << key << "' is equal in both list" )
  }

  return equal;
}

bool VerifyPropertyListsEquality(const mitk::PropertyList* testList, const mitk::PropertyList* referenceList)
{
  bool allTestPropsInReference = CheckAllPropertiesAreInOtherList(testList, referenceList);
  MITK_TEST_CONDITION(allTestPropsInReference, "All test properties found in reference properties")
  bool allReferencePropsInTest = CheckAllPropertiesAreInOtherList(referenceList, testList);
  MITK_TEST_CONDITION(allReferencePropsInTest, "All reference properties found in test properties")
  return allTestPropsInReference && allReferencePropsInTest;
}

// !!! we expect that this tests get a list of files that load as ONE SINGLE mitk::Image!
int mitkDICOMPreloadedVolumeTest(int argc, char** const argv)
{
  MITK_TEST_BEGIN("DICOMPreloadedVolume")

  mitk::TestDICOMLoading loader;
  mitk::StringList files;

  // load files from commandline
  for (int arg = 1; arg < argc; ++arg)
  {
    MITK_TEST_OUTPUT(<< "Test file " << argv[arg])
    files.push_back( argv[arg] );
  }

  // verify all files are DICOM
  for (mitk::StringList::const_iterator fileIter = files.begin();
       fileIter != files.end();
       ++fileIter)
  {
    MITK_TEST_CONDITION_REQUIRED( mitk::DICOMFileReader::IsDICOM(*fileIter) , *fileIter << " is recognized as loadable DICOM object" )
  }

  // load for a first time
  mitk::TestDICOMLoading::ImageList images = loader.LoadFiles(files);
  MITK_TEST_OUTPUT(<< "Loaded " << images.size() << " images. Remembering properties of the first one for later comparison.")
  mitk::Image::Pointer firstImage = images.front();

  mitk::PropertyList::Pointer originalProperties = firstImage->GetPropertyList(); // save the original
  firstImage->SetPropertyList( mitk::PropertyList::New() ); // clear image properties
  // what about DEFAULT properties? currently ONLY nodes get default properties

  // load for a second time, this time provide the image volume as a pointer
  // expectation is that the reader will provide the same properties to this image (without actually loading a new mitk::Image)

  // !!! we expect that this tests get a list of files that load as ONE SINGLE mitk::Image!
  MITK_TEST_CONDITION_REQUIRED( images.size() == 1, "Not more than 1 images loaded." );
  // otherwise, we would need to determine the correct set of files here
  MITK_TEST_OUTPUT(<< "Generating properties via reader. Comparing new properties to previously loaded version.")
  mitk::Image::Pointer reloadedImage = loader.DecorateVerifyCachedImage(files, firstImage);
  MITK_TEST_CONDITION_REQUIRED(reloadedImage.IsNotNull(), "Reader was able to property-decorate image.");

  mitk::PropertyList::Pointer regeneratedProperties = reloadedImage->GetPropertyList(); // get the version of the second load attempt

  bool listsAreEqual = VerifyPropertyListsEquality(regeneratedProperties, originalProperties);
  MITK_TEST_CONDITION(listsAreEqual, "DICOM file reader generates a valid property list when provided a pre-loaded image");

  // test again, this time provide a tag cache.
  // expectation is, that an empty tag cache will lead to NO image
  mitk::DICOMTagCache::Pointer tagCache; // empty
  MITK_TEST_OUTPUT(<< "Generating properties via reader. Comparing new properties to previously loaded version.")
  firstImage->SetPropertyList( mitk::PropertyList::New() ); // clear image properties
  reloadedImage = loader.DecorateVerifyCachedImage(files, tagCache, firstImage);
  MITK_TEST_CONDITION_REQUIRED(reloadedImage.IsNull(), "Reader was able to detect missing tag-cache.");

  MITK_TEST_END()
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("JQDotNet")]
[assembly: InternalsVisibleTo("JQDotNet.Tests")]
[assembly: Guid("714942e8-ae13-434c-8304-f1cb1aa1f2ff")]


text:
//-----------------------------------------------------------------------
// <summary>Defines the CreateUserConfigurationRequest class.</summary>
//-----------------------------------------------------------------------

namespace Microsoft.Exchange.WebServices.Data
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    /// <summary>
    /// Represents a CreateUserConfiguration request.
    /// </summary>
    internal class CreateUserConfigurationRequest : MultiResponseServiceRequest<ServiceResponse>, IJsonSerializable
    {
        protected UserConfiguration userConfiguration;

        /// <summary>
        /// Validate request.
        /// </summary>
        internal override void Validate()
        {
            base.Validate();
            EwsUtilities.ValidateParam(this.userConfiguration, "userConfiguration");
        }

        /// <summary>
        /// Creates the service response.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="responseIndex">Index of the response.</param>
        /// <returns>Service response.</returns>
        internal override ServiceResponse CreateServiceResponse(ExchangeService service, int responseIndex)
        {
            return new ServiceResponse();
        }

        /// <summary>
        /// Gets the request version.
        /// </summary>
        /// <returns>Earliest Exchange version in which this request is supported.</returns>
        internal override ExchangeVersion GetMinimumRequiredServerVersion()
        {
            return ExchangeVersion.Exchange2010;
        }

        /// <summary>
        /// Gets the expected response message count.
        /// </summary>
        /// <returns>Number of expected response messages.</returns>
        internal override int GetExpectedResponseMessageCount()
        {
            return 1;
        }

        /// <summary>
        /// Gets the name of the XML element.
        /// </summary>
        /// <returns>XML element name,</returns>
        internal override string GetXmlElementName()
        {
            return XmlElementNames.CreateUserConfiguration;
        }

        /// <summary>
        /// Gets the name of the response XML element.
        /// </summary>
        /// <returns>XML element name,</returns>
        internal override string GetResponseXmlElementName()
        {
            return XmlElementNames.CreateUserConfigurationResponse;
        }

        /// <summary>
        /// Gets the name of the response message XML element.
        /// </summary>
        /// <returns>XML element name,</returns>
        internal override string GetResponseMessageXmlElementName()
        {
            return XmlElementNames.CreateUserConfigurationResponseMessage;
        }

        /// <summary>
        /// Writes XML elements.
        /// </summary>
        /// <param name="writer">The writer.</param>
        internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
        {
            // Write UserConfiguation element
            this.userConfiguration.WriteToXml(writer, XmlNamespace.Messages, XmlElementNames.UserConfiguration);
        }

        /// <summary>
        /// Creates a JSON representation of this object.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <returns>
        /// A Json value (either a JsonObject, an array of Json values, or a Json primitive)
        /// </returns>
        object IJsonSerializable.ToJson(ExchangeService service)
        {
            JsonObject jsonObject = new JsonObject();

            jsonObject.Add(XmlElementNames.UserConfiguration, ((IJsonSerializable)this.UserConfiguration).ToJson(service));

            return jsonObject;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CreateUserConfigurationRequest"/> class.
        /// </summary>
        /// <param name="service">The service.</param>
        internal CreateUserConfigurationRequest(ExchangeService service)
            : base(service, ServiceErrorHandling.ThrowOnError)
        {
        }

        /// <summary>
        /// Gets or sets the user configuration.
        /// </summary>
        /// <value>The userConfiguration.</value>
        public UserConfiguration UserConfiguration
        {
            get { return this.userConfiguration; }
            set { this.userConfiguration = value; }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Package org.apache.poi.poifs.dev (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.apache.poi.poifs.dev

Packages that use org.apache.poi.poifs.dev

Package
Description

org.apache.poi.poifs.filesystem

filesystem package maps OLE 2 Compound document files to a more familiar filesystem interface.

org.apache.poi.poifs.property

property package contains high and low level Property structures for POIFS.

Classes in org.apache.poi.poifs.dev used by org.apache.poi.poifs.filesystem

Class and Description

POIFSViewable

Interface for a drill-down viewable object.

Classes in org.apache.poi.poifs.dev used by org.apache.poi.poifs.property

Class and Description

POIFSViewable

Interface for a drill-down viewable object.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

                Copyright 2015 The Apache Software Foundation or
        its licensors, as applicable.


text:
#include "core/svg/SVGImageElement.h"

#include "core/CSSPropertyNames.h"
#include "core/dom/StyleChangeReason.h"
#include "core/layout/LayoutImageResource.h"
#include "core/layout/svg/LayoutSVGImage.h"

namespace blink {

inline SVGImageElement::SVGImageElement(Document& document)
    : SVGGraphicsElement(SVGNames::imageTag, document)
    , SVGURIReference(this)
    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(SVGLengthMode::Width)))
    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(SVGLengthMode::Height)))
    , m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(SVGLengthMode::Width)))
    , m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(SVGLengthMode::Height)))
    , m_preserveAspectRatio(SVGAnimatedPreserveAspectRatio::create(this, SVGNames::preserveAspectRatioAttr, SVGPreserveAspectRatio::create()))
    , m_imageLoader(SVGImageLoader::create(this))
    , m_needsLoaderURIUpdate(true)
{
    addToPropertyMap(m_x);
    addToPropertyMap(m_y);
    addToPropertyMap(m_width);
    addToPropertyMap(m_height);
    addToPropertyMap(m_preserveAspectRatio);
}

DEFINE_NODE_FACTORY(SVGImageElement)

DEFINE_TRACE(SVGImageElement)
{
    visitor->trace(m_x);
    visitor->trace(m_y);
    visitor->trace(m_width);
    visitor->trace(m_height);
    visitor->trace(m_preserveAspectRatio);
    visitor->trace(m_imageLoader);
    SVGGraphicsElement::trace(visitor);
    SVGURIReference::trace(visitor);
}

bool SVGImageElement::currentFrameHasSingleSecurityOrigin() const
{
    if (LayoutSVGImage* layoutSVGImage = toLayoutSVGImage(layoutObject())) {
        if (layoutSVGImage->imageResource()->hasImage()) {
            if (Image* image = layoutSVGImage->imageResource()->cachedImage()->image())
                return image->currentFrameHasSingleSecurityOrigin();
        }
    }

    return true;
}

bool SVGImageElement::isPresentationAttribute(const QualifiedName& attrName) const
{
    if (attrName == SVGNames::xAttr || attrName == SVGNames::yAttr
        || attrName == SVGNames::widthAttr || attrName == SVGNames::heightAttr)
        return true;
    return SVGGraphicsElement::isPresentationAttribute(attrName);
}

bool SVGImageElement::isPresentationAttributeWithSVGDOM(const QualifiedName& attrName) const
{
    if (attrName == SVGNames::xAttr || attrName == SVGNames::yAttr
        || attrName == SVGNames::widthAttr || attrName == SVGNames::heightAttr)
        return true;
    return SVGGraphicsElement::isPresentationAttributeWithSVGDOM(attrName);
}

void SVGImageElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
    SVGAnimatedPropertyBase* property = propertyFromAttribute(name);
    if (property == m_width)
        addPropertyToPresentationAttributeStyle(style, CSSPropertyWidth, m_width->currentValue()->asCSSPrimitiveValue());
    else if (property == m_height)
        addPropertyToPresentationAttributeStyle(style, CSSPropertyHeight, m_height->currentValue()->asCSSPrimitiveValue());
    else if (property == m_x)
        addPropertyToPresentationAttributeStyle(style, CSSPropertyX, m_x->currentValue()->asCSSPrimitiveValue());
    else if (property == m_y)
        addPropertyToPresentationAttributeStyle(style, CSSPropertyY, m_y->currentValue()->asCSSPrimitiveValue());
    else
        SVGGraphicsElement::collectStyleForPresentationAttribute(name, value, style);
}

void SVGImageElement::svgAttributeChanged(const QualifiedName& attrName)
{
    bool isLengthAttribute = attrName == SVGNames::xAttr
                          || attrName == SVGNames::yAttr
                          || attrName == SVGNames::widthAttr
                          || attrName == SVGNames::heightAttr;

    if (isLengthAttribute || attrName == SVGNames::preserveAspectRatioAttr) {
        SVGElement::InvalidationGuard invalidationGuard(this);

        if (isLengthAttribute) {
            invalidateSVGPresentationAttributeStyle();
            setNeedsStyleRecalc(LocalStyleChange,
                StyleChangeReasonForTracing::fromAttribute(attrName));
            updateRelativeLengthsInformation();
        }

        LayoutObject* object = this->layoutObject();
        if (!object)
            return;

        // FIXME: if isLengthAttribute then we should avoid this call if the
        // viewport didn't change, however since we don't have the computed
        // style yet we can't use updateBoundingBox/updateImageContainerSize.
        // See http://crbug.com/466200.
        markForLayoutAndParentResourceInvalidation(object);
        return;
    }

    if (SVGURIReference::isKnownAttribute(attrName)) {
        SVGElement::InvalidationGuard invalidationGuard(this);
        if (inDocument())
            imageLoader().updateFromElement(ImageLoader::UpdateIgnorePreviousError);
        else
            m_needsLoaderURIUpdate = true;
        return;
    }

    SVGGraphicsElement::svgAttributeChanged(attrName);
}

bool SVGImageElement::selfHasRelativeLengths() const
{
    return m_x->currentValue()->isRelative()
        || m_y->currentValue()->isRelative()
        || m_width->currentValue()->isRelative()
        || m_height->currentValue()->isRelative();
}

LayoutObject* SVGImageElement::createLayoutObject(const ComputedStyle&)
{
    return new LayoutSVGImage(this);
}

bool SVGImageElement::haveLoadedRequiredResources()
{
    return !m_needsLoaderURIUpdate && !imageLoader().hasPendingActivity();
}

void SVGImageElement::attach(const AttachContext& context)
{
    SVGGraphicsElement::attach(context);

    if (LayoutSVGImage* imageObj = toLayoutSVGImage(layoutObject())) {
        if (imageObj->imageResource()->hasImage())
            return;

        imageObj->imageResource()->setImageResource(imageLoader().image());
    }
}

Node::InsertionNotificationRequest SVGImageElement::insertedInto(ContainerNode* rootParent)
{
    SVGGraphicsElement::insertedInto(rootParent);
    if (!rootParent->inDocument())
        return InsertionDone;

    // We can only resolve base URIs properly after tree insertion - hence, URI mutations while
    // detached are deferred until this point.
    if (m_needsLoaderURIUpdate) {
        imageLoader().updateFromElement(ImageLoader::UpdateIgnorePreviousError);
        m_needsLoaderURIUpdate = false;
    } else {
        // A previous loader update may have failed to actually fetch the image if the document
        // was inactive. In that case, force a re-update (but don't clear previous errors).
        if (!imageLoader().image())
            imageLoader().updateFromElement();
    }

    return InsertionDone;
}

const AtomicString SVGImageElement::imageSourceURL() const
{
    return AtomicString(hrefString());
}

void SVGImageElement::didMoveToNewDocument(Document& oldDocument)
{
    imageLoader().elementDidMoveToNewDocument();
    SVGGraphicsElement::didMoveToNewDocument(oldDocument);
}

} // namespace blink


text:
from atom.api import Typed

from enaml.widgets.radio_button import ProxyRadioButton

from .QtGui import QRadioButton

from .qt_abstract_button import QtAbstractButton

class QtRadioButton(QtAbstractButton, ProxyRadioButton):
    """ A Qt implementation of an Enaml RadioButton.

    """
    #: A reference to the widget created by the proxy.
    widget = Typed(QRadioButton)

    def create_widget(self):
        """ Create the underlying radio button widget.

        """
        self.widget = QRadioButton(self.parent_widget())


text:
You're create a `jvm_app` target definition for [[bundling|pants('src/docs/common_tasks:bundle')]] a Scala or Java project and you want to include assets such as config files or shell scripts in the bundle.

## Solution

Add a `bundles` list to your `jvm_app` target definition (more info on `jvm_app` definitions can be found in [[Define a Scala or Java Bundle Target|pants('src/docs/common_tasks:bundle')]]).

## Discussion

Here is an example `jvm_app` definition that shows different possibilities for defining file bundles (and explains them below):

    ::python
    jvm_app(name='bundle',
      bundle(fileset=rglobs('src/main/resources/*')), # 1
      bundle(fileset=globs('config/*') - globs('*.xml'), # 2
      bundle(relative_to='src', fileset=globs('src/scripts/*.sh')) # 3
    )

1. The `rglobs` definition will recursively include all files in the `src/main/resources` directory, *including all sub-directories*. More info can be found in [[Use globs and rglobs to group files|pants('src/docs/common_tasks:globs')]].
2. All files in the `config` directory are included except any `.xml` files.
3. All `.sh` files in the `src/scripts` directory will be included. The `relative_to` effectively strips away the specified directory, in this case `src`, which means that all files in `src/scripts` would end up in the root of the bundle. If you specified `relative_to='src/scripts'` instead, for example, all files would end up in the root directory.

## See Also

* [[Create a Bundled zip or Other Archive|pants('src/docs/common_tasks:bundle')]]
* [[Use globs and rglobs to Group Files|pants('src/docs/common_tasks:globs')]]


text:
@interface DeliverTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *date;
@property (weak, nonatomic) IBOutlet UILabel *remark;

@end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Chrysanthemum coronarium var. discolor d'Urv.

### Remarks
null


text:
package javax.ws.rs.core;

public class Cookie {
    public Cookie(final String name, final String value, final String path, final String domain, final int version)
            throws IllegalArgumentException {
    }

    public Cookie(final String name, final String value, final String path, final String domain)
            throws IllegalArgumentException {
    }

    public Cookie(final String name, final String value)
            throws IllegalArgumentException {
    }

    public static Cookie valueOf(final String value) {
      return null;
    }

    public String getName() {
      return null;
    }

    public String getValue() {
      return null;
    }

    public int getVersion() {
      return 0;
    }

    public String getDomain() {
      return null;
    }

    public String getPath() {
      return null;
    }

    @Override
    public String toString() {
      return null;
    }

    @Override
    public int hashCode() {
      return 0;
    }

    @Override
    public boolean equals(final Object obj) {
      return false;
    }

}


text:
require_relative 'spec_helper'

describe SharedFormulaBuilder, "Formulas with shared_formula_offsets" do

  before(:each) do
    @builder = SharedFormulaBuilder.new
    @builder.shared_formula_offset = [1,1]
  end

  def ruby_for(formula)
    ast = Formula.parse(formula)
    ast.visit(@builder)
  end

  it "should move individual references appropriately" do
    ruby_for("A1").should == "b2"
    ruby_for("A$1").should == "b1"
    ruby_for("$A1").should == "a2"
    ruby_for("$A$1").should == "a1"
  end

  it "should move several references in the same formula" do
    ruby_for("A1+B2").should == "b2+c3"
    ruby_for("A$1+B$1").should == "b1+c1"
    ruby_for("$A1+$B1").should == "a2+b2"
    ruby_for("$A$1+$B$1").should == "a1+b1"
  end

end


text:
FROM  node:8

WORKDIR /app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied where available (npm@5+)
COPY package*.json ./
RUN npm install
RUN npm i -g bower gulp svgo
COPY bower.json ./
RUN bower install --allow-root

COPY . .


text:
package cam.base.engine;

import java.util.HashMap;
import java.util.Map;

import cam.base.VMath.Vector3f;

public class LightManager
{
	private Map<String, SpotLight> spotLights = new HashMap<String, SpotLight> ();
	private Map<String, DirectionLight> directionLights = new HashMap<String, DirectionLight> ();
	private Map<String, PointLight> pointLights = new HashMap<String, PointLight> ();
	private static LightManager instance = new LightManager();
	private LightingShader shader;

	public static LightManager getInstance()
	{
		return instance;
	}

	private LightManager()
	{
		shader = LightingShader.getInstance();
	}

	public void addDirectionLight(String id, DirectionLight dLight)
	{
		if(directionLights.containsKey(id))
		{
			System.err.println("This list already contains a directionLight with a id of " + id);
			return;
		}

		directionLights.put(id, dLight);
	}

	public void addSpotLight(String id, SpotLight sLight)
	{
		if(spotLights.containsKey(id))
		{
			System.err.println("This list already contains a spotLight with a id of " + id);
			return;
		}

		spotLights.put(id, sLight);
	}

	public void addPointLight(String id, PointLight pLight)
	{
		if(pointLights.containsKey(id))
		{
			System.err.println("This list already contains a pointLight with a id of " + id);
			return;
		}

		pointLights.put(id, pLight);
	}

	public void enableSpotLight(String id)
	{
		if(!spotLights.containsKey(id))
		{
			System.err.println("There exists no spotlight with the id of " + id + " in the spotLight list");
			return;
		}

		shader.addSpotLight(spotLights.get(id));
	}

	public void enablePointLight(String id)
	{
		if(!pointLights.containsKey(id))
		{
			System.err.println("There exists no pointlight with the id of " + id + " in the pointLight list");
			return;
		}

		shader.addPointLight(pointLights.get(id));
	}

	public void enableDirectionLight(String id)
	{
		if(!directionLights.containsKey(id))
		{
			System.err.println("There exists no directionlight with the id of " + id + " in the directionLight list");
			return;
		}

		shader.setDirectionLight(directionLights.get(id));
	}

	public void disableSpotLight(String id)
	{
		if(!spotLights.containsKey(id))
		{
			System.err.println("There exists no spotlight with the id of " + id + " in the spotLight list");
			return;
		}

		shader.removeSpotLight(spotLights.get(id));
	}

	public void disablePointLight(String id)
	{
		if(!pointLights.containsKey(id))
		{
			System.err.println("There exists no pointlight with the id of " + id + " in the pointLight list");
			return;
		}

		shader.removePointLight(pointLights.get(id));
	}

	public void disableDirectionLight(String id)
	{
		shader.setDirectionLight(new DirectionLight(new BaseLight(new Vector3f(0,0,0), 0), new Vector3f(0,0,0)));
	}

	public void removeSpotLight(String id)
	{
		if(!spotLights.containsKey(id))
		{
			System.err.println("There exists no spotlight with the id of " + id + " in the spotLight list");
			return;
		}

		if(shader.spotLightsContain(id))
		{
			shader.removeSpotLight(spotLights.get(id));
		}

		spotLights.remove(id);
	}

	public void removePointLight(String id)
	{
		if(!pointLights.containsKey(id))
		{
			System.err.println("There exists no pointlight with the id of " + id + " in the pointLight list");
			return;
		}

		if(shader.pointLightsContain(id))
		{
			shader.removePointLight(pointLights.get(id));
		}

		pointLights.remove(id);
	}

	public void removeDirectionLight(String id)
	{
		if(!directionLights.containsKey(id))
		{
			System.err.println("There exists no directionlight with the id of " + id + " in the directionLight list");
			return;
		}

		disableDirectionLight(id);
		directionLights.remove(id);
	}

	public void setAmbientLight(Vector3f color)
	{
		shader.setAmbientLight(color);
	}

	public SpotLight getSpotLight(String id)
	{
		if(!spotLights.containsKey(id))
		{
			System.err.println("There exists no spotlight with the id of " + id + " in the spotLight list");
			return null;
		}

		return spotLights.get(id);
	}

	public PointLight getPointLight(String id)
	{
		if(!pointLights.containsKey(id))
		{
			System.err.println("There exists no pointlight with the id of " + id + " in the pointLight list");
			return null;
		}

		return pointLights.get(id);
	}

	public DirectionLight getDirectionLight(String id)
	{
		if(!directionLights.containsKey(id))
		{
			System.err.println("There exists no directionlight with the id of " + id + " in the pointLight list");
			return null;
		}

		return directionLights.get(id);
	}

}


text: Word Cloud using D3.js


text:
{{#template name="angular-step03"}}

# Storing tasks in a collection

{{> step03CollectionsIntro}}

Let's update our JavaScript code to get our tasks from a collection instead of a static array:

{{> DiffBox tutorialName="simple-todos-angular" step="3.1"}}

We are using the `$meteor` service to bind our `Tasks` collection to our `$scope.tasks` variable.
Now every change that will happen to each of those objects will be synced in real time across our stack.

When you make these changes to the code, you'll notice that the tasks that used to be in the todo list have disappeared. That's because our database is currently empty — we need to insert some tasks!

{{> step03InsertingTasksFromConsole}}

{{/template}}


text:
package org.apache.tapestry5.plastic.test;

import org.apache.tapestry5.plastic.MethodAdvice;
import org.apache.tapestry5.plastic.MethodInvocation;

public class NoopAdvice implements MethodAdvice
{

    @Override
    public void advise(MethodInvocation invocation)
    {
        invocation.proceed();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.alorma.sharingaccounts">

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".LoginActivity" />

        <service android:name=".account.AccountService">
            <intent-filter>
                <action android:name="android.accounts.AccountAuthenticator" />
            </intent-filter>
            <meta-data
                android:name="android.accounts.AccountAuthenticator"
                android:resource="@xml/account_authenticator" />
        </service>
    </application>

</manifest>


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Test;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Contracts\Service\ResetInterface;

/**
 * KernelTestCase is the base class for tests needing a Kernel.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
abstract class KernelTestCase extends TestCase
{
    use MailerAssertionsTrait;

    protected static $class;

    /**
     * @var KernelInterface
     */
    protected static $kernel;

    /**
     * @var ContainerInterface
     *
     * @deprecated since Symfony 5.3, use static::getContainer() instead
     */
    protected static $container;

    protected static $booted = false;

    private static $kernelContainer;

    protected function tearDown(): void
    {
        static::ensureKernelShutdown();
        static::$kernel = null;
        static::$booted = false;
    }

    /**
     * @return string
     *
     * @throws \RuntimeException
     * @throws \LogicException
     */
    protected static function getKernelClass()
    {
        if (!isset($_SERVER['KERNEL_CLASS']) && !isset($_ENV['KERNEL_CLASS'])) {
            throw new \LogicException(sprintf('You must set the KERNEL_CLASS environment variable to the fully-qualified class name of your Kernel in phpunit.xml / phpunit.xml.dist or override the "%1$s::createKernel()" or "%1$s::getKernelClass()" method.', static::class));
        }

        if (!class_exists($class = $_ENV['KERNEL_CLASS'] ?? $_SERVER['KERNEL_CLASS'])) {
            throw new \RuntimeException(sprintf('Class "%s" doesn\'t exist or cannot be autoloaded. Check that the KERNEL_CLASS value in phpunit.xml matches the fully-qualified class name of your Kernel or override the "%s::createKernel()" method.', $class, static::class));
        }

        return $class;
    }

    /**
     * Boots the Kernel for this test.
     *
     * @return KernelInterface
     */
    protected static function bootKernel(array $options = [])
    {
        static::ensureKernelShutdown();

        static::$kernel = static::createKernel($options);
        static::$kernel->boot();
        static::$booted = true;

        self::$kernelContainer = $container = static::$kernel->getContainer();
        static::$container = $container->has('test.service_container') ? $container->get('test.service_container') : $container;

        return static::$kernel;
    }

    /**
     * Provides a dedicated test container with access to both public and private
     * services. The container will not include private services that have been
     * inlined or removed. Private services will be removed when they are not
     * used by other services.
     *
     * Using this method is the best way to get a container from your test code.
     */
    protected static function getContainer(): ContainerInterface
    {
        if (!static::$booted) {
            static::bootKernel();
        }

        try {
            return self::$kernelContainer->get('test.service_container');
        } catch (ServiceNotFoundException $e) {
            throw new \LogicException('Could not find service "test.service_container". Try updating the "framework.test" config to "true".', 0, $e);
        }
    }

    /**
     * Creates a Kernel.
     *
     * Available options:
     *
     *  * environment
     *  * debug
     *
     * @return KernelInterface
     */
    protected static function createKernel(array $options = [])
    {
        if (null === static::$class) {
            static::$class = static::getKernelClass();
        }

        if (isset($options['environment'])) {
            $env = $options['environment'];
        } elseif (isset($_ENV['APP_ENV'])) {
            $env = $_ENV['APP_ENV'];
        } elseif (isset($_SERVER['APP_ENV'])) {
            $env = $_SERVER['APP_ENV'];
        } else {
            $env = 'test';
        }

        if (isset($options['debug'])) {
            $debug = $options['debug'];
        } elseif (isset($_ENV['APP_DEBUG'])) {
            $debug = $_ENV['APP_DEBUG'];
        } elseif (isset($_SERVER['APP_DEBUG'])) {
            $debug = $_SERVER['APP_DEBUG'];
        } else {
            $debug = true;
        }

        return new static::$class($env, $debug);
    }

    /**
     * Shuts the kernel down if it was used in the test - called by the tearDown method by default.
     */
    protected static function ensureKernelShutdown()
    {
        if (null !== static::$kernel) {
            static::$kernel->shutdown();
            static::$booted = false;
        }

        if (self::$kernelContainer instanceof ResetInterface) {
            self::$kernelContainer->reset();
        }

        static::$container = self::$kernelContainer = null;
    }
}