text:
package com.esotericsoftware.kryo.io;

import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.io.KryoBufferUnderflowException;
import com.esotericsoftware.kryo.util.Util;

import java.io.IOException;
import java.io.InputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/** An {@link Input} that uses a ByteBuffer rather than a byte[].
 * <p>
 * Note that the byte[] {@link #getBuffer() buffer} is not used. Code taking an Input and expecting the byte[] to be used may not
 * work correctly.
 * @author Roman Levenstein <romixlev@gmail.com>
 * @author Nathan Sweet */
public class ByteBufferInput extends Input {
	private static final ByteOrder nativeOrder = ByteOrder.nativeOrder();

	protected ByteBuffer byteBuffer;
	private byte[] tempBuffer;

	/** Creates an uninitialized Input, {@link #setBuffer(ByteBuffer)} must be called before the Input is used. */
	public ByteBufferInput () {
	}

	/** Creates a new Input for reading from a direct {@link ByteBuffer}.
	 * @param bufferSize The size of the buffer. An exception is thrown if more bytes than this are read and
	 *           {@link #fill(ByteBuffer, int, int)} does not supply more bytes. */
	public ByteBufferInput (int bufferSize) {
		this.capacity = bufferSize;
		byteBuffer = ByteBuffer.allocateDirect(bufferSize);
	}

	/** Creates a new Input for reading from a {@link ByteBuffer} which is filled with the specified bytes. */
	public ByteBufferInput (byte[] bytes) {
		this(bytes, 0, bytes.length);
	}

	/** Creates a new Input for reading from a {@link ByteBuffer} which is filled with the specified bytes.
	 * @see #setBuffer(byte[], int, int) */
	public ByteBufferInput (byte[] bytes, int offset, int count) {
		if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
		ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.length);
		buffer.put(bytes);
		flipBuffer(buffer);
		setBuffer(buffer);
	}

	/** Creates a new Input for reading from a ByteBuffer. */
	public ByteBufferInput (ByteBuffer buffer) {
		setBuffer(buffer);
	}

	/** @see Input#Input(InputStream) */
	public ByteBufferInput (InputStream inputStream) {
		this(4096);
		if (inputStream == null) throw new IllegalArgumentException("inputStream cannot be null.");
		this.inputStream = inputStream;
	}

	/** @see Input#Input(InputStream, int) */
	public ByteBufferInput (InputStream inputStream, int bufferSize) {
		this(bufferSize);
		if (inputStream == null) throw new IllegalArgumentException("inputStream cannot be null.");
		this.inputStream = inputStream;
	}

	/** Throws {@link UnsupportedOperationException} because this input uses a ByteBuffer, not a byte[].
	 * @deprecated
	 * @see #getByteBuffer() */
	public byte[] getBuffer () {
		throw new UnsupportedOperationException("This input does not used a byte[], see #getByteBuffer().");
	}

	/** Throws {@link UnsupportedOperationException} because this input uses a ByteBuffer, not a byte[].
	 * @deprecated
	 * @see #setBuffer(ByteBuffer) */
	public void setBuffer (byte[] bytes) {
		throw new UnsupportedOperationException("This input does not used a byte[], see #setByteBuffer(ByteBuffer).");
	}

	/** Throws {@link UnsupportedOperationException} because this input uses a ByteBuffer, not a byte[].
	 * @deprecated
	 * @see #setBuffer(ByteBuffer) */
	public void setBuffer (byte[] bytes, int offset, int count) {
		throw new UnsupportedOperationException("This input does not used a byte[], see #setByteBufferByteBuffer().");
	}

	/** Sets a new buffer to read from. The bytes are not copied, the old buffer is discarded and the new buffer used in its place.
	 * The position, limit, and capacity are set to match the specified buffer. The total is reset. The
	 * {@link #setInputStream(InputStream) InputStream} is set to null. */
	public void setBuffer (ByteBuffer buffer) {
		if (buffer == null) throw new IllegalArgumentException("buffer cannot be null.");
		byteBuffer = buffer;
		position = buffer.position();
		limit = buffer.limit();
		capacity = buffer.capacity();
		total = 0;
		inputStream = null;
	}

	public ByteBuffer getByteBuffer () {
		return byteBuffer;
	}

	public void setInputStream (InputStream inputStream) {
		this.inputStream = inputStream;
		limit = 0;
		reset();
	}

	public void reset () {
		super.reset();
		setBufferPosition(byteBuffer, 0);
	}

	/** Fills the buffer with more bytes. May leave the buffer position changed. The default implementation reads from the
	 * {@link #getInputStream() InputStream}, if set. Can be overridden to fill the bytes from another source. */
	protected int fill (ByteBuffer buffer, int offset, int count) throws KryoException {
		if (inputStream == null) return -1;
		try {
			if (tempBuffer == null) tempBuffer = new byte[2048];
			setBufferPosition(buffer, offset);
			int total = 0;
			while (count > 0) {
				int read = inputStream.read(tempBuffer, 0, Math.min(tempBuffer.length, count));
				if (read == -1) {
					if (total == 0) return -1;
					break;
				}
				buffer.put(tempBuffer, 0, read);
				count -= read;
				total += read;
			}
			return total;
		} catch (IOException ex) {
			throw new KryoException(ex);
		}
	}

	protected int require (int required) throws KryoException {
		int remaining = limit - position;
		if (remaining >= required) return remaining;
		if (required > capacity) throw new KryoException("Buffer too small: capacity: " + capacity + ", required: " + required);

		int count;

		// Try to fill the buffer.
		if (remaining > 0) {
			count = fill(byteBuffer, limit, capacity - limit);
			if (count == -1) throw new KryoBufferUnderflowException("Buffer underflow.");
			setBufferPosition(byteBuffer, position);
			remaining += count;
			if (remaining >= required) {
				limit += count;
				return remaining;
			}
		}

		// Compact.
		byteBuffer.compact(); // Buffer's position is at end of compacted bytes.
		total += position;
		position = 0;

		// Try to fill again.
		while (true) {
			count = fill(byteBuffer, remaining, capacity - remaining);
			if (count == -1) {
				if (remaining >= required) break;
				throw new KryoBufferUnderflowException("Buffer underflow.");
			}
			remaining += count;
			if (remaining >= required) break; // Enough has been read.
		}
		limit = remaining;
		setBufferPosition(byteBuffer, 0);
		return remaining;
	}

	/** Fills the buffer with at least the number of bytes specified, if possible.
	 * @param optional Must be > 0.
	 * @return the number of bytes remaining, but not more than optional, or -1 if {@link #fill(ByteBuffer, int, int)} is unable to
	 *         provide more bytes. */
	protected int optional (int optional) throws KryoException {
		int remaining = limit - position;
		if (remaining >= optional) return optional;
		optional = Math.min(optional, capacity);

		// Try to fill the buffer.
		int count = fill(byteBuffer, limit, capacity - limit);
		setBufferPosition(byteBuffer, position);
		if (count == -1) return remaining == 0 ? -1 : Math.min(remaining, optional);
		remaining += count;
		if (remaining >= optional) {
			limit += count;
			return optional;
		}

		// Compact.
		byteBuffer.compact(); // Buffer's position is at end of compacted bytes.
		total += position;
		position = 0;

		// Try to fill again.
		while (true) {
			count = fill(byteBuffer, remaining, capacity - remaining);
			if (count == -1) break;
			remaining += count;
			if (remaining >= optional) break; // Enough has been read.
		}
		limit = remaining;
		setBufferPosition(byteBuffer, 0);
		return remaining == 0 ? -1 : Math.min(remaining, optional);
	}

	// InputStream:

	public int read () throws KryoException {
		if (optional(1) <= 0) return -1;
		position++;
		return byteBuffer.get() & 0xFF;
	}

	public int read (byte[] bytes) throws KryoException {
		return read(bytes, 0, bytes.length);
	}

	public int read (byte[] bytes, int offset, int count) throws KryoException {
		if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
		int startingCount = count;
		int copyCount = Math.min(limit - position, count);
		while (true) {
			byteBuffer.get(bytes, offset, copyCount);
			position += copyCount;
			count -= copyCount;
			if (count == 0) break;
			offset += copyCount;
			copyCount = optional(count);
			if (copyCount == -1) {
				// End of data.
				if (startingCount == count) return -1;
				break;
			}
			if (position == limit) break;
		}
		return startingCount - count;
	}

	public void setPosition (int position) {
		this.position = position;
		setBufferPosition(byteBuffer, position);
	}

	public void setLimit (int limit) {
		this.limit = limit;
		setBufferLimit(byteBuffer, limit);
	}

	public void skip (int count) throws KryoException {
		super.skip(count);
		setBufferPosition(byteBuffer, position);
	}

	public long skip (long count) throws KryoException {
		long remaining = count;
		while (remaining > 0) {
			int skip = (int)Math.min(Util.maxArraySize, remaining);
			skip(skip);
			remaining -= skip;
		}
		return count;
	}

	public void close () throws KryoException {
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException ignored) {
			}
		}
	}

	private int getBufferPosition (Buffer buffer) {
		return buffer.position();
	}

	private void setBufferPosition (Buffer buffer, int position) {
		buffer.position(position);
	}

	private void setBufferLimit (Buffer buffer, int limit) {
		buffer.limit(limit);
	}

	private void flipBuffer (Buffer buffer) {
		buffer.flip();
	}

	// byte:

	public byte readByte () throws KryoException {
		if (position == limit) require(1);
		position++;
		return byteBuffer.get();
	}

	public int readByteUnsigned () throws KryoException {
		if (position == limit) require(1);
		position++;
		return byteBuffer.get() & 0xFF;
	}

	public byte[] readBytes (int length) throws KryoException {
		byte[] bytes = new byte[length];
		readBytes(bytes, 0, length);
		return bytes;
	}

	public void readBytes (byte[] bytes, int offset, int count) throws KryoException {
		if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
		int copyCount = Math.min(limit - position, count);
		while (true) {
			byteBuffer.get(bytes, offset, copyCount);
			position += copyCount;
			count -= copyCount;
			if (count == 0) break;
			offset += copyCount;
			copyCount = Math.min(count, capacity);
			require(copyCount);
		}
	}

	// int:

	public int readInt () throws KryoException {
		require(4);
		position += 4;
		ByteBuffer byteBuffer = this.byteBuffer;
		return byteBuffer.get() & 0xFF //
			| (byteBuffer.get() & 0xFF) << 8 //
			| (byteBuffer.get() & 0xFF) << 16 //
			| (byteBuffer.get() & 0xFF) << 24;
	}

	public int readVarInt (boolean optimizePositive) throws KryoException {
		if (require(1) < 5) return readVarInt_slow(optimizePositive);
		int b = byteBuffer.get();
		int result = b & 0x7F;
		if ((b & 0x80) != 0) {
			ByteBuffer byteBuffer = this.byteBuffer;
			b = byteBuffer.get();
			result |= (b & 0x7F) << 7;
			if ((b & 0x80) != 0) {
				b = byteBuffer.get();
				result |= (b & 0x7F) << 14;
				if ((b & 0x80) != 0) {
					b = byteBuffer.get();
					result |= (b & 0x7F) << 21;
					if ((b & 0x80) != 0) {
						b = byteBuffer.get();
						result |= (b & 0x7F) << 28;
					}
				}
			}
		}
		position = getBufferPosition(byteBuffer);
		return optimizePositive ? result : ((result >>> 1) ^ -(result & 1));
	}

	private int readVarInt_slow (boolean optimizePositive) {
		// The buffer is guaranteed to have at least 1 byte.
		position++;
		int b = byteBuffer.get();
		int result = b & 0x7F;
		if ((b & 0x80) != 0) {
			if (position == limit) require(1);
			ByteBuffer byteBuffer = this.byteBuffer;
			position++;
			b = byteBuffer.get();
			result |= (b & 0x7F) << 7;
			if ((b & 0x80) != 0) {
				if (position == limit) require(1);
				position++;
				b = byteBuffer.get();
				result |= (b & 0x7F) << 14;
				if ((b & 0x80) != 0) {
					if (position == limit) require(1);
					position++;
					b = byteBuffer.get();
					result |= (b & 0x7F) << 21;
					if ((b & 0x80) != 0) {
						if (position == limit) require(1);
						position++;
						b = byteBuffer.get();
						result |= (b & 0x7F) << 28;
					}
				}
			}
		}
		return optimizePositive ? result : ((result >>> 1) ^ -(result & 1));
	}

	public boolean canReadVarInt () throws KryoException {
		if (limit - position >= 5) return true;
		if (optional(5) <= 0) return false;
		int p = position, limit = this.limit;
		ByteBuffer byteBuffer = this.byteBuffer;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		return true;
	}

	/** Reads the boolean part of a varint flag. The position is not advanced, {@link #readVarIntFlag(boolean)} should be used to
	 * advance the position. */
	public boolean readVarIntFlag () {
		if (position == limit) require(1);
		return (byteBuffer.get(position) & 0x80) != 0;
	}

	/** Reads the 1-5 byte int part of a varint flag. The position is advanced so if the boolean part is needed it should be read
	 * first with {@link #readVarIntFlag()}. */
	public int readVarIntFlag (boolean optimizePositive) {
		if (require(1) < 5) return readVarIntFlag_slow(optimizePositive);
		int b = byteBuffer.get();
		int result = b & 0x3F; // Mask first 6 bits.
		if ((b & 0x40) != 0) { // Bit 7 means another byte, bit 8 means UTF8.
			ByteBuffer byteBuffer = this.byteBuffer;
			b = byteBuffer.get();
			result |= (b & 0x7F) << 6;
			if ((b & 0x80) != 0) {
				b = byteBuffer.get();
				result |= (b & 0x7F) << 13;
				if ((b & 0x80) != 0) {
					b = byteBuffer.get();
					result |= (b & 0x7F) << 20;
					if ((b & 0x80) != 0) {
						b = byteBuffer.get();
						result |= (b & 0x7F) << 27;
					}
				}
			}
		}
		position = getBufferPosition(byteBuffer);
		return optimizePositive ? result : ((result >>> 1) ^ -(result & 1));
	}

	private int readVarIntFlag_slow (boolean optimizePositive) {
		// The buffer is guaranteed to have at least 1 byte.
		position++;
		int b = byteBuffer.get();
		int result = b & 0x3F;
		if ((b & 0x40) != 0) {
			if (position == limit) require(1);
			position++;
			ByteBuffer byteBuffer = this.byteBuffer;
			b = byteBuffer.get();
			result |= (b & 0x7F) << 6;
			if ((b & 0x80) != 0) {
				if (position == limit) require(1);
				position++;
				b = byteBuffer.get();
				result |= (b & 0x7F) << 13;
				if ((b & 0x80) != 0) {
					if (position == limit) require(1);
					position++;
					b = byteBuffer.get();
					result |= (b & 0x7F) << 20;
					if ((b & 0x80) != 0) {
						if (position == limit) require(1);
						position++;
						b = byteBuffer.get();
						result |= (b & 0x7F) << 27;
					}
				}
			}
		}
		return optimizePositive ? result : ((result >>> 1) ^ -(result & 1));
	}

	// long:

	public long readLong () throws KryoException {
		require(8);
		position += 8;
		ByteBuffer byteBuffer = this.byteBuffer;
		return byteBuffer.get() & 0xFF //
			| (byteBuffer.get() & 0xFF) << 8 //
			| (byteBuffer.get() & 0xFF) << 16 //
			| (long)(byteBuffer.get() & 0xFF) << 24 //
			| (long)(byteBuffer.get() & 0xFF) << 32 //
			| (long)(byteBuffer.get() & 0xFF) << 40 //
			| (long)(byteBuffer.get() & 0xFF) << 48 //
			| (long)byteBuffer.get() << 56;
	}

	public long readVarLong (boolean optimizePositive) throws KryoException {
		if (require(1) < 9) return readVarLong_slow(optimizePositive);
		int b = byteBuffer.get();
		long result = b & 0x7F;
		if ((b & 0x80) != 0) {
			ByteBuffer byteBuffer = this.byteBuffer;
			b = byteBuffer.get();
			result |= (b & 0x7F) << 7;
			if ((b & 0x80) != 0) {
				b = byteBuffer.get();
				result |= (b & 0x7F) << 14;
				if ((b & 0x80) != 0) {
					b = byteBuffer.get();
					result |= (b & 0x7F) << 21;
					if ((b & 0x80) != 0) {
						b = byteBuffer.get();
						result |= (long)(b & 0x7F) << 28;
						if ((b & 0x80) != 0) {
							b = byteBuffer.get();
							result |= (long)(b & 0x7F) << 35;
							if ((b & 0x80) != 0) {
								b = byteBuffer.get();
								result |= (long)(b & 0x7F) << 42;
								if ((b & 0x80) != 0) {
									b = byteBuffer.get();
									result |= (long)(b & 0x7F) << 49;
									if ((b & 0x80) != 0) {
										b = byteBuffer.get();
										result |= (long)b << 56;
									}
								}
							}
						}
					}
				}
			}
		}
		position = getBufferPosition(byteBuffer);
		return optimizePositive ? result : ((result >>> 1) ^ -(result & 1));
	}

	private long readVarLong_slow (boolean optimizePositive) {
		// The buffer is guaranteed to have at least 1 byte.
		position++;
		int b = byteBuffer.get();
		long result = b & 0x7F;
		if ((b & 0x80) != 0) {
			if (position == limit) require(1);
			ByteBuffer byteBuffer = this.byteBuffer;
			position++;
			b = byteBuffer.get();
			result |= (b & 0x7F) << 7;
			if ((b & 0x80) != 0) {
				if (position == limit) require(1);
				position++;
				b = byteBuffer.get();
				result |= (b & 0x7F) << 14;
				if ((b & 0x80) != 0) {
					if (position == limit) require(1);
					position++;
					b = byteBuffer.get();
					result |= (b & 0x7F) << 21;
					if ((b & 0x80) != 0) {
						if (position == limit) require(1);
						position++;
						b = byteBuffer.get();
						result |= (long)(b & 0x7F) << 28;
						if ((b & 0x80) != 0) {
							if (position == limit) require(1);
							position++;
							b = byteBuffer.get();
							result |= (long)(b & 0x7F) << 35;
							if ((b & 0x80) != 0) {
								if (position == limit) require(1);
								position++;
								b = byteBuffer.get();
								result |= (long)(b & 0x7F) << 42;
								if ((b & 0x80) != 0) {
									if (position == limit) require(1);
									position++;
									b = byteBuffer.get();
									result |= (long)(b & 0x7F) << 49;
									if ((b & 0x80) != 0) {
										if (position == limit) require(1);
										position++;
										b = byteBuffer.get();
										result |= (long)b << 56;
									}
								}
							}
						}
					}
				}
			}
		}
		return optimizePositive ? result : ((result >>> 1) ^ -(result & 1));
	}

	public boolean canReadVarLong () throws KryoException {
		if (limit - position >= 9) return true;
		if (optional(5) <= 0) return false;
		int p = position, limit = this.limit;
		ByteBuffer byteBuffer = this.byteBuffer;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((byteBuffer.get(p++) & 0x80) == 0) return true;
		if (p == limit) return false;
		return true;
	}

	// float:

	public float readFloat () throws KryoException {
		require(4);
		ByteBuffer byteBuffer = this.byteBuffer;
		int p = this.position;
		this.position = p + 4;
		return Float.intBitsToFloat(byteBuffer.get() & 0xFF //
			| (byteBuffer.get() & 0xFF) << 8 //
			| (byteBuffer.get() & 0xFF) << 16 //
			| (byteBuffer.get() & 0xFF) << 24);
	}

	// double:

	public double readDouble () throws KryoException {
		require(8);
		ByteBuffer byteBuffer = this.byteBuffer;
		int p = position;
		position = p + 8;
		return Double.longBitsToDouble(byteBuffer.get() & 0xFF //
			| (byteBuffer.get() & 0xFF) << 8 //
			| (byteBuffer.get() & 0xFF) << 16 //
			| (long)(byteBuffer.get() & 0xFF) << 24 //
			| (long)(byteBuffer.get() & 0xFF) << 32 //
			| (long)(byteBuffer.get() & 0xFF) << 40 //
			| (long)(byteBuffer.get() & 0xFF) << 48 //
			| (long)byteBuffer.get() << 56);
	}

	// boolean:

	public boolean readBoolean () throws KryoException {
		if (position == limit) require(1);
		position++;
		return byteBuffer.get() == 1 ? true : false;
	}

	// short:

	public short readShort () throws KryoException {
		require(2);
		position += 2;
		return (short)((byteBuffer.get() & 0xFF) | ((byteBuffer.get() & 0xFF) << 8));
	}

	public int readShortUnsigned () throws KryoException {
		require(2);
		position += 2;
		return (byteBuffer.get() & 0xFF) | ((byteBuffer.get() & 0xFF) << 8);
	}

	// char:

	public char readChar () throws KryoException {
		require(2);
		position += 2;
		return (char)((byteBuffer.get() & 0xFF) | ((byteBuffer.get() & 0xFF) << 8));
	}

	// String:

	public String readString () {
		if (!readVarIntFlag()) return readAsciiString(); // ASCII.
		// Null, empty, or UTF8.
		int charCount = readVarIntFlag(true);
		switch (charCount) {
		case 0:
			return null;
		case 1:
			return "";
		}
		charCount--;
		readUtf8Chars(charCount);
		return new String(chars, 0, charCount);
	}

	public StringBuilder readStringBuilder () {
		if (!readVarIntFlag()) return new StringBuilder(readAsciiString()); // ASCII.
		// Null, empty, or UTF8.
		int charCount = readVarIntFlag(true);
		switch (charCount) {
		case 0:
			return null;
		case 1:
			return new StringBuilder("");
		}
		charCount--;
		readUtf8Chars(charCount);
		StringBuilder builder = new StringBuilder(charCount);
		builder.append(chars, 0, charCount);
		return builder;
	}

	private void readUtf8Chars (int charCount) {
		if (chars.length < charCount) chars = new char[charCount];
		char[] chars = this.chars;
		// Try to read 7 bit ASCII chars.
		ByteBuffer byteBuffer = this.byteBuffer;
		int charIndex = 0;
		int count = Math.min(require(1), charCount);
		while (charIndex < count) {
			int b = byteBuffer.get();
			if (b < 0) break;
			chars[charIndex++] = (char)b;
		}
		position += charIndex;
		// If buffer didn't hold all chars or any were not ASCII, use slow path for remainder.
		if (charIndex < charCount) {
			setBufferPosition(byteBuffer, position);
			readUtf8Chars_slow(charCount, charIndex);
		}
	}

	private void readUtf8Chars_slow (int charCount, int charIndex) {
		ByteBuffer byteBuffer = this.byteBuffer;
		char[] chars = this.chars;
		while (charIndex < charCount) {
			if (position == limit) require(1);
			position++;
			int b = byteBuffer.get() & 0xFF;
			switch (b >> 4) {
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
			case 7:
				chars[charIndex] = (char)b;
				break;
			case 12:
			case 13:
				if (position == limit) require(1);
				position++;
				chars[charIndex] = (char)((b & 0x1F) << 6 | byteBuffer.get() & 0x3F);
				break;
			case 14:
				require(2);
				position += 2;
				int b2 = byteBuffer.get();
				int b3 = byteBuffer.get();
				chars[charIndex] = (char)((b & 0x0F) << 12 | (b2 & 0x3F) << 6 | b3 & 0x3F);
				break;
			}
			charIndex++;
		}
	}

	private String readAsciiString () {
		char[] chars = this.chars;
		ByteBuffer byteBuffer = this.byteBuffer;
		int charCount = 0;
		for (int n = Math.min(chars.length, limit - position); charCount < n; charCount++) {
			int b = byteBuffer.get();
			if ((b & 0x80) == 0x80) {
				position = getBufferPosition(byteBuffer);
				chars[charCount] = (char)(b & 0x7F);
				return new String(chars, 0, charCount + 1);
			}
			chars[charCount] = (char)b;
		}
		position = getBufferPosition(byteBuffer);
		return readAscii_slow(charCount);
	}

	private String readAscii_slow (int charCount) {
		char[] chars = this.chars;
		ByteBuffer byteBuffer = this.byteBuffer;
		while (true) {
			if (position == limit) require(1);
			position++;
			int b = byteBuffer.get();
			if (charCount == chars.length) {
				char[] newChars = new char[charCount * 2];
				System.arraycopy(chars, 0, newChars, 0, charCount);
				chars = newChars;
				this.chars = newChars;
			}
			if ((b & 0x80) == 0x80) {
				chars[charCount] = (char)(b & 0x7F);
				return new String(chars, 0, charCount + 1);
			}
			chars[charCount++] = (char)b;
		}
	}

	// Primitive arrays:

	public int[] readInts (int length) throws KryoException {
		int[] array = new int[length];
		if (optional(length << 2) == length << 2) {
			ByteBuffer byteBuffer = this.byteBuffer;
			for (int i = 0; i < length; i++) {
				array[i] = byteBuffer.get() & 0xFF //
					| (byteBuffer.get() & 0xFF) << 8 //
					| (byteBuffer.get() & 0xFF) << 16 //
					| (byteBuffer.get() & 0xFF) << 24;
			}
			position = getBufferPosition(byteBuffer);
		} else {
			for (int i = 0; i < length; i++)
				array[i] = readInt();
		}
		return array;
	}

	public long[] readLongs (int length) throws KryoException {
		long[] array = new long[length];
		if (optional(length << 3) == length << 3) {
			ByteBuffer byteBuffer = this.byteBuffer;
			for (int i = 0; i < length; i++) {
				array[i] = byteBuffer.get() & 0xFF//
					| (byteBuffer.get() & 0xFF) << 8 //
					| (byteBuffer.get() & 0xFF) << 16 //
					| (long)(byteBuffer.get() & 0xFF) << 24 //
					| (long)(byteBuffer.get() & 0xFF) << 32 //
					| (long)(byteBuffer.get() & 0xFF) << 40 //
					| (long)(byteBuffer.get() & 0xFF) << 48 //
					| (long)byteBuffer.get() << 56;
			}
			position = getBufferPosition(byteBuffer);
		} else {
			for (int i = 0; i < length; i++)
				array[i] = readLong();
		}
		return array;
	}

	public float[] readFloats (int length) throws KryoException {
		float[] array = new float[length];
		if (optional(length << 2) == length << 2) {
			ByteBuffer byteBuffer = this.byteBuffer;
			for (int i = 0; i < length; i++) {
				array[i] = Float.intBitsToFloat(byteBuffer.get() & 0xFF //
					| (byteBuffer.get() & 0xFF) << 8 //
					| (byteBuffer.get() & 0xFF) << 16 //
					| (byteBuffer.get() & 0xFF) << 24);
			}
			position = getBufferPosition(byteBuffer);
		} else {
			for (int i = 0; i < length; i++)
				array[i] = readFloat();
		}
		return array;
	}

	public double[] readDoubles (int length) throws KryoException {
		double[] array = new double[length];
		if (optional(length << 3) == length << 3) {
			ByteBuffer byteBuffer = this.byteBuffer;
			for (int i = 0; i < length; i++) {
				array[i] = Double.longBitsToDouble(byteBuffer.get() & 0xFF //
					| (byteBuffer.get() & 0xFF) << 8 //
					| (byteBuffer.get() & 0xFF) << 16 //
					| (long)(byteBuffer.get() & 0xFF) << 24 //
					| (long)(byteBuffer.get() & 0xFF) << 32 //
					| (long)(byteBuffer.get() & 0xFF) << 40 //
					| (long)(byteBuffer.get() & 0xFF) << 48 //
					| (long)byteBuffer.get() << 56);
			}
			position = getBufferPosition(byteBuffer);
		} else {
			for (int i = 0; i < length; i++)
				array[i] = readDouble();
		}
		return array;
	}

	public short[] readShorts (int length) throws KryoException {
		short[] array = new short[length];
		if (optional(length << 1) == length << 1) {
			ByteBuffer byteBuffer = this.byteBuffer;
			for (int i = 0; i < length; i++)
				array[i] = (short)((byteBuffer.get() & 0xFF) | ((byteBuffer.get() & 0xFF) << 8));
			position = getBufferPosition(byteBuffer);
		} else {
			for (int i = 0; i < length; i++)
				array[i] = readShort();
		}
		return array;
	}

	public char[] readChars (int length) throws KryoException {
		char[] array = new char[length];
		if (optional(length << 1) == length << 1) {
			ByteBuffer byteBuffer = this.byteBuffer;
			for (int i = 0; i < length; i++)
				array[i] = (char)((byteBuffer.get() & 0xFF) | ((byteBuffer.get() & 0xFF) << 8));
			position = getBufferPosition(byteBuffer);
		} else {
			for (int i = 0; i < length; i++)
				array[i] = readChar();
		}
		return array;
	}

	public boolean[] readBooleans (int length) throws KryoException {
		boolean[] array = new boolean[length];
		if (optional(length) == length) {
			ByteBuffer byteBuffer = this.byteBuffer;
			for (int i = 0; i < length; i++)
				array[i] = byteBuffer.get() != 0;
			position = getBufferPosition(byteBuffer);
		} else {
			for (int i = 0; i < length; i++)
				array[i] = readBoolean();
		}
		return array;
	}
}

redpajama_set_name: RedPajamaGithub


text:
Troubleshooting
===============

Mysterious Crash in APT
-----------------------

For the following exception

::

       [cookcc] An exception has occurred in apt (1.6.0_22). Please file a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport)  after checking the Bug Parade for duplicates. Include your program and the following diagnostic in your report.  Thank you.
       [cookcc] java.lang.ClassCastException: com.sun.tools.javac.tree.JCTree$JCErroneous cannot be cast to com.sun.tools.javac.tree.JCTree$JCAnnotation
       [cookcc]     at com.sun.tools.javac.comp.Annotate.enterAttributeValue(Annotate.java:205)
       [cookcc]     at com.sun.tools.javac.comp.Annotate.enterAttributeValue(Annotate.java:219)
       [cookcc]     at com.sun.tools.javac.comp.Annotate.enterAnnotation(Annotate.java:167)
       [cookcc]     at com.sun.tools.javac.comp.MemberEnter.enterAnnotations(MemberEnter.java:743)
       [cookcc]     at com.sun.tools.javac.comp.MemberEnter.access$300(MemberEnter.java:42)
       [cookcc]     at com.sun.tools.javac.comp.MemberEnter$5.enterAnnotation(MemberEnter.java:711)
       [cookcc]     at com.sun.tools.javac.comp.Annotate.flush(Annotate.java:95)
       [cookcc]     at com.sun.tools.javac.comp.Annotate.enterDone(Annotate.java:87)
       [cookcc]     at com.sun.tools.javac.comp.Enter.complete(Enter.java:485)
       [cookcc]     at com.sun.tools.javac.comp.Enter.main(Enter.java:442)
       [cookcc]     at com.sun.tools.apt.main.JavaCompiler.compile(JavaCompiler.java:250)
       [cookcc]     at com.sun.tools.apt.main.Main.compile(Main.java:1102)
       [cookcc]     at com.sun.tools.apt.main.Main.compile(Main.java:964)
       [cookcc]     at com.sun.tools.apt.Main.processing(Main.java:95)
       [cookcc]     at com.sun.tools.apt.Main.process(Main.java:43)
       [cookcc]     at com.sun.tools.apt.Main.main(Main.java:34)

The cause of the issue is likely due to an extra comma after the last
element in the annotation array.

.. code:: java

        @Shortcuts ( shortcuts = {
            @Shortcut (name="arg", pattern="[^=;, \\t\\r\\n\\f'\"]"),
            @Shortcut (name="ws", pattern="[ \\t\\r\\n\\f]"),
        })

Eclipse Java Compiler (ECJ) does not report the extra comma in
annotation arrays as a syntax error. Sun's APT does not report the
correct error message. So it gets a bit confusing. Once removing this
extra comma, the problem would go away.

If the problem still persists, check your class path passed to APT. The
incorrect PATH separator can lead to the similar back trace as well.


text:
'use strict';

var gonzales = require('gonzales-pe-sl');
var matter = require('gray-matter');

module.exports = function (input, syntax, filename) {
  var tree;
  var result = matter(input, {});
  var text = result.content;

  if (result.matter) {
    var emptyLines = new Array(result.matter.split('\n').length + 2).join('\n');
    text = emptyLines + result.content;
  }

  try {
    tree = gonzales.parse(text, {
      'syntax': syntax
    });
  }
  catch (e) {
    throw {
      message: e.message,
      file: filename,
      line: e.line
    };
  }

  if (typeof tree === 'undefined') {
    throw {
      message: 'Undefined tree',
      file: filename,
      text: text.toString(),
      tree: tree.toString()
    };
  }

  return tree;
};


text:
package org.ektorp;

/**
 * Interface for retrieving data about an indexer task
 *
 * @author ed wagstaff
 */
public interface IndexerTask extends ActiveTask {

    /**
     * @return the database which the task is running against
     */
    String getDatabaseName();

    /**
     * @return the ID of the design document where the index is defined
     */
    String getDesignDocumentId();

    /**
     * @return the number of processed changes
     */
    long getCompletedChanges();

    /**
     * @return the total number of changes to process
     */
    long getTotalChanges();
}


text:
package advancedhud.client;

import advancedhud.AdvancedHUD;
import advancedhud.api.HUDRegistry;
import advancedhud.api.HudItem;
import advancedhud.api.RenderAssist;
import com.mojang.authlib.GameProfile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.client.network.NetworkPlayerInfo;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.scoreboard.Score;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraft.scoreboard.ScorePlayerTeam;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.MathHelper;
import net.minecraft.util.StringUtils;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.client.GuiIngameForge;
import net.minecraftforge.fml.common.FMLCommonHandler;
import org.lwjgl.opengl.GL11;

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

public class GuiAdvancedHUD extends GuiIngameForge {

    public static float partialTicks;

    private ScaledResolution res = null;

    public GuiAdvancedHUD(Minecraft mc) {
        super(mc);
    }

    @Override
    protected void func_180479_a(final ScaledResolution res, final float partialTicks) {
        mc.mcProfiler.startSection("Advanced Hud");

        GuiAdvancedHUD.partialTicks = partialTicks;

        HUDRegistry.checkForResize();

        mc.entityRenderer.setupOverlayRendering();
        GL11.glEnable(3042);
        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
        GL11.glBlendFunc(770, 771);

        mc.mcProfiler.startSection("modules");
        for (HudItem huditem : HUDRegistry.getHudItemList()) {
            mc.mcProfiler.startSection(huditem.getName());
            if (mc.playerController.isInCreativeMode() && !huditem.isRenderedInCreative()) {
                mc.mcProfiler.endSection();
                continue;
            }
            if (mc.thePlayer.ridingEntity instanceof EntityLivingBase) {
                if (huditem.shouldDrawOnMount()) {
                    huditem.fixBounds();
                    huditem.render(partialTicks);
                }
            } else {
                if (huditem.shouldDrawAsPlayer()) {
                    huditem.fixBounds();
                    huditem.render(partialTicks);
                }
            }
            mc.mcProfiler.endSection();
        }
        mc.mcProfiler.endSection();

        renderHUDText(HUDRegistry.screenWidth, HUDRegistry.screenHeight);

        int width = HUDRegistry.screenWidth;
        int height = HUDRegistry.screenHeight;

        GL11.glEnable(GL11.GL_BLEND);
        GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
        GL11.glDisable(GL11.GL_ALPHA_TEST);

        this.renderChat(width, height);

        this.renderPlayerList(width, height);

        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
        GL11.glDisable(GL11.GL_LIGHTING);
        GL11.glEnable(GL11.GL_ALPHA_TEST);

        mc.mcProfiler.endSection();
    }

    @Override
    protected void renderHUDText(int width, int height) {
        mc.mcProfiler.startSection("forgeHudText");
        OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0);
        ArrayList<String> left = new ArrayList<String>();
        ArrayList<String> right = new ArrayList<String>();

        if (mc.isDemo()) {
            long time = mc.theWorld.getTotalWorldTime();
            if (time >= 120500L) {
                right.add(I18n.format("demo.demoExpired"));
            } else {
                right.add(I18n.format("demo.remainingTime", StringUtils.ticksToElapsedTime((int) (120500L - time))));
            }
        }

        if (mc.gameSettings.showDebugInfo) {
            GL11.glPushMatrix();
            left.add("Minecraft " + AdvancedHUD.MC_VERSION + " (" + mc.debug + ")");
            left.add(mc.renderGlobal.getDebugInfoRenders());
            left.add(mc.theWorld.getDebugLoadedEntities());
            left.add(mc.renderGlobal.getDebugInfoEntities());
            left.add(mc.theWorld.getProviderName());
            left.add(null); // Spacer

            long max = Runtime.getRuntime().maxMemory();
            long total = Runtime.getRuntime().totalMemory();
            long free = Runtime.getRuntime().freeMemory();
            long used = total - free;

            right.add("Used memory: " + used * 100L / max + "% (" + used / 1024L / 1024L + "MB) of " + max / 1024L / 1024L + "MB");
            right.add("Allocated memory: " + total * 100L / max + "% (" + total / 1024L / 1024L + "MB)");

            int x = MathHelper.floor_double(mc.thePlayer.posX);
            int y = MathHelper.floor_double(mc.thePlayer.posY);
            int z = MathHelper.floor_double(mc.thePlayer.posZ);
            float yaw = mc.thePlayer.rotationYaw;
            int heading = MathHelper.floor_double(mc.thePlayer.rotationYaw * 4.0F / 360.0F + 0.5D) & 3;

            left.add(String.format("x: %.5f (%d) // c: %d (%d)", mc.thePlayer.posX, x, x >> 4, x & 15));
            left.add(String.format("y: %.3f (feet pos, %.3f eyes pos)", mc.thePlayer.posY, mc.thePlayer.getEyeHeight
              ()));
            left.add(String.format("z: %.5f (%d) // c: %d (%d)", mc.thePlayer.posZ, z, z >> 4, z & 15));
            left.add(String.format("f: %d (%s) / %f", heading, EnumFacing.values()[heading + 2], MathHelper
              .wrapAngleTo180_float(yaw)));

            final BlockPos pos = new BlockPos(x, y, z);
          if (mc.theWorld != null && mc.theWorld.chunkExists(x, z)) {
                final Chunk chunk = mc.theWorld.getChunkFromBlockCoords(pos);
                left.add(String.format("lc: %d b: %s bl: %d sl: %d rl: %d", chunk.getTopFilledSegment() + 15,
                  chunk.getBiome(pos, mc.theWorld.getWorldChunkManager()).biomeName, chunk.getLightFor(EnumSkyBlock
                    .BLOCK, new BlockPos(x & 15, y, z & 15)), chunk.getLightFor(EnumSkyBlock.SKY, new BlockPos(x &
                    15, y, z & 15)), chunk.getLightFor(EnumSkyBlock.BLOCK, new BlockPos(x & 15, y, z & 15))));
            } else {
                left.add(null);
            }

            left.add(String.format("ws: %.3f, fs: %.3f, g: %b, fl: %d", mc.thePlayer.capabilities.getWalkSpeed(), mc
              .thePlayer.capabilities.getFlySpeed(), mc.thePlayer.onGround, mc.theWorld.getActualHeight()));
            if (mc.entityRenderer != null && mc.entityRenderer.isShaderActive()) {
                left.add(String.format("shader: %s", mc.entityRenderer.getShaderGroup().getShaderGroupName()));
            }

            right.add(null);
            for (String brand : FMLCommonHandler.instance().getBrandings(false)) {
                right.add(brand);
            }
            GL11.glPopMatrix();
        }

        for (int x = 0; x < left.size(); x++) {
            String msg = left.get(x);
            if (msg == null) {
                continue;
            }
            mc.fontRendererObj.drawString(msg, 2, 2 + x * 10, 0xFFFFFF);
        }

        for (int x = 0; x < right.size(); x++) {
            String msg = right.get(x);
            if (msg == null) {
                continue;
            }
            int w = mc.fontRendererObj.getStringWidth(msg);
            mc.fontRendererObj.drawString(msg, width - w - 10, 2 + x * 10, 0xFFFFFF);
        }

        mc.mcProfiler.endSection();
    }

    @Override
    protected void renderPlayerList(int width, int height) {
        mc.mcProfiler.startSection("playerList");
        ScoreObjective scoreobjective = mc.theWorld.getScoreboard().getObjectiveInDisplaySlot(0);
        NetHandlerPlayClient handler = mc.thePlayer.sendQueue;

        if (mc.gameSettings.keyBindPlayerList.isPressed() && (!mc.isIntegratedServerRunning() || handler.func_175106_d() .size() > 1 || scoreobjective != null)) {
            List<?> players = (List<?>) handler.func_175106_d();
            int maxPlayers = handler.currentServerMaxPlayers;
            int rows = maxPlayers;
            int columns = 1;

            for (columns = 1; rows > 20; rows = (maxPlayers + columns - 1) / columns) {
                columns++;
            }

            int columnWidth = 300 / columns;

            if (columnWidth > 150) {
                columnWidth = 150;
            }

            int left = (width - columns * columnWidth) / 2;
            byte border = 10;
            drawRect(left - 1, border - 1, left + columnWidth * columns, border + 9 * rows, Integer.MIN_VALUE);

            for (int i = 0; i < maxPlayers; i++) {
                int xPos = left + i % columns * columnWidth;
                int yPos = border + i / columns * 9;
                drawRect(xPos, yPos, xPos + columnWidth - 1, yPos + 8, 553648127);
                GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
                GL11.glEnable(GL11.GL_ALPHA_TEST);

                if (i < players.size()) {
                    NetworkPlayerInfo player = (NetworkPlayerInfo) players.get(i);
                    final GameProfile gameProfile = player.func_178845_a();
                    ScorePlayerTeam team = mc.theWorld.getScoreboard().getPlayersTeam(gameProfile.getName());
                    String displayName = ScorePlayerTeam.formatPlayerName(team, gameProfile.getName());
                    mc.fontRendererObj.drawString(displayName, xPos, yPos, 16777215);

                    if (scoreobjective != null) {
                        int endX = xPos + mc.fontRendererObj.getStringWidth(displayName) + 5;
                        int maxX = xPos + columnWidth - 12 - 5;

                        if (maxX - endX > 5) {
                            Score score = scoreobjective.getScoreboard().getValueFromObjective(gameProfile.getName(),
                              scoreobjective);
                            String scoreDisplay = EnumChatFormatting.YELLOW + "" + score.getScorePoints();
                            mc.fontRendererObj.drawString(scoreDisplay, maxX - mc.fontRendererObj.getStringWidth
                              (scoreDisplay), yPos, 16777215);
                        }
                    }

                    GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);

                    RenderAssist.bindTexture(Gui.icons);
                    int pingIndex = 4;
                    int ping = player.getResponseTime();
                    if (ping < 0) {
                        pingIndex = 5;
                    } else if (ping < 150) {
                        pingIndex = 0;
                    } else if (ping < 300) {
                        pingIndex = 1;
                    } else if (ping < 600) {
                        pingIndex = 2;
                    } else if (ping < 1000) {
                        pingIndex = 3;
                    }

                    zLevel += 100.0F;
                    drawTexturedModalRect(xPos + columnWidth - 12, yPos, 0, 176 + pingIndex * 8, 10, 8);
                    zLevel -= 100.0F;
                }
            }
        }
        mc.mcProfiler.endSection();
    }

    @Override
    protected void renderChat(int width, int height) {
        mc.mcProfiler.startSection("chat");

        GL11.glPushMatrix();
        GL11.glTranslatef(0.0F, mc.displayHeight / 2 - 40F, 0.0F);
        persistantChatGUI.drawChat(updateCounter);
        GL11.glPopMatrix();

        mc.mcProfiler.endSection();
    }

    @Override
    public ScaledResolution getResolution() {
        return res;
    }

    @Override
    public void updateTick() {
        mc.mcProfiler.startSection("Advanced HUD - UpdateTick");

        if (mc.theWorld != null) {
            for (HudItem huditem : HUDRegistry.getHudItemList()) {
                mc.mcProfiler.startSection(huditem.getName());
                if (mc.playerController.isInCreativeMode() && !huditem.isRenderedInCreative()) {
                    mc.mcProfiler.endSection();
                    continue;
                }
                if (huditem.needsTick()) {
                    huditem.tick();
                }
                mc.mcProfiler.endSection();
            }
        }

        updateCounter++;
        HUDRegistry.updateCounter = updateCounter;

        mc.mcProfiler.endSection();
    }
}


text:
from __future__ import absolute_import, division, print_function, \
    with_statement

import os
import sys
import hashlib
import logging

from shadowsocks import common
from shadowsocks.crypto import rc4_md5, openssl, sodium, table

method_supported = {}
method_supported.update(rc4_md5.ciphers)
method_supported.update(openssl.ciphers)
method_supported.update(sodium.ciphers)
method_supported.update(table.ciphers)

def random_string(length):
    try:
        return os.urandom(length)
    except NotImplementedError as e:
        return openssl.rand_bytes(length)

cached_keys = {}

def try_cipher(key, method=None):
    Encryptor(key, method)

def EVP_BytesToKey(password, key_len, iv_len):
    # equivalent to OpenSSL's EVP_BytesToKey() with count 1
    # so that we make the same key and iv as nodejs version
    if hasattr(password, 'encode'):
        password = password.encode('utf-8')
    cached_key = '%s-%d-%d' % (password, key_len, iv_len)
    r = cached_keys.get(cached_key, None)
    if r:
        return r
    m = []
    i = 0
    while len(b''.join(m)) < (key_len + iv_len):
        md5 = hashlib.md5()
        data = password
        if i > 0:
            data = m[i - 1] + password
        md5.update(data)
        m.append(md5.digest())
        i += 1
    ms = b''.join(m)
    key = ms[:key_len]
    iv = ms[key_len:key_len + iv_len]
    cached_keys[cached_key] = (key, iv)
    return key, iv

class Encryptor(object):

    def __init__(self, key, method, iv=None):
        self.key = key
        self.method = method
        self.iv = None
        self.iv_sent = False
        self.cipher_iv = b''
        self.iv_buf = b''
        self.cipher_key = b''
        self.decipher = None
        method = method.lower()
        self._method_info = self.get_method_info(method)
        if self._method_info:
            if iv is None or len(iv) != self._method_info[1]:
                self.cipher = self.get_cipher(
                    key, method, 1, random_string(
                        self._method_info[1]))
            else:
                self.cipher = self.get_cipher(key, method, 1, iv)
        else:
            logging.error('method %s not supported' % method)
            sys.exit(1)

    def get_method_info(self, method):
        method = method.lower()
        m = method_supported.get(method)
        return m

    def iv_len(self):
        return len(self.cipher_iv)

    def get_cipher(self, password, method, op, iv):
        password = common.to_bytes(password)
        m = self._method_info
        if m[0] > 0:
            key, iv_ = EVP_BytesToKey(password, m[0], m[1])
        else:
            # key_length == 0 indicates we should use the key directly
            key, iv = password, b''

        iv = iv[:m[1]]
        if op == 1:
            # this iv is for cipher not decipher
            self.cipher_iv = iv[:m[1]]
        self.cipher_key = key
        return m[2](method, key, iv, op)

    def encrypt(self, buf):
        if len(buf) == 0:
            return buf
        if self.iv_sent:
            return self.cipher.update(buf)
        else:
            self.iv_sent = True
            return self.cipher_iv + self.cipher.update(buf)

    def decrypt(self, buf):
        if len(buf) == 0:
            return buf
        if self.decipher is not None:  # optimize
            return self.decipher.update(buf)

        decipher_iv_len = self._method_info[1]
        if len(self.iv_buf) <= decipher_iv_len:
            self.iv_buf += buf
        if len(self.iv_buf) > decipher_iv_len:
            decipher_iv = self.iv_buf[:decipher_iv_len]
            self.decipher = self.get_cipher(self.key, self.method, 0,
                                            iv=decipher_iv)
            buf = self.iv_buf[decipher_iv_len:]
            del self.iv_buf
            return self.decipher.update(buf)
        else:
            return b''

def encrypt_all(password, method, op, data):
    result = []
    method = method.lower()
    (key_len, iv_len, m) = method_supported[method]
    if key_len > 0:
        key, _ = EVP_BytesToKey(password, key_len, iv_len)
    else:
        key = password
    if op:
        iv = random_string(iv_len)
        result.append(iv)
    else:
        iv = data[:iv_len]
        data = data[iv_len:]
    cipher = m(method, key, iv, op)
    result.append(cipher.update(data))
    return b''.join(result)

def encrypt_key(password, method):
    method = method.lower()
    (key_len, iv_len, m) = method_supported[method]
    if key_len > 0:
        key, _ = EVP_BytesToKey(password, key_len, iv_len)
    else:
        key = password
    return key

def encrypt_iv_len(method):
    method = method.lower()
    (key_len, iv_len, m) = method_supported[method]
    return iv_len

def encrypt_new_iv(method):
    method = method.lower()
    (key_len, iv_len, m) = method_supported[method]
    return random_string(iv_len)

def encrypt_all_iv(key, method, op, data, ref_iv):
    result = []
    method = method.lower()
    (key_len, iv_len, m) = method_supported[method]
    if op:
        iv = ref_iv[0]
        result.append(iv)
    else:
        iv = data[:iv_len]
        data = data[iv_len:]
        ref_iv[0] = iv
    cipher = m(method, key, iv, op)
    result.append(cipher.update(data))
    return b''.join(result)

CIPHERS_TO_TEST = [
    'aes-128-cfb',
    'aes-256-cfb',
    'rc4-md5',
    'salsa20',
    'chacha20',
    'table',
]

def test_encryptor():
    from os import urandom
    plain = urandom(10240)
    for method in CIPHERS_TO_TEST:
        logging.warn(method)
        encryptor = Encryptor(b'key', method)
        decryptor = Encryptor(b'key', method)
        cipher = encryptor.encrypt(plain)
        plain2 = decryptor.decrypt(cipher)
        assert plain == plain2

def test_encrypt_all():
    from os import urandom
    plain = urandom(10240)
    for method in CIPHERS_TO_TEST:
        logging.warn(method)
        cipher = encrypt_all(b'key', method, 1, plain)
        plain2 = encrypt_all(b'key', method, 0, cipher)
        assert plain == plain2

if __name__ == '__main__':
    test_encrypt_all()
    test_encryptor()


text:
package com.stubbornjava.webapp.themes;

import java.util.List;

import org.jooq.lambda.Seq;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.stubbornjava.common.HttpClient;
import com.stubbornjava.common.Json;
import com.stubbornjava.common.Retry;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class TemplateMonsterScraper {
    private static final Logger log = LoggerFactory.getLogger(TemplateMonsterScraper.class);
    private static final String affilaiteCode = "stubbornjava";
    private static final String HOST = "https://www.templatemonster.com";
    private static final String POPULAR_THEMES_URL =
        "https://www.templatemonster.com/best-selling-website-templates/";
    private static final OkHttpClient client = HttpClient.globalClient();

    public static List<HtmlCssTheme> popularThemes() {
        HttpUrl url = HttpUrl.parse(POPULAR_THEMES_URL);
        Request request = new Request.Builder().url(url).get().build();
        String html = Retry.retryUntilSuccessfulWithBackoff(
            () -> client.newCall(request).execute()
        );

        Elements elements = Jsoup.parse(html).select("#products .thumbnail");
        List<HtmlCssTheme> themes = Seq.seq(elements).map(TemplateMonsterScraper::themeFromElement).toList();

        return themes;
    }

    private static HtmlCssTheme themeFromElement(Element element) {
        String title = element.select(".small-prev-data h3").text();
        String url = HttpUrl.parse(element.select(".small-prev-data a").attr("href"))
                            .newBuilder()
                            .addQueryParameter("aff", affilaiteCode)
                            .build().toString();
        String imageUrl = element.select(".thumbnail-preview link").attr("href");

        /*
         *  Downloads aren't available on this page and we
         *  currently don't want to scrape all the detail pages
         *  just to get download counts.
         */
        int downloads = 0;
        return new HtmlCssTheme(title, url, imageUrl, downloads);
    }

    public static void main(String[] args) {
        List<HtmlCssTheme> themes = popularThemes();
        log.debug(Json.serializer().toPrettyString(themes));
    }
}


text:
function Update-PSVersionData
{

    <#
.SYNOPSIS
    Updates mapping table used by Get-PSVersion

.DESCRIPTION
    Updates mapping table used by Get-PSVersion, a function to map information from $PSVersionTable in order to retrieve friendly names for Windows PowerShell build numbers

.PARAMETER Uri
    The Uri to download PowerShell version information from.

.EXAMPLE
     Update-PSVersionData

.EXAMPLE
     Update-PSVersionData -Verbose

.EXAMPLE
     Update-PSVersionData -Uri 'https://www.domain.com/PSVersionMappingTable.json'

.INPUTS
    String

.OUTPUTS
    None

.NOTES
    Author:  Jan Egil Ring
    Twitter: @JanEgilRing
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false,
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true)]
        [string]$Uri = 'https://raw.githubusercontent.com/janegilring/PSVersion/master/PSVersionMappingTable.json'
    )

    if ($IsLinux)
    {
        $DestinationFile = Join-Path -Path "$($home)/.config" -ChildPath 'PSVersionMappingTable.json'
    }
    else
    {
        $DestinationFile = Join-Path -Path $env:LOCALAPPDATA\Microsoft\Windows\PowerShell -ChildPath 'PSVersionMappingTable.json'
    }

    try
    {

        Write-Verbose -Message "Trying to download $Uri using Invoke-WebRequest..."

        Invoke-WebRequest -Uri $Uri -OutFile $DestinationFile -ErrorAction Stop

        Write-Verbose -Message "$Uri successfully downloaded to $DestinationFile"

        Write-Verbose -Message "PSVersionData was updated successfully"

    }

    catch
    {

        throw "An error occured while trying to download $Uri to $DestinationFile, exception: $($_.Exception)"

    }

}


text:
require 'spec_helper'

describe Spree::WizardsHelper do

  describe '#params_hash' do
    it 'should be empty' do
      wizard = FactoryGirl.create(:wizard)
      helper.preselected_params(wizard).should == {}
    end

    it 'should have preselected variant sku' do
      wizard = FactoryGirl.create(:wizard)
      wizard.wizard_taxons.each_with_index do |wt, i|
        wt.sku = "abc-#{i}"
      end

      wizard.wizard_taxons.each_with_index do |wt, i|
        helper.preselected_params(wizard)["step#{i+1}"].should == "abc-#{i}"
      end
    end
  end

end


text:
import { describe, it } from "flow-typed-test";
import {
  channel,
  eventChannel,
  multicastChannel,
  stdChannel,
} from "redux-saga";
import { takeMaybe } from "redux-saga/effects";

describe("takeMaybe effect", () => {
  describe("structure", () => {
    const c = takeMaybe("ACTION_NAME");

    it('type must be equal "TAKE"', () => {
      (c.type: "TAKE");
    });

    it('payload property must have "maybe" property', () => {
      (c.payload.maybe: true);
    });

    it("returned object must be read only", () => {
      // $FlowExpectedError: read-only  property
      c.type = "anyType";
      // $FlowExpectedError: read-only  property
      c.payload = {};
    });

    it("returned object must be exact", () => {
      // $FlowExpectedError: exact type
      c.abc = 69;
    });
  });

  describe("takeMaybe()", () => {
    it("must passes when call effect without any arguments", () => {
      const t = takeMaybe();

      (t.payload.pattern: '*');
    });
  });

  describe("takeMaybe(pattern)", () => {
    it("must passes when used properly", () => {
      takeMaybe(action => action.type === "foo");
      takeMaybe([
        action => action.type === "foo",
        action => action.type === "foo",
      ]);

      takeMaybe("ACTION_1");
      takeMaybe(["ACTION_1", "ACTION_2"]);
    });

    it("must raises an error when passed invalid pattern", () => {
      // $FlowExpectedError: PatternFn returns a boolean
      takeMaybe(action => null);

      // $FlowExpectedError: Only string patterns for arrays
      takeMaybe(["FOO", "BAR", 1]);
    });
  });

  describe("takeMaybe(channel)", () => {
    it("must passes when pass Channel", () => {
      const myChannel = channel();

      takeMaybe(myChannel);
    });

    it("must passes when pass EventChannel", () => {
      const myEventChannel = eventChannel(emitter => {
        emitter("test");

        return () => {};
      });

      takeMaybe(myEventChannel);
    });

    it("must passes when pass MulticastChannel", () => {
      takeMaybe(multicastChannel());
      takeMaybe(stdChannel());
    });

    it("must raises an error when passed invalid channel", () => {
      // $FlowExpectedError: Channels must have take prop
      takeMaybe({ close: () => {}, put: msg => {} });
    });
  });
});


text:
* `Train` Ein Zug, der aus mehreren Teilen (RollingStock) besteht. Kann auch ein einzelnes Fahrzeug sein.
  * `name`: `string` - Name des Zuges (Fahrzeugverbund)
  * `speed`: `number` - aktuelle Geschwindigkeit
  * `rollingStockCount`: `number` - Anzahl der Fahrzeuge im Zug
  * `route`: `string` - Route des Zuges
  * `trackType`: `string` - Typ der Spline, auf denen sich der Zug befindet (`"auxiliary"`, `"control"`, `"road"`, `"rail"`, `"tram"`)
  * `onTracks`: `table` Alle Tracks auf denen der Zug steht
  * `values`: `table` of all entries stored in the train

* `RollingStock` enthält alle Fahrzeuge


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

<title>Using as: Z8000 Opcodes</title>

<meta name="description" content="Using as: Z8000 Opcodes">
<meta name="keywords" content="Using as: Z8000 Opcodes">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="AS-Index.html#AS-Index" rel="index" title="AS Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Z8000_002dDependent.html#Z8000_002dDependent" rel="up" title="Z8000-Dependent">
<link href="Vax_002dDependent.html#Vax_002dDependent" rel="next" title="Vax-Dependent">
<link href="Z8000-Directives.html#Z8000-Directives" rel="prev" title="Z8000 Directives">

Previous: Z8000 Directives, Up: Z8000-Dependent   [Contents][Index]

9.47.4 Opcodes

For detailed information on the Z8000 machine instruction set, see
Z8000 Technical Manual.


text:
using Functional.Maybe;

public interface IReadWrite<T>
{
    Maybe<T> Load(string id);
    void Save(Maybe<T> entity);
}


text:
JavaScript without syntax errors

[https://stevekrouse.github.io/rose](https://stevekrouse.github.io/rose/)

## Setup

1. Install node and npm

2. Install all dependencies

```bash
npm install
```

## Developing

When developing Rose's JavaScript, you'll probably want to bundle up the code using webpack.

To bundle the demo:
```bash
webpack --watch rose/src/index.js rose/dist/bundle.js
```

To bundle the woof:
```bash
webpack --watch rose/src/index.js rose/dist/bundle.js
```

## Helpful links

- rose actions: https://docs.google.com/document/d/1744mrs1kYBjWEbGRl5fzZCo4J7UY_vYZAz4GZrqCR7g/edit#
- ast explorer (don't forget to use babloyn6): https://astexplorer.net/
- babel handbook: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#toc-babel-traverse
- all the types: https://github.com/babel/babel/tree/7.0/packages/babel-types
- lodash: https://lodash.com/docs/4.17.4
- vuejs guide: vuejs.org/guide/

## Goals

1. Bootstrap - develop rose in rose
2. Add rose to woofjs.com/create

## To dos

- things are getting fustrating!
  - editor option input are not behaving themselves, sharing state in a fucking weird way that makes me think Vue has bugs
    - it says: initialName: "function1"
    - name: "input1"
    - but even when I watch for name changes, I can't detect any and yet it magically is changed
  - having a little textbox next to some options is nowhere near complex enough for all the options we have to map out
    - I should think about submenus, searchability, and specifics, like forever() or text() for woof
    - also think about buildng the ast in the menu more as opposed to setting stuff to null everywhere and then having to change it...
  - I don't like the game of adding string options and hooking them up with the bus on the backend, super brittle
    - I should think of ways I can describe the transformations possible at each type of node more programmatically like Workflow's graph of coercion

- turn null into number, string

- transformations
  - get thing's member
  - call as a function
  - rename variable just here / refactor everywhere
  - create empty array expression / wrap in array expression
  - change AssignmentExpression to set, increase, descease, multiple, divide
  - change BinaryExpression to -, +, /, % and others...
  - call parameters / array expression
    - swap ordering
    - when adding element (and to left/right), give option to select? number, text, null, undefined, object, array, function

- arrow key navigation
  - right and tab - next sibling to right
  - left and shift-tab - next sibling to left
  - up -- parent
  - down -- first child
  - esc - out of edit mode
  - the selected node doesn't recieve keydown events unless you click on it --> maybe we need to focus on it? --> better way to get divs to get keydowns?

- add first-line block so you can add things at the top of file and block statement
  - or "add line above" / "add line below" option
    - open questin: what about blocks with nothing inside them...?
      - "add line inside?"

- typing
  - plop you into editing it (with empty name and only goes to _input1 if you leave it empty)
  - numbers and identifiers need validators on keydown / paste

- submit bug to vuejs where contenteditable node replaced with contenteditable node takes old value (deleting key, val of obj  or elem of array with delete key)

- add a character like microsoft word's clippy to ask you things about what you want where

- only be able to add return when a parent somewhere is a function

- layout
  - figure out when arrays and objects should layout in a new line
  - when you have console.log(() => 1), the console.log should be at the top of the blo

- colors
  - identifiers should be colored uniquely with scope

- make the size of input box's more durable by responding to the font size

- distinguish between var, const, let, etc

- cut/copy/paste

- look into https://github.com/codecombat/esper.js

- clipboard
  - or: recently touched
  - or: recently copied

- think about ways to standardize view customizing
  - turn all camel case into spaces?
  - sprite.move(10) -> move sprite 10 by 10 steps
  - console.log("hi") -> log "hi" to the console
  - const x = 1 -> create a constant x and set it to 1
  - someArray.forEach(sprite => sprite.move(10)) --> for each sprite in someArray, move that sprite by 10 steps

- when you click around in the text editor, it should select in the blocks selection
  - and vice-versa: selection in the UI should highlight the text in the editor (this will probably be easy-ish)
  - and things should scroll into view on both

- consider making the editor search thingy follow the selection
  - maybe have it appear when you rest on a node for 500 miliseconds and disappear if you don't touch it for 1.5 seconds

- object member computed

- help option in the editor menu to tell you what each node is...?

- validate what you can type into the input boxes when editing number, strings, literals, etc

- string formatting
  - convert string input to multiline input on enter
  - ability to describe/detect string type
    - rgb and "#fefefe" colors should have the colour near them and color picker widgets
    - syntax highlight for code string

- search for block


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>What Is A Cryptographic Hash?</title>
  <meta name="description" content="Cryptographic hashes play a fundamental role in the structure of blockchains, which is what Bitcoin is built on.Essentially, hashes act as digital fingerprin...">

    <link href='//fonts.googleapis.com/css?family=Lato:400,400italic' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" type="text/css" href="/css/tufte.css?v=1.0.1">

  <link rel="canonical" href="http://localhost:4000/2017/06/09/What-Is-A-Cryptographic-Hash">

  <link rel="alternate" type="application/rss+xml" title="homeowmorphism" href="http://localhost:4000/feed.xml" />

		      Cats

		      blog

		      Talks

		      Notes

		      Work

		      About

What Is A Cryptographic Hash?

June 9, 2017

Cryptographic hashes play a fundamental role in the structure of blockchains, which is what Bitcoin is built on.

Essentially, hashes act as digital fingerprints for data. If you have a person and a fingerprint, it is easy to verify that the fingerprint belongs to the person, but a fingerprint alone tells you very little about someone. We will later see that this property is useful for verifying the authenticity of a blockchain.

Let's explore this more formally in this pre-introductory post to Bitcoin.

What's A Hash Function?

The input space X is the set of strings of arbitrary length.

The output space Y is a set of strings fixed length.

The hash function $H$ is efficient to compute.

What Is A Cryptographic Hash Function

Collision Resistance

Hiding

Puzzle Friendliness

Summary

Source

What's A Hash Function?

A hash is a function $H: X \to Y$ which satisfies the three following properties.

The input space X is the set of strings of arbitrary length.

This means that 'helloworld' and 'helloworldhelloworldhelloworld' are both perfectly fine inputs.

The output space Y is a set of strings fixed length.

Regardless of their different lengths, both inputs would map to something of the same length, say $H(\text{'helloworld'})=\text{'l1'}$ and $H('helloworldhelloworldhelloworld') = '3x'$.

Bitcoin uses SHA256 as its hash function. The 256 part stands for the number of bits in its fixed-sized output.

The hash function $H$ is efficient to compute.

Given a string $s$ of length $n$, the complexity to produce $H(s)$ is $O(n)$.

This ease of computation is what give blockchains the property of being easily verifiable to prevent tampering. As we will see later, we can verify if a block is "authentic" in a blockchain by simply computing the hash of a block, which is a cost-effective operation (computation-wise).

What Is A Cryptographic Hash Function

In addition to the three properties of hash functionslisted above, cryptographic hash functions have the following additional properties.

Collision Resistance

A collision happens when a hash function maps two different inputs to the same output.<input type="checkbox" id="inj" class="margin-toggle" />So collisions happen on points where the function isn't injective.

Image source: Bitcoin and Cryptocurrency Technologies.

Since the target space is of a fixed sized (say 256 bits) while the input size is infinite, a hash function cannot be truly injective by the Pigeonhole principle<input type="checkbox" id="Pigeonhole" class="margin-toggle" />The principle that if I throw 4 balls in 3 holes, one hole is going to have more than 1 ball. . A collision resistant function is one where it is computationally infeasible to find a collision. What is infeasible, of course, changes with technological progress.

For a "good" hash function with 256-bit output (which is what Bitcoin uses), it takes $2^{128}$ computations on average to produce a collision. If a computer calculates 10,000 hashes per second, it would take one octillion ($10^{27}$) years to calculate $2^{128}$ hashes in order to produce a collision. Source.

A example of a hash function where it's feasible to find a collision is $H(x) = x \mod 2^{256}$. This function satisfies our fixed length property, but it is easy to find a collision as $H^{-1}(x)$ is simply $x + r \cdot 2^{256}, \quad r \in \mathbb{Z}$, so each number which differs by an integer multiple of $2^{256}$ collide once they are mapped by this hash function.

As of now, no function has been proven to be collision resistant yet<input type="checkbox" id="in fact" class="margin-toggle" />In fact, we have been wrong in the past. The MD5 function was assumed to be collision resistant but after a couple years people have found collisions. What is computationally costly in the past won't be as much in the future.
 , so the cryptographic functions we are using nowadays are functions for which we have yet to find collisions for.

Application: Collision resistance is what gives cryptographic hash the property of acting like fingerprints/identifiers of data. Although we cannot usually deduce from the hash what the data looks like (as we will see below), the data is (until proven otherwise) uniquely identified to its hash function, which is of fixed length. As we will see later, this allows us to identify blocks in the blockchain of Bitcoin by hashing them. It also makes the blocks resistant to tampering since changing the data changes the hash.

Hiding

Intuitively, we want the hash functions to "hide" the
space of practical inputs. Given the hash $y = H(x)$, an attacker should have to generate the hash of every $x'$ in the input space randomly in order to be able to find $x$ which generated $y$. This makes it infeasible to predict which input will result in the right hash.

For example, if the information we are hashing is of the form "Alice pays Bob", "Bob pays Eve", then the input space is easily guessable to be of the form "Person1 pays Person2".

This is a situation we want to avoid, because it makes computing inverse images becomes easy: generate all the hashes of the form $H(\text{"Person1 pays Person2"})$ (assuming strings of these form are finite), and we now have a lookup table of every input-output pair.

To remedy the situation, each time we want to input to our hash function, we must pick random fixed length string (say a 256-bit one) $r$ from a "spread out" (high min-entropy) probability distribution. In Bitcoin, this random string $r$ is called the nonce, for number used once. We then concatenate our string $x$ with $r$. From this concatenation, we have spread our space of practical input which was low entropy (high information) to a space with high entropy (low information).

Given a hash function $H$, we will now write $H(x)$ when we really mean  $H(x)  = H(r || x) = y$ with the $||$ symbol denoting concatenation. Now given $y$, it is infeasible to find $x$ because there are too many combinations $r' ||x'$ to try out. Constructing a lookup table is now unfeasible.

Application: The hiding property allows us to make a commitment scheme. Given a message $x$, we may send a hash of the message $y = H(r || x)$ to announce a commitment to this message without revealing what it is. In other words, given $H(r||x)$ we cannot figure out what $x$ is by the hiding property. Then, once we are ready to reveal the message, we can declare it along with the nonce, meaning we are declaring the tuple $(r,x)$. Then, someone can compute the hash of the nonce and the message in linear time, confirming that this message was indeed the one committed. By the collision-free property, we may not have edited our message because it infeasible to find a tuple $(r',x')$ which hash to the same thing.

Puzzle Friendliness

We have just seen that given an output, we want to make it difficult to find the input.

Puzzle friendliness is the property that given part of the input $k$ which is picked from a high min-entropy distribution and an $n$-bit output $y$, it is infeasible to find $x$ so that $H(k || x)  = y$ in time significantly less than $2^n$.

Basically, even given part of the input and the output, it is very difficult for us to find the rest of the input.

Application: As we will see later, this property is central to Bitcoin mining, which is essentially a race to solve a cryptographic puzzle by essentially trying out solutions uniformly randomly. Bitcoin achieves its distributed consensus by allowing the first person to solve the puzzle to decide the next block. This why having access to more computational power increases your leverage in Bitcoin.

As computational power increases over time, it gets easier and easier to solve Bitcoin's cryptographic puzzle. Moore's law states that computational power increases as $2^T$, where $T$ is time. Puzzle friendliness allows us to keep the required time to solve Bitcoin's cryptographic puzzle roughly constant by increasing the length of $y$, the hash output we want to find in the puzzle. By definition of puzzle friendliness, the difficulty of the puzzle evolves as $2^n$ where $n$ is the length of $y$. This cancels the effect of Moore's law, as well as bigger players entering the Bitcoin ecosystem. In fact, Bitcoin  keeps the average time to mine a new block to 10 minutes.

That's all for now! In a next post, we will see how these properties of the crytographic hash make the hash pointer in a blockchain resistant to tempering, a property that is fundamental to the Bitcoin system. Stay tuned!

Summary

In summary, the hash function has these three properties.

Takes as input a string of arbitrary length,

Returns as output a string of fixed length,

The output of the function is easy to compute relative to the length of the input.

A cryptographic hash has these three additional properties.

Collision resistance: we are very unlikely to find two inputs which give the same output, no matter how hard we try.

Hiding: given a hash, it is infeasible to find its associated input and the optimal way to do so is to try every possibility uniformly randomly.

Puzzle friendliness: given a hash and part of the input that has been chosen in a suitably random way, the optimal way to find the rest of the input is still to try every possibility randomly. The difficulty of that task is exponential in the length of the hash, making it easy to adjust the difficulty of the puzzle by varying the restriction on the desired hash output.

Source

Bitcoin and Cryptocurrency Technologies great theoretical textbook on Bitcoin with free lectures available.

This post was written from the perspective of a mathy beginner.

Special thanks to Jake Hickey for guiding through my cryptocurrency learning and providing valuable feedback for this blog post.

    What Is A Cryptographic Hash? - June 9, 2017 - Hang Lu Su

© 2021   HANG LU SU

This site was created with the Tufte theme  in Jekyll.


text:
void AnimationBrowser::Update(const InputState& input, CoordinateSpace& coords)
{
    if (Debugging().mBrowserUi.animationBrowserOpen)
    {
        RenderAnimationSelector(coords);
    }

    for (auto& anim : mLoadedAnims)
    {
        anim->Update();
    }

    const glm::vec2 mouseWorldPos = coords.ScreenToWorld(glm::vec2(input.mMousePosition.mX, input.mMousePosition.mY));

    // Set the "selected" animation
    if (!mSelected && input.mMouseButtons[0].IsPressed())
    {
        for (auto& anim : mLoadedAnims)
        {
            if (anim->Collision(static_cast<s32>(mouseWorldPos.x), static_cast<s32>(mouseWorldPos.y)))
            {
                mSelected = anim.get();
                mXDelta = (static_cast<s32>(anim->XPos()-mouseWorldPos.x));
                mYDelta = (static_cast<s32>(anim->YPos()-mouseWorldPos.y));
                return;
            }
        }
    }

    // Move the "selected" animation
    if (mSelected && input.mMouseButtons[0].IsDown())
    {
        LOG_INFO("Move selected to " << mouseWorldPos.x+ mXDelta << "," << mouseWorldPos.y+ mYDelta);
        mSelected->SetXPos(static_cast<s32>(mouseWorldPos.x+ mXDelta));
        mSelected->SetYPos(static_cast<s32>(mouseWorldPos.y+ mYDelta));
    }

    if (input.mMouseButtons[0].IsReleased())
    {
        mSelected = nullptr;
    }

    // When the right button is released delete the "selected" animation
    if (input.mMouseButtons[1].IsPressed())
    {
        for (auto it = mLoadedAnims.begin(); it != mLoadedAnims.end(); it++)
        {
            if ((*it)->Collision(static_cast<s32>(mouseWorldPos.x), static_cast<s32>(mouseWorldPos.y)))
            {
                mLoadedAnims.erase(it);
                break;
            }
        }
        mSelected = nullptr;
    }
}

AnimationBrowser::AnimationBrowser(ResourceLocator& resMapper)
    : mResourceLocator(resMapper)
{

}

void AnimationBrowser::Render(AbstractRenderer& renderer)
{
    for (auto& anim : mLoadedAnims)
    {
        if (mDebugResetAnimStates)
        {
            anim->Restart();
        }
        anim->Render(renderer, false, AbstractRenderer::eForegroundLayer0, AbstractRenderer::eWorld);
    }
}

void AnimationBrowser::RenderAnimationSelector(CoordinateSpace& coords)
{
    mDebugResetAnimStates = false;
    if (ImGui::Begin("Animations"))
    {
        if (ImGui::Button("Reset states"))
        {
            mDebugResetAnimStates = true;
        }

        if (ImGui::Button("Clear all"))
        {
            mLoadedAnims.clear();
        }

        static char datasetFilterString[64] = {};
        ImGui::InputText("Data set filter", datasetFilterString, sizeof(datasetFilterString));

        static char nameFilterString[64] = {};
        ImGui::InputText("Name filter", nameFilterString, sizeof(nameFilterString));

        auto animsToLoad = mResourceLocator.DebugUi(datasetFilterString, nameFilterString);
        for (const auto& res : animsToLoad)
        {
            if (std::get<0>(res))
            {
                const char* dataSetName = std::get<0>(res);
                const char* resourceName = std::get<1>(res);
                bool load = std::get<2>(res);
                if (load)
                {
                    auto anim = mResourceLocator.LocateAnimation(resourceName, dataSetName).get();
                    if (anim)
                    {
                        anim->SetXPos(static_cast<s32>(coords.CameraPosition().x));
                        anim->SetYPos(static_cast<s32>(coords.CameraPosition().y));
                        mLoadedAnims.push_back(std::move(anim));
                    }
                }
            }
        }
    }
    ImGui::End();
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ActivityLoaderActivity" >

    <Button
        android:id="@+id/start_bookmarks_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/main_button3" />

</LinearLayout><!-- From: file:/Users/juangui/AndroidStudioProjects/PermissionsLab/app/src/main/res/layout/activity_loader_activity.xml -->


text:
{% extends "base.html" %}

{% block title %}The Blue Alliance - Thanks{% endblock %}

{% block meta_description %}Thanks to all the companies and technologies that make The Blue Alliance possible.{% endblock %}

{% block content %}

Thanks to

VEXpro

For deferring hosting costs

Firebase

For sponsoring the backend service that handles our push notifications

Dotblock VPS Hosting

For the dedicated server that serves our videos

Google AppEngine

For the webapp platform

Komodo Media

For the wonderful social media icons

Bootstrap

For the wonderful HTML CSS JS framework

{% endblock %}


text:
'use strict';

function HopeFuture() {
}
HopeFuture.prototype.play = function (name) {
  this.name = name;
};

HopeFuture.prototype.getName = function () {
  return this.name;
};

HopeFuture.prototype.setName = function (name) {
  this.name = name;
};

HopeFuture.prototype.setBlog = function (blog) {
  this.currentBlog = blog;
};

HopeFuture.prototype.add = function (a, b) {
  return a + b;
};


text:
Branch Simulation
========

#### Animation of a tree growing and branching ####
Using [three.js](http://threejs.org/)


text:
/*global localStorage, jsface*/

Class({
  $static: {
    registry: {},
    instances: {},
    isLocalStorageSupported: (function() {
      try {
        var key = Date.now();
        localStorage[key] = key;
        delete localStorage[key];
        return true;
      }
      catch(e) {
        return false;
      }
    })()
  },

  $const: {
    STORE_PREFIX: 'store:',

    create: function(modelName, data) {
      var modelInfo = this.registry[modelName];

      if (modelInfo) {
        var instance = new modelInfo.Class();
        instance.Class = modelInfo.Class;

        if (data) {
          jsface.extend(instance, data);
        }
        return instance;
      }
      else {
        throw 'store: Model with modelName: ' + modelName + ' not found';
      }
    },

    find: function(modelName, filterFn) {
      var key = this.STORE_PREFIX + modelName;

      if (!this.instances[modelName]) {
        var cookie = wpm.service('cookie').get();
        var value;

        value = this.isLocalStorageSupported ? localStorage[key] : cookie(key);
        this.instances[modelName] = value ? JSON.parse(value): [];
      }

      var result = this.instances[modelName];
      var instance;

      if (result) {
        if (result.length > 1) {
          filterFn = filterFn || function() { return true; };

          return result.filter(result, filterFn).map((r, index) => {
            if (r && typeof(r.save) !== 'function') {
              result[index] = r = this.create(modelName, r);
            }

            return r;
          });
        }
        else {
          instance = result[0];

          if (instance && typeof(instance.save) !== 'function') {
            result[0] = instance = this.create(modelName, instance);
          }
          return instance;
        }
      }
    },

    persist: function(modelName) {
      var value = JSON.stringify(this.instances[modelName]);
      var cookie = wpm.service('cookie').get();
      var key = this.STORE_PREFIX + modelName;

      if (this.isLocalStorageSupported) {
        localStorage[key] = value;
      }
      else {
        cookie(key, value);
      }
    },

    remove: function(modelName) {
      var cookie = wpm.service('cookie').get();
      var types = modelName ? [modelName] : Object.keys(this.registry);
      var len = types.length;
      this.instances = {};

      while (len--) {
        modelName = types[len];

        if (this.isLocalStorageSupported) {
          delete localStorage[this.STORE_PREFIX + modelName];
        }
        else {
          cookie(this.STORE_PREFIX + modelName, null);
        }
      }
    },

    removeAll: function() {
      this.remove();
    }
  },

  main: function(Store) {
    wpm.registerService('store', Store);
  }
});


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
				xmlns:app="http://schemas.android.com/apk/res-auto"
				android:layout_width="match_parent"
				android:layout_height="match_parent">

	<com.github.rongi.rotate_layout.layout.RotateLayout
		android:id="@+id/form1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_centerHorizontal="true"
		android:layout_marginTop="10dip"
		android:background="#550000ff" >

		<include
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			app:layout_angle="0"
			layout="@layout/small_form"
			android:padding="5dip" />
	</com.github.rongi.rotate_layout.layout.RotateLayout>

	<com.github.rongi.rotate_layout.layout.RotateLayout
		android:id="@+id/form2"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_below="@id/form1"
		android:layout_centerHorizontal="true"
		android:layout_marginTop="10dip"
		android:background="#550000ff" >

		<include
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			app:layout_angle="90"
			layout="@layout/small_form"
			android:padding="5dip" />
	</com.github.rongi.rotate_layout.layout.RotateLayout>

	<com.github.rongi.rotate_layout.layout.RotateLayout
		android:id="@+id/form3"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_below="@id/form2"
		android:layout_centerHorizontal="true"
		android:layout_marginTop="10dip"
		android:background="#550000ff" >

		<include
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			app:layout_angle="180"
			layout="@layout/small_form"
			android:padding="5dip" />
	</com.github.rongi.rotate_layout.layout.RotateLayout>

</RelativeLayout>


text:
if [ ZSP_AND_START_OSD = 1  ]; then
#Obtain devices
devices=$(lsblk -l |awk '$6=="disk"{print $1}')
# Zap all devices
# NOTICE: dd zero to device mbr will not affect parted printed table,
#         so use parted to remove the part tables
for d in $devices
do
  for v_partition in $(parted -s /dev/${d} print|awk '/^ / {print $1}')
  do
     parted -s /dev/${d} rm ${v_partition}
  done
  # make sure to wipe out the GPT infomation, let ceph uses gdisk to init
  dd if=/dev/zero of=/dev/${d} bs=512 count=2
  parted -s /dev/${d} mklabel gpt
done
fi

# FIXME: default to install coreos on /dev/sda
default_iface=$(awk '$2 == 00000000 { print $1  }' /proc/net/route | uniq)

printf "Default interface: ${default_iface}\n"
default_iface=$(echo ${default_iface} | awk '{ print \$1 }')

mac_addr=$(ip addr show dev ${default_iface} | awk '$1 ~ /^link\// { print $2 }')
printf "Interface: ${default_iface} MAC address: ${mac_addr}\n"

wget -O ${mac_addr}.yml http://BS_IP/cloud-config/${mac_addr}
sudo coreos-install -d /dev/sda -c ${mac_addr}.yml -b http://BS_IP/static -V current && sudo reboot


text:
/* $XFree86: xc/include/Xos.h,v 3.41tsi Exp $ */

/* This is a collection of things to try and minimize system dependencies
 * in a "significant" number of source files.
 */

#ifndef _XOS_H_
#define _XOS_H_

#include <X11/Xosdefs.h>

/*
 * Get major data types (esp. caddr_t)
 */

#ifdef USG
#ifndef __TYPES__
#ifdef CRAY
#define word word_t
#endif /* CRAY */
#include <sys/types.h>			/* forgot to protect it... */
#define __TYPES__
#endif /* __TYPES__ */
#else /* USG */
#if defined(_POSIX_SOURCE) && defined(MOTOROLA)
#undef _POSIX_SOURCE
#include <sys/types.h>
#define _POSIX_SOURCE
#else
# include <sys/types.h>
#endif
#endif /* USG */

#ifndef sgi
#if defined(__SCO__) || defined(__UNIXWARE__)
#include <stdint.h>
#endif
#endif

#ifdef _SEQUENT_
/*
 * in_systm.h compatibility between SysV and BSD types u_char u_short u_long
 * select.h  for typedef of args to select, fd_set, may use SVR4 later
 */
#include <netinet/in_systm.h>
#include <sys/select.h>
#endif /* _SEQUENT_ */

/*
 * Just about everyone needs the strings routines.  We provide both forms here,
 * index/rindex and strchr/strrchr, so any systems that don't provide them all
 * need to have #defines here.
 *
 * These macros are defined this way, rather than, e.g.:
 *    #defined index(s,c) strchr(s,c)
 * because someone might be using them as function pointers, and such
 * a change would break compatibility for anyone who's relying on them
 * being the way they currently are. So we're stuck with them this way,
 * which can be really inconvenient. :-(
 */

#ifndef X_NOT_STDC_ENV

#include <string.h>
#if defined(__SCO__) || defined(__UNIXWARE__)
#include <strings.h>
#else
#if (defined(sun) && defined(__SVR4))
#include <strings.h>
#endif
#ifdef __STDC__
#ifndef index
#define index(s,c) (strchr((s),(c)))
#endif
#ifndef rindex
#define rindex(s,c) (strrchr((s),(c)))
#endif
#else
#ifndef index
#define index strchr
#endif
#ifndef rindex
#define rindex strrchr
#endif
#endif
#endif

#else

#ifdef SYSV
#if defined(clipper) || defined(__clipper__)
#include <malloc.h>
#endif
#include <string.h>
#define index strchr
#define rindex strrchr
#else
#include <strings.h>
#define strchr index
#define strrchr rindex
#endif

#endif /* X_NOT_STDC_ENV */

/*
 * strerror()
 */
#if (defined(X_NOT_STDC_ENV) || (defined(sun) && !defined(SVR4)) || defined(macII)) && !defined(__GLIBC__)
#ifndef strerror
extern char *sys_errlist[];
extern int sys_nerr;
#define strerror(n) \
    (((n) >= 0 && (n) < sys_nerr) ? sys_errlist[n] : "unknown error")
#endif
#endif

/*
 * Get open(2) constants
 */
#if defined(X_NOT_POSIX)
#include <fcntl.h>
#if defined(USL) || defined(CRAY) || defined(MOTOROLA) || (defined(i386) && (defined(SYSV) || defined(SVR4))) || defined(__sxg__)
#include <unistd.h>
#endif
#ifdef WIN32
#include <X11/Xw32defs.h>
#else
#include <sys/file.h>
#endif
#else /* X_NOT_POSIX */
#if !defined(_POSIX_SOURCE) && defined(macII)
#define _POSIX_SOURCE
#include <fcntl.h>
#include <unistd.h>
#undef _POSIX_SOURCE
#else
#include <fcntl.h>
#include <unistd.h>
#endif
#endif /* X_NOT_POSIX else */

/*
 * Get struct timeval and struct tm
 */

#if defined(SYSV) && !defined(_SEQUENT_)

#ifndef USL
#include <sys/time.h>
#endif
#include <time.h>
#ifdef CRAY
#undef word
#endif /* CRAY */
#if defined(USG) && !defined(CRAY) && !defined(MOTOROLA) && !defined(uniosu) && !defined(__sxg__) && !defined(clipper) && !defined(__clipper__)
struct timeval {
    long tv_sec;
    long tv_usec;
};
#ifndef USL_SHARELIB
struct timezone {
    int tz_minuteswest;
    int tz_dsttime;
};
#endif /* USL_SHARELIB */
#endif /* USG */

#ifdef _SEQUENT_
struct timezone {
    int tz_minuteswest;
    int tz_dsttime;
};
#endif /* _SEQUENT_ */

#else /* not SYSV */

#if defined(_POSIX_SOURCE) && defined(SVR4)
/* need to omit _POSIX_SOURCE in order to get what we want in SVR4 */
#undef _POSIX_SOURCE
#include <sys/time.h>
#define _POSIX_SOURCE
#elif defined(WIN32)
#include <time.h>
#if !defined(_WINSOCKAPI_) && !defined(_WILLWINSOCK_) && !defined(_TIMEVAL_DEFINED) && !defined(_STRUCT_TIMEVAL)
struct timeval {
    long    tv_sec;         /* seconds */
    long    tv_usec;        /* and microseconds */
};
#define _TIMEVAL_DEFINED
#endif
#include <sys/timeb.h>
#define gettimeofday(t) \
{ \
    struct _timeb _gtodtmp; \
    _ftime (&_gtodtmp); \
    (t)->tv_sec = _gtodtmp.time; \
    (t)->tv_usec = _gtodtmp.millitm * 1000; \
}
#elif defined(_SEQUENT_) || defined(Lynx)
#include <time.h>
#elif defined (__QNX__)
typedef unsigned long fd_mask;
/* Make sure we get 256 bit select masks */
#define FD_SETSIZE 256
#include <sys/select.h>
#include <sys/time.h>
#include <time.h>
#else
#include <sys/time.h>
#include <time.h>
#endif /* defined(_POSIX_SOURCE) && defined(SVR4) */

#endif /* SYSV */

/* define X_GETTIMEOFDAY macro, a portable gettimeofday() */
#if defined(_XOPEN_XPG4) || defined(_XOPEN_UNIX) /* _XOPEN_UNIX is XPG4.2 */
#define X_GETTIMEOFDAY(t) gettimeofday(t, (struct timezone*)0)
#else
#if defined(SVR4) || defined(VMS) || defined(WIN32)
#define X_GETTIMEOFDAY(t) gettimeofday(t)
#else
#define X_GETTIMEOFDAY(t) gettimeofday(t, (struct timezone*)0)
#endif
#endif /* XPG4 else */

#ifdef __UNIXOS2__
typedef unsigned long fd_mask;
#include <limits.h>
#define MAX_PATH _POSIX_PATH_MAX
#endif

#ifdef __GNU__
#define PATH_MAX 4096
#define MAXPATHLEN 4096
#define OPEN_MAX 256 /* We define a reasonable limit.  */
#endif

/* use POSIX name for signal */
#if defined(X_NOT_POSIX) && defined(SYSV) && !defined(SIGCHLD) && !defined(ISC)
#define SIGCHLD SIGCLD
#endif

#ifdef ISC
#include <sys/bsdtypes.h>
#include <sys/limits.h>
#define NGROUPS 16
#endif

#if defined(ISC) || defined(__UNIXOS2__) || \
    (defined(__linux__) && !defined(__GLIBC__)) || \
    (defined(__QNX__) && !defined(UNIXCONN))
/*
 *	Some OS's may not have this
 */

#define X_NO_SYS_UN 1

struct sockaddr_un {
	short	sun_family;
	char	sun_path[108];
};
#endif

#endif /* _XOS_H_ */


text:
raytracer: raytrace.cpp
	g++ -o raytrace raytrace.cpp -O2 --std=c++1y -Wall -Wextra && ./raytrace && "C:\Program Files\IrfanView\i_view64.exe" image.ppm

view:
	"C:\Program Files\IrfanView\i_view64.exe" image.ppm