text:
package tests.api.java.nio.charset;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.MalformedInputException;
import java.nio.charset.UnmappableCharacterException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;

import junit.framework.TestCase;

/**
 * API unit test for java.nio.charset.CharsetEncoder
 */
public class CharsetEncoderTest extends TestCase {

	static final int MAX_BYTES = 3;

	static final float AVER_BYTES = 0.5f;

	// charset for mock class
	private static final Charset MOCKCS = new MockCharset("CharsetEncoderTest_mock", new String[0]);

	Charset cs = MOCKCS;

	// default encoder
	CharsetEncoder encoder;

	// default for Charset abstract class
	byte[] defaultReplacement = new byte[] { 63 };

	// specific for Charset implementation subclass
	byte[] specifiedReplacement = new byte[] { 26 };

	static final String unistr = " buffer";// \u8000\u8001\u00a5\u3000\r\n";

	byte[] unibytes = new byte[] { 32, 98, 117, 102, 102, 101, 114 };

	byte[] unibytesWithRep = null;

	byte[] surrogate = new byte[0];

	protected void setUp() throws Exception {
		super.setUp();
		encoder = cs.newEncoder();
		if (null == unibytesWithRep) {
			byte[] replacement = encoder.replacement();
			unibytesWithRep = new byte[replacement.length + unibytes.length];
			System.arraycopy(replacement, 0, unibytesWithRep, 0,
					replacement.length);
			System.arraycopy(unibytes, 0, unibytesWithRep, replacement.length,
					unibytes.length);
		}
	}

	/*
	 * @see TestCase#tearDown()
	 */
	protected void tearDown() throws Exception {
		super.tearDown();
	}

	public void testSpecificDefaultValue() {
		assertTrue(encoder.averageBytesPerChar() == AVER_BYTES);
		assertTrue(encoder.maxBytesPerChar() == MAX_BYTES);
	}

	public void testDefaultValue() {
		assertEquals(CodingErrorAction.REPORT, encoder.malformedInputAction());
		assertEquals(CodingErrorAction.REPORT, encoder
				.unmappableCharacterAction());
		assertSame(encoder, encoder.onMalformedInput(CodingErrorAction.IGNORE));
		assertSame(encoder, encoder
				.onUnmappableCharacter(CodingErrorAction.IGNORE));
		if (encoder instanceof MockCharsetEncoder) {
			assertTrue(Arrays.equals(encoder.replacement(), defaultReplacement));
		} else {
			assertTrue(Arrays.equals(encoder.replacement(),
					specifiedReplacement));
		}

	}

	/*
	 * Class under test for constructor CharsetEncoder(Charset, float, float)
	 */
	public void testCharsetEncoderCharsetfloatfloat() {
		// default value
		encoder = new MockCharsetEncoder(cs, (float) AVER_BYTES, MAX_BYTES);
		assertSame(encoder.charset(), cs);
		assertTrue(encoder.averageBytesPerChar() == AVER_BYTES);
		assertTrue(encoder.maxBytesPerChar() == MAX_BYTES);
		assertEquals(CodingErrorAction.REPORT, encoder.malformedInputAction());
		assertEquals(CodingErrorAction.REPORT, encoder
				.unmappableCharacterAction());
		assertEquals(new String(encoder.replacement()), new String(
				defaultReplacement));
		assertSame(encoder, encoder.onMalformedInput(CodingErrorAction.IGNORE));
		assertSame(encoder, encoder
				.onUnmappableCharacter(CodingErrorAction.IGNORE));

		// normal case
		CharsetEncoder ec = new MockCharsetEncoder(cs, 1, MAX_BYTES);
		assertSame(ec.charset(), cs);
		assertEquals(1.0, ec.averageBytesPerChar(), 0);
		assertTrue(ec.maxBytesPerChar() == MAX_BYTES);

		/*
		 * ------------------------ Exceptional cases -------------------------
		 */
		// NullPointerException: null charset
		try {
			ec = new MockCharsetEncoder(null, 1, MAX_BYTES);
			fail("should throw null pointer exception");
		} catch (NullPointerException e) {
		}

		ec = new MockCharsetEncoder(new MockCharset("mock", new String[0]), 1,
				MAX_BYTES);

                // Commented out since the comment is wrong since MAX_BYTES > 1
		// // OK: average length less than max length
		// ec = new MockCharsetEncoder(cs, MAX_BYTES, 1);
		// assertTrue(ec.averageBytesPerChar() == MAX_BYTES);
		// assertTrue(ec.maxBytesPerChar() == 1);

		// Illegal Argument: zero length
		try {
			ec = new MockCharsetEncoder(cs, 0, MAX_BYTES);
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}
		try {
			ec = new MockCharsetEncoder(cs, 1, 0);
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}

		// Illegal Argument: negative length
		try {
			ec = new MockCharsetEncoder(cs, -1, MAX_BYTES);
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}
		try {
			ec = new MockCharsetEncoder(cs, 1, -1);
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}
	}

	/*
	 * Class under test for constructor CharsetEncoder(Charset, float, float,
	 * byte[])
	 */
	public void testCharsetEncoderCharsetfloatfloatbyteArray() {
		byte[] ba = getLegalByteArray();
		// normal case
		CharsetEncoder ec = new MockCharsetEncoder(cs, 1, MAX_BYTES, ba);
		assertSame(ec.charset(), cs);
		assertEquals(1.0, ec.averageBytesPerChar(), 0.0);
		assertTrue(ec.maxBytesPerChar() == MAX_BYTES);
		assertSame(ba, ec.replacement());

		/*
		 * ------------------------ Exceptional cases -------------------------
		 */
		// NullPointerException: null charset
		try {
			ec = new MockCharsetEncoder(null, 1, MAX_BYTES, ba);
			fail("should throw null pointer exception");
		} catch (NullPointerException e) {
		}

		// Illegal Argument: null byte array
		try {
			ec = new MockCharsetEncoder(cs, 1, MAX_BYTES, null);
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}
		// Illegal Argument: empty byte array
		try {
			ec = new MockCharsetEncoder(cs, 1, MAX_BYTES, new byte[0]);
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}
		// Illegal Argument: byte array is longer than max length
		try {
			ec = new MockCharsetEncoder(cs, 1, MAX_BYTES, new byte[] { 1, 2,
					MAX_BYTES, 4 });
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}

                // Commented out since the comment is wrong since MAX_BYTES > 1
                // This test throws IllegalArgumentException on Harmony and RI
		// // OK: average length less than max length
		// ec = new MockCharsetEncoder(cs, MAX_BYTES, ba.length, ba);
		// assertTrue(ec.averageBytesPerChar() == MAX_BYTES);
		// assertTrue(ec.maxBytesPerChar() == ba.length);

		// Illegal Argument: zero length
		try {
			ec = new MockCharsetEncoder(cs, 0, MAX_BYTES, ba);
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}
		try {
			ec = new MockCharsetEncoder(cs, 1, 0, ba);
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}

		// Illegal Argument: negative length
		try {
			ec = new MockCharsetEncoder(cs, -1, MAX_BYTES, ba);
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}
		try {
			ec = new MockCharsetEncoder(cs, 1, -1, ba);
			fail("should throw IllegalArgumentException");
		} catch (IllegalArgumentException e) {
		}
	}

	/*
	 * Class under test for boolean canEncode(char)
	 */
	public void testCanEncodechar() throws CharacterCodingException {
		// for non-mapped char
		assertTrue(encoder.canEncode('\uc2c0'));
		// surrogate char for unicode
		// 1st byte: d800-dbff
		// 2nd byte: dc00-dfff
		assertTrue(encoder.canEncode('\ud800'));
		// valid surrogate pair
		assertTrue(encoder.canEncode('\udc00'));
	}

	/*-----------------------------------------
	 * Class under test for illegal state case
	 * methods which can change internal states are two encode, flush, two canEncode, reset
	 * -----------------------------------------
	 */

	// Normal case: just after reset, and it also means reset can be done
	// anywhere
	public void testResetIllegalState() throws CharacterCodingException {
		assertSame(encoder, encoder.reset());
		encoder.canEncode('\ud901');
		assertSame(encoder, encoder.reset());
		encoder.canEncode("\ud901\udc00");
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("aaa"));
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("aaa"), ByteBuffer.allocate(3), false);
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("aaa"), ByteBuffer.allocate(3), true);
		assertSame(encoder, encoder.reset());
	}

	public void testFlushIllegalState() throws CharacterCodingException {
		CharBuffer in = CharBuffer.wrap("aaa");
		ByteBuffer out = ByteBuffer.allocate(5);

		// Normal case: after encode with endOfInput is true
		assertSame(encoder, encoder.reset());
		encoder.encode(in, out, true);
		out.rewind();
		CoderResult result = encoder.flush(out);

		// Illegal state: flush twice
		try {
			encoder.flush(out);
			fail("should throw IllegalStateException");
		} catch (IllegalStateException e) {
		}

		// Illegal state: flush after encode with endOfInput is false
		assertSame(encoder, encoder.reset());
		encoder.encode(in, out, false);
		try {
			encoder.flush(out);
			fail("should throw IllegalStateException");
		} catch (IllegalStateException e) {
		}
	}

	// test illegal states for encode facade
	public void testEncodeFacadeIllegalState() throws CharacterCodingException {
		// encode facade can be execute in anywhere
		CharBuffer in = CharBuffer.wrap("aaa");
		// Normal case: just created
		encoder.encode(in);
		in.rewind();

		// Normal case: just after encode facade
		encoder.encode(in);
		in.rewind();

		// Normal case: just after canEncode
		assertSame(encoder, encoder.reset());
		encoder.canEncode("\ud902\udc00");
		encoder.encode(in);
		in.rewind();
		assertSame(encoder, encoder.reset());
		encoder.canEncode('\ud902');
		encoder.encode(in);
		in.rewind();

		// Normal case: just after encode with that endOfInput is true
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
				ByteBuffer.allocate(30), true);
		encoder.encode(in);
		in.rewind();

		// Normal case:just after encode with that endOfInput is false
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
				ByteBuffer.allocate(30), false);
		encoder.encode(in);
		in.rewind();

		// Normal case: just after flush
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
				ByteBuffer.allocate(30), true);
		encoder.flush(ByteBuffer.allocate(10));
		encoder.encode(in);
		in.rewind();
	}

	// test illegal states for two encode method with endOfInput is true
	public void testEncodeTrueIllegalState() throws CharacterCodingException {
		CharBuffer in = CharBuffer.wrap("aaa");
		ByteBuffer out = ByteBuffer.allocate(5);
		// Normal case: just created
		encoder.encode(in, out, true);
		in.rewind();
		out.rewind();

		in.rewind();
		out.rewind();

		// Normal case: just after encode with that endOfInput is true
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
				ByteBuffer.allocate(30), true);
		encoder.encode(in, out, true);
		in.rewind();
		out.rewind();

		// Normal case:just after encode with that endOfInput is false
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
				ByteBuffer.allocate(30), false);
		encoder.encode(in, out, true);
		in.rewind();
		out.rewind();

		// Illegal state: just after flush
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
				ByteBuffer.allocate(30), true);
		encoder.flush(ByteBuffer.allocate(10));
		try {
			encoder.encode(in, out, true);
			fail("should illegal state");
		} catch (IllegalStateException e) {
		}

		// Normal case: after canEncode
		assertSame(encoder, encoder.reset());
		encoder.canEncode("\ud906\udc00");
		encoder.encode(in, out, true);
		in.rewind();
		out.rewind();
		assertSame(encoder, encoder.reset());
		encoder.canEncode('\ud905');
		encoder.encode(in, out, true);
	}

	// test illegal states for two encode method with endOfInput is false
	public void testEncodeFalseIllegalState() throws CharacterCodingException {
		CharBuffer in = CharBuffer.wrap("aaa");
		ByteBuffer out = ByteBuffer.allocate(5);
		// Normal case: just created
		encoder.encode(in, out, false);
		in.rewind();
		out.rewind();

		// Illegal state: just after encode facade
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState1"));
		try {
			encoder.encode(in, out, false);
			fail("should illegal state");
		} catch (IllegalStateException e) {
		}

		// Illegal state: just after encode with that endOfInput is true
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
				ByteBuffer.allocate(30), true);
		try {
			encoder.encode(in, out, false);
			fail("should illegal state");
		} catch (IllegalStateException e) {
		}

		// Normal case:just after encode with that endOfInput is false
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
				ByteBuffer.allocate(30), false);
		encoder.encode(in, out, false);
		in.rewind();
		out.rewind();

		// Illegal state: just after flush
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
				ByteBuffer.allocate(30), true);
		encoder.flush(ByteBuffer.allocate(10));
		try {
			encoder.encode(in, out, false);
			fail("should illegal state");
		} catch (IllegalStateException e) {
		}

		// Normal case: after canEncode
		assertSame(encoder, encoder.reset());
		encoder.canEncode("\ud906\udc00");
		encoder.encode(in, out, false);
		in.rewind();
		out.rewind();
		assertSame(encoder, encoder.reset());
		encoder.canEncode('\ud905');
		encoder.encode(in, out, false);
	}

	// test illegal states for two canEncode methods
	public void testCanEncodeIllegalState() throws CharacterCodingException {
		// Normal case: just created
		encoder.canEncode("\ud900\udc00");
		encoder.canEncode('\ud900');

		// Illegal state: just after encode with that endOfInput is true
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
				ByteBuffer.allocate(30), true);
		try {
			encoder.canEncode("\ud903\udc00");
			fail("should throw illegal state exception");
		} catch (IllegalStateException e) {
		}

		// Illegal state:just after encode with that endOfInput is false
		assertSame(encoder, encoder.reset());
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
				ByteBuffer.allocate(30), false);
		try {
			encoder.canEncode("\ud904\udc00");
			fail("should throw illegal state exception");
		} catch (IllegalStateException e) {
		}

		// Normal case: just after flush
		encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
				ByteBuffer.allocate(30), true);
		encoder.flush(ByteBuffer.allocate(10));
		encoder.canEncode("\ud905\udc00");
		encoder.canEncode('\ud906');

		// Normal case: after reset again
		assertSame(encoder, encoder.reset());
		encoder.canEncode("\ud906\udc00");
		encoder.canEncode('\ud905');
	}

	/*
	 * --------------------------------- illegal state test end
	 * ---------------------------------
	 */

	/*
	 * Class under test for boolean canEncode(CharSequence)
	 */
	public void testCanEncodeCharSequence() {
		// for non-mapped char
		assertTrue(encoder.canEncode("\uc2c0"));
		// surrogate char for unicode
		// 1st byte: d800-dbff
		// 2nd byte: dc00-dfff
		assertTrue(encoder.canEncode("\ud800"));
		// valid surrogate pair
		assertTrue(encoder.canEncode("\ud800\udc00"));
		// invalid surrogate pair
		assertTrue(encoder.canEncode("\ud800\udb00"));
	}

	/*
	 * Class under test for Charset charset()
	 */
	public void testCharset() {
		try {
			encoder = new MockCharsetEncoder(Charset.forName("gbk"), 1,
					MAX_BYTES);
			// assertSame(encoder.charset(), Charset.forName("gbk"));
		} catch (UnsupportedCharsetException e) {
			System.err
					.println("Don't support GBK encoding, ignore current test");
		}
	}

	/*
	 * Class under test for ByteBuffer encode(CharBuffer)
	 */
	public void testEncodeCharBuffer() throws CharacterCodingException {
		// Null pointer
		try {
			encoder.encode(null);
			fail("should throw null pointer exception");
		} catch (NullPointerException e) {
		}

		// empty input buffer
		ByteBuffer out = encoder.encode(CharBuffer.wrap(""));
		assertEquals(out.position(), 0);
		assertByteArray(out, new byte[0]);
		// assertByteArray(out, surrogate);

		// normal case
		out = encoder.encode(CharBuffer.wrap(unistr));
		assertEquals(out.position(), 0);
		assertByteArray(out, addSurrogate(unibytes));

        // Regression test for harmony-3378
        Charset cs = Charset.forName("UTF-8");
        CharsetEncoder encoder = cs.newEncoder();
        encoder.onMalformedInput(CodingErrorAction.REPLACE);
        encoder = encoder.replaceWith(new byte[] { (byte) 0xef, (byte) 0xbf,
                (byte) 0xbd, });
        CharBuffer in = CharBuffer.wrap("\ud800");
        out = encoder.encode(in);
        assertNotNull(out);
	}

	private byte[] addSurrogate(byte[] expected) {
		if (surrogate.length > 0) {
			byte[] temp = new byte[surrogate.length + expected.length];
			System.arraycopy(surrogate, 0, temp, 0, surrogate.length);
			System.arraycopy(expected, 0, temp, surrogate.length,
					expected.length);
			expected = temp;
		}
		return expected;
	}

	/**
	 * @return
	 */
	protected byte[] getEmptyByteArray() {
		return new byte[0];
	}

	CharBuffer getMalformedCharBuffer() {
		return CharBuffer.wrap("malform buffer");
	}

	CharBuffer getUnmapCharBuffer() {
		return CharBuffer.wrap("unmap buffer");
	}

	CharBuffer getExceptionCharBuffer() {
		return CharBuffer.wrap("runtime buffer");
	}

	public void testEncodeCharBufferException() throws CharacterCodingException {
		ByteBuffer out;
		CharBuffer in;
		// MalformedException:
		in = getMalformedCharBuffer();
		encoder.onMalformedInput(CodingErrorAction.REPORT);
		encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
		if (in != null) {
			try {
                // regression test for Harmony-1379
				encoder.encode(in);
				fail("should throw MalformedInputException");
			} catch (MalformedInputException e) {
			}

			encoder.reset();
			in.rewind();
			encoder.onMalformedInput(CodingErrorAction.IGNORE);
			out = encoder.encode(in);
			assertByteArray(out, addSurrogate(unibytes));

			encoder.reset();
			in.rewind();
			encoder.onMalformedInput(CodingErrorAction.REPLACE);
			out = encoder.encode(in);
			assertByteArray(out, addSurrogate(unibytesWithRep));
		}

		// Unmapped Exception:
		in = getUnmapCharBuffer();
		encoder.onMalformedInput(CodingErrorAction.REPORT);
		encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
		if (in != null) {
			encoder.reset();
			try {
				encoder.encode(in);
				fail("should throw UnmappableCharacterException");
			} catch (UnmappableCharacterException e) {
			}

			encoder.reset();
			in.rewind();
			encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
			out = encoder.encode(in);
			assertByteArray(out, unibytes);

			encoder.reset();
			in.rewind();
			encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
			out = encoder.encode(in);
			assertByteArray(out, unibytesWithRep);
		}

		// RuntimeException
		try {
			encoder.encode(getExceptionCharBuffer());
			fail("should throw runtime exception");
		} catch (RuntimeException e) {
		}
	}

	/*
	 * utility method, extract given bytebuffer to a string and compare with
	 * give string
	 */
	void assertByteArray(ByteBuffer out, byte[] expected) {
		out = out.duplicate();
		if (out.position() != 0) {
			out.flip();
		}
		byte[] ba = new byte[out.limit() - out.position()];
		out.get(ba);
		// byte[] ba = out.array();
		assertTrue(Arrays.equals(ba, expected));
	}

	/*
	 * Class under test for CoderResult encode(CharBuffer, ByteBuffer, boolean)
	 */
	public void testEncodeCharBufferByteBufferboolean()
			throws CharacterCodingException {
		ByteBuffer out = ByteBuffer.allocate(200);
		CharBuffer in = CharBuffer.wrap(unistr);
		// Null pointer
		try {
			encoder.encode(null, out, true);
			fail("should throw null pointer exception");
		} catch (NullPointerException e) {
		}
		try {
			encoder.encode(in, null, true);
			fail("should throw null pointer exception");
		} catch (NullPointerException e) {
		}

		// normal case, one complete operation
		assertSame(encoder, encoder.reset());
		in.rewind();
		out.rewind();
		assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true));
		assertEquals(out.limit(), 200);
		assertTrue(out.position() > 0);
		assertTrue(out.remaining() > 0);
		assertEquals(out.capacity(), 200);
		assertByteArray(out, addSurrogate(unibytes));
		in.rewind();

		encoder.flush(out);

		// normal case, one complete operation, but call twice, first time set
		// endOfInput to false
		assertSame(encoder, encoder.reset());
		in.rewind();
		out = ByteBuffer.allocate(200);
		assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, false));
		assertEquals(out.limit(), 200);
		assertTrue(out.position() > 0);
		assertTrue(out.remaining() > 0);
		assertEquals(out.capacity(), 200);
		assertByteArray(out, addSurrogate(unibytes));

		in.rewind();
		assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, false));
		in.rewind();
		assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true));
		assertEquals(out.limit(), 200);
		assertTrue(out.position() > 0);
		assertTrue(out.remaining() > 0);
		assertEquals(out.capacity(), 200);

		assertByteArray(out, addSurrogate(duplicateByteArray(unibytes, 3)));

		// overflow
		out = ByteBuffer.allocate(4);
		assertSame(encoder, encoder.reset());
		in.rewind();
		out.rewind();
		assertSame(CoderResult.OVERFLOW, encoder.encode(in, out, true));
		assertEquals(out.limit(), 4);
		assertEquals(out.position(), 4);
		assertEquals(out.remaining(), 0);
		assertEquals(out.capacity(), 4);
		ByteBuffer temp = ByteBuffer.allocate(200);
		out.flip();
		temp.put(out);
		out = temp;
		assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true));
		assertEquals(out.limit(), 200);
		assertTrue(out.position() > 0);
		assertTrue(out.remaining() > 0);
		assertEquals(out.capacity(), 200);
		assertByteArray(out, addSurrogate(unibytes));

		assertSame(encoder, encoder.reset());
		in.rewind();
		out = ByteBuffer.allocate(4);
		assertSame(CoderResult.OVERFLOW, encoder.encode(in, out, false));
		assertEquals(out.limit(), 4);
		assertEquals(out.position(), 4);
		assertEquals(out.remaining(), 0);
		assertEquals(out.capacity(), 4);
		temp = ByteBuffer.allocate(200);
		out.flip();
		temp.put(out);
		out = temp;
		assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, false));
		assertEquals(out.limit(), 200);
		assertTrue(out.position() > 0);
		assertTrue(out.remaining() > 0);
		assertEquals(out.capacity(), 200);
		assertByteArray(out, addSurrogate(unibytes));
	}

	void printByteBuffer(ByteBuffer buffer) {
		System.out.println("print buffer");
		if (buffer.position() != 0) {
			buffer.flip();
		}
		byte[] ba = buffer.array();
		for (int i = 0; i < ba.length; i++) {
			System.out.println(Integer.toHexString(ba[i]));
		}
	}

	public void testEncodeCharBufferByteBufferbooleanExceptionFalse()
			throws CharacterCodingException {
		implTestEncodeCharBufferByteBufferbooleanException(false);
	}

	public void testEncodeCharBufferByteBufferbooleanExceptionTrue()
			throws CharacterCodingException {
		implTestEncodeCharBufferByteBufferbooleanException(true);
	}

	private byte[] duplicateByteArray(byte[] ba, int times) {
		byte[] result = new byte[ba.length * times];
		for (int i = 0; i < times; i++) {
			System.arraycopy(ba, 0, result, i * ba.length, ba.length);
		}
		return result;
	}

	protected void implTestEncodeCharBufferByteBufferbooleanException(
			boolean endOfInput) throws CharacterCodingException {
		ByteBuffer out = ByteBuffer.allocate(100);

		// MalformedException:
		CharBuffer in = getMalformedCharBuffer();
		encoder.onMalformedInput(CodingErrorAction.REPORT);
		encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
		if (in != null) {
			encoder.reset();
			CoderResult r = encoder.encode(in, out, endOfInput);
			assertTrue(r.isMalformed());

			encoder.reset();
			out.clear();
			in.rewind();
			encoder.onMalformedInput(CodingErrorAction.IGNORE);
			assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out,
					endOfInput));
			assertCodingErrorAction(endOfInput, out, in, unibytes);

			encoder.reset();
			out.clear();
			in.rewind();
			encoder.onMalformedInput(CodingErrorAction.REPLACE);
			assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out,
					endOfInput));
			assertCodingErrorAction(endOfInput, out, in, unibytesWithRep);
		} else {
			System.out.println("Cannot find malformed char buffer for "
					+ cs.name());
		}

		// Unmapped Exception:
		in = getUnmapCharBuffer();
		encoder.onMalformedInput(CodingErrorAction.REPORT);
		encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
		if (in != null) {
			encoder.reset();
			out.clear();
			assertTrue(encoder.encode(in, out, endOfInput).isUnmappable());

			encoder.reset();
			out.clear();
			in.rewind();
			encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
			assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out,
					endOfInput));
			assertCodingErrorAction(endOfInput, out, in, unibytes);

			encoder.reset();
			out.clear();
			in.rewind();
			encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
			assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out,
					endOfInput));
			assertCodingErrorAction(endOfInput, out, in, unibytesWithRep);
		} else {
			System.out.println("Cannot find unmapped char buffer for "
					+ cs.name());
		}

		// RuntimeException
		try {
			encoder.encode(getExceptionCharBuffer());
			fail("should throw runtime exception");
		} catch (RuntimeException e) {
		}
	}

	private void assertCodingErrorAction(boolean endOfInput, ByteBuffer out,
			CharBuffer in, byte[] expect) {
		if (endOfInput) {
			assertByteArray(out, addSurrogate(expect));
		} else {
			in.rewind();
			assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out,
					endOfInput));
			in.rewind();
			assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true));
			assertByteArray(out, addSurrogate(duplicateByteArray(expect, 3)));
		}
	}

	/*
	 * Class under test for CoderResult flush(ByteBuffer)
	 */
	public void testFlush() throws CharacterCodingException {
		ByteBuffer out = ByteBuffer.allocate(6);
		CharBuffer in = CharBuffer.wrap("aaa");
		assertEquals(in.remaining(), 3);

		// by encode facade, so that internal state will be wrong
		encoder.encode(CharBuffer.wrap("testFlush"), ByteBuffer.allocate(20),
				true);
		assertSame(CoderResult.UNDERFLOW, encoder
				.flush(ByteBuffer.allocate(50)));
	}

	/*
	 * test isLegalReplacement(byte[])
	 */
	public void testIsLegalReplacement() {
		try {
			encoder.isLegalReplacement(null);
			fail("should throw null pointer exception");
		} catch (NullPointerException e) {
		}
		assertTrue(encoder.isLegalReplacement(specifiedReplacement));

		assertTrue(encoder.isLegalReplacement(new byte[200]));
		byte[] ba = getIllegalByteArray();
		if (ba != null) {
			assertFalse(encoder.isLegalReplacement(ba));
		}
	}

	public void testIsLegalReplacementEmptyArray() {
		// ISO, ASC, GB, UTF8 encoder will throw exception in RI
		// others will pass
		// try {
		assertTrue(encoder.isLegalReplacement(new byte[0]));
		// fail("should throw ArrayIndexOutOfBoundsException");
		// } catch (ArrayIndexOutOfBoundsException e) {
		// }
	}

	public void testOnMalformedInput() {
		assertSame(CodingErrorAction.REPORT, encoder.malformedInputAction());
		try {
			encoder.onMalformedInput(null);
			fail("should throw null pointer exception");
		} catch (IllegalArgumentException e) {
		}
		encoder.onMalformedInput(CodingErrorAction.IGNORE);
		assertSame(CodingErrorAction.IGNORE, encoder.malformedInputAction());
	}

	public void testOnUnmappableCharacter() {
		assertSame(CodingErrorAction.REPORT, encoder
				.unmappableCharacterAction());
		try {
			encoder.onUnmappableCharacter(null);
			fail("should throw null pointer exception");
		} catch (IllegalArgumentException e) {
		}
		encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
		assertSame(CodingErrorAction.IGNORE, encoder
				.unmappableCharacterAction());
	}

	public void testReplacement() {
		try {
			encoder.replaceWith(null);
			fail("should throw null pointer exception");
		} catch (IllegalArgumentException e) {
		}
		try {
			encoder.replaceWith(new byte[0]);
			fail("should throw null pointer exception");
		} catch (IllegalArgumentException e) {
		}
		try {
			encoder.replaceWith(new byte[100]);
			fail("should throw null pointer exception");
		} catch (IllegalArgumentException e) {
		}

		byte[] nr = getLegalByteArray();
		assertSame(encoder, encoder.replaceWith(nr));
		assertSame(nr, encoder.replacement());

		nr = getIllegalByteArray();
		try {
			encoder.replaceWith(new byte[100]);
			fail("should throw null pointer exception");
		} catch (IllegalArgumentException e) {
		}
	}

	protected byte[] getLegalByteArray() {
		return new byte[] { 'a' };
	}

	protected byte[] getIllegalByteArray() {
		return new byte[155];
	}

	/*
	 * Mock subclass of CharsetEncoder For protected method test
	 */
	public static class MockCharsetEncoder extends CharsetEncoder {

		boolean flushed = false;

		public boolean isFlushed() {
			boolean result = flushed;
			flushed = false;
			return result;
		}

		public boolean isLegalReplacement(byte[] ba) {
			if (ba.length == 155) {// specified magic number, return false
				return false;
			}
			return super.isLegalReplacement(ba);
		}

		public MockCharsetEncoder(Charset cs, float aver, float max) {
			super(cs, aver, max);
		}

		public MockCharsetEncoder(Charset cs, float aver, float max,
				byte[] replacement) {
			super(cs, aver, max, replacement);
		}

		protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) {
			int inPosition = in.position();
			char[] input = new char[in.remaining()];
			in.get(input);
			String result = new String(input);
			if (result.startsWith("malform")) {
				// reset the cursor to the error position
				in.position(inPosition);
				// in.position(0);
				// set the error length
				return CoderResult.malformedForLength("malform".length());
			} else if (result.startsWith("unmap")) {
				// reset the cursor to the error position
				in.position(inPosition);
				// in.position(0);
				// set the error length
				return CoderResult.unmappableForLength("unmap".length());
			} else if (result.startsWith("runtime")) {
				// reset the cursor to the error position
				in.position(0);
				// set the error length
				throw new RuntimeException("runtime");
			}
			int inLeft = input.length;
			int outLeft = out.remaining();
			CoderResult r = CoderResult.UNDERFLOW;
			int length = inLeft;
			if (outLeft < inLeft) {
				r = CoderResult.OVERFLOW;
				length = outLeft;
				in.position(inPosition + outLeft);
			}
			for (int i = 0; i < length; i++) {
				out.put((byte) input[i]);
			}
			return r;
		}

		protected CoderResult implFlush(ByteBuffer out) {
			CoderResult result = super.implFlush(out);
			int length = 0;
			if (out.remaining() >= 5) {
				length = 5;
				result = CoderResult.UNDERFLOW;
				flushed = true;
				// for (int i = 0; i < length; i++) {
				// out.put((byte)'f');
				// }
			} else {
				length = out.remaining();
				result = CoderResult.OVERFLOW;
			}
			return result;
		}

		protected void implReplaceWith(byte[] ba) {
			assertSame(ba, replacement());
		}

	}

	/*
	 * mock charset for test encoder initialization
	 */
	public static class MockCharset extends Charset {
		protected MockCharset(String arg0, String[] arg1) {
			super(arg0, arg1);
		}

		public boolean contains(Charset arg0) {
			return false;
		}

		public CharsetDecoder newDecoder() {
			return new CharsetDecoderTest.MockCharsetDecoder(this,
					(float) AVER_BYTES, MAX_BYTES);
		}

		public CharsetEncoder newEncoder() {
			return new MockCharsetEncoder(this, (float) AVER_BYTES, MAX_BYTES);
		}
	}

}


text:
package io.netty.handler.codec.http2;

import io.netty.channel.ChannelHandlerContext;

/**
 * A {@link Http2FlowController} for controlling the flow of outbound {@code DATA} frames to the remote
 * endpoint.
 */
public interface Http2RemoteFlowController extends Http2FlowController {

    /**
     * Writes or queues a payload for transmission to the remote endpoint. There is no
     * guarantee when the data will be written or whether it will be split into multiple frames
     * before sending.
     * <p>
     * Manually flushing the {@link ChannelHandlerContext} is not required, since the flow
     * controller will flush as appropriate.
     *
     * @param ctx the context from the handler.
     * @param stream the subject stream. Must not be the connection stream object.
     * @param payload payload to write subject to flow-control accounting and ordering rules.
     */
    void sendFlowControlled(ChannelHandlerContext ctx, Http2Stream stream, FlowControlled payload);

    /**
     * Implementations of this interface are used to progressively write chunks of the underlying
     * payload to the stream. A payload is considered to be fully written if {@link #write} has
     * been called at least once and it's {@link #size} is now zero.
     */
    interface FlowControlled {
        /**
         * The size of the payload in terms of bytes applied to the flow-control window.
         * Some payloads like {@code HEADER} frames have no cost against flow control and would
         * return 0 for this value even though they produce a non-zero number of bytes on
         * the wire. Other frames like {@code DATA} frames have both their payload and padding count
         * against flow-control.
         */
        int size();

        /**
         * Signal an error and release any retained buffers.
         * @param cause of the error.
         */
        void error(Throwable cause);

        /**
         * Writes up to {@code allowedBytes} of the encapsulated payload to the stream. Note that
         * a value of 0 may be passed which will allow payloads with flow-control size == 0 to be
         * written. The flow-controller may call this method multiple times with different values until
         * the payload is fully written.
         *
         * @param allowedBytes an upper bound on the number of bytes the payload can write at this time.
         * @return {@code true} if a flush is required, {@code false} otherwise.
         */
        boolean write(int allowedBytes);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace TBone;

class TBoneEvent
{
    /**
     * A matching route was not found.
     */
    const ROUTE_NOT_FOUND = 1;
    const ROUTE_DISPATCH_REQUESTED = 2;
    const ROUTE_DISPATCHED = 3;
}


text:
SOLIDAdapter es un ejemplo de cómo crear un Adaptador para un RecyclerView teniendo en cuenta los principios SOLID.

Podéis ver la entrada en http://jmperezramos.net/desarrollo-en-android/android-adapter-para-recyclerview-cumpliendo-los-principios-solid/


text:
<?php

namespace Zephia\MercadoLibre\Entity;

/**
 * Class SellerTransaction
 *
 * @package Zephia\MercadoLibre\Entity
 * @author  Mauro Moreno<moreno.mauro.emanuel@gmail.com>
 */
class SellerTransaction
{
    /**
     * @var integer
     */
    public $canceled;

    /**
     * @var integer
     */
    public $completed;

    /**
     * @var string
     */
    public $period;

    /**
     * @var Rating
     */
    public $ratings;

    /**
     * @var integer
     */
    public $total;
}


text:
'use strict';

describe('AlertsController', function() {
  var scope, createController;

  beforeEach(angular.mock.module('kopf'));

  beforeEach(angular.mock.inject(function($rootScope, $controller, $injector) {
    this.scope = $rootScope.$new();
    this.AlertService = $injector.get('AlertService');
    this.createController = function() {
      return $controller('AlertsController', {$scope: this.scope},
          this.AlertService);
    };
    this._controller = this.createController();
  }));

  it('init : values are set', function() {
    expect(this.scope.alerts).toEqual([]);
  });

  it('updates alerts when alert service changes', function() {
    expect(this.scope.alerts.length).toEqual(0);
    this.AlertService.info("test");
    this.scope.$digest();
    expect(this.scope.alerts.length).toEqual(1);
  });

  it('removes an alert when remove method is called', function() {
    spyOn(this.AlertService, 'remove').andReturn(true);
    this.scope.remove('hello');
    expect(this.AlertService.remove).toHaveBeenCalledWith('hello');
  });

});


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.facebook.presto</groupId>
        <artifactId>presto-root</artifactId>
        <version>0.159</version>
    </parent>
    <artifactId>presto-elasticsearch</artifactId>
    <description>Presto - Elasticsearch Connector</description>
    <packaging>presto-plugin</packaging>

    <properties>
        <air.main.basedir>${project.parent.basedir}</air.main.basedir>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>1.6.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.yaml</groupId>
                    <artifactId>snakeyaml</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.ow2.asm</groupId>
                    <artifactId>asm-all</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.ow2.asm</groupId>
                    <artifactId>asm-commons</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.ow2.asm</groupId>
                    <artifactId>asm</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20080701</version>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-spi</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>bootstrap</artifactId>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>json</artifactId>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>log</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>units</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>configuration</artifactId>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>slice</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>

        <!-- for testing -->
        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-main</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>testing</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>http-server</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>node</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>concurrent</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>


text:
package com.tiny.demo.firstlinecode.materialdesign;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tiny.demo.firstlinecode.BaseActivity;
import com.tiny.demo.firstlinecode.R;

/**
 * 水果详情页
 */
public class FruitDetailActivity extends BaseActivity {
    public static final String FRUIT_NAME = "FRUIT_NAME";
    public static final String FRUIT_IMG = "FRUIT_IMG";
    private String name;
    private Integer imgId;

    public static void actionStart(Context context, Bundle bundle) {
        Intent intent = new Intent(context, FruitDetailActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected int setContentLayout() {
        return R.layout.activity_fruit_detail;
    }

    @Override
    protected void buildContentView() {
        Intent intent = getIntent();
        if (intent != null) {
            name = intent.getStringExtra(FRUIT_NAME);
            imgId = intent.getIntExtra(FRUIT_IMG, 0);
        }
        CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        ImageView img = (ImageView) findViewById(R.id.fruit_image_view);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        TextView txtContent = (TextView) findViewById(R.id.fruit_content_text);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        //设置收缩起来时toolBar的标题和展开时CollapsingToolbarLayout左下角的标题。
        collapsingToolbarLayout.setTitle("童童");
        Glide.with(mContext).load(imgId).into(img);
        String fruitContent = generateFruitContent(name);
        txtContent.setText(fruitContent);
    }

    private String generateFruitContent(String name) {
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < 500; j++) {
            sb.append(name).append(" --> ");
        }
        return sb.toString();
    }

    @Override
    protected void initViewData() {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
body {
  background-color: #333;
  color: white;
}


text:
import * as React from 'react';
import { IMembersListProps } from './IMembersListProps';
import { IMemberListState } from './IMemberListState';
import { Panel, PanelType, Spinner, SpinnerSize, DefaultButton } from 'office-ui-fabric-react';
import { ListView, IViewField } from '@pnp/spfx-controls-react/lib/ListView';
import { graph } from '@pnp/graph/presets/all';
import { CSVLink } from 'react-csv';
import styles from './MembersList.module.scss';

const view: IViewField[] = [
    {
        name: 'displayName',
        displayName: 'Name',
        minWidth: 150,
        isResizable: true
    },
    {
        name: 'mail',
        displayName: 'Email',
        minWidth: 150,
        isResizable: true
    }
];

const csvHeaders = [
    { label: 'Name', key: 'displayName'},
    { label: 'Email', key: 'mail'}
];

export class MembersList extends React.Component<IMembersListProps, IMemberListState>{

    constructor(props: IMembersListProps) {
        super(props);

        this.state = {
            members: null,
            membersCount: 0,
            isLoading: false
        };
    }

    public render(): React.ReactElement<IMembersListProps> {
        return (

                <Panel type={PanelType.medium} isOpen={this.props.showPanel} headerText={`${this.props.groupName} - Members (${this.state.membersCount})`} onDismiss={this._handlePanel}>
                    {this.state.isLoading ?

                            <Spinner label="Loading Members..." size={SpinnerSize.medium} />

                        :

                                <CSVLink data={this.state.members} headers={csvHeaders} filename={`${this.props.groupName}-Members.csv`}>
                                    <DefaultButton text="Export to CSV" />
                                </CSVLink>

                            <ListView
                             items={this.state.members}
                             viewFields={view}
                             showFilter={true}
                             filterPlaceHolder={"Search Members..."}
                            />

                    }
                </Panel>

        );
    }

    public componentDidMount() {
        this._loadMembers();
    }

    private _loadMembers = (): void => {
        this.setState({isLoading: true});
        this._getMembers(this.props.groupId).then(response => {
            this.setState({
                members: response,
                membersCount: response.length,
                isLoading: false
            });
        });
    }

    private async _getMembers(id: string) {
        const members = await graph.groups.getById(id).members();
        console.log(members);
        return members;
    }

    private _handlePanel = (): void => {
       this.props.closePanel();
    }

}


text:
package models

import "time"

// UserRequestModel model.
type UserRequestModel struct {
	ID       string `json:"id"`
	Username string `json:"username"`
	Password string `json:"password"`
}

// LoginRequestModel model.
type LoginRequestModel struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// TodoRequestModel model.
type TodoRequestModel struct {
	ID       string     `json:"id"`
	Content  string     `json:"content"`
	Category string     `json:"category"`
	Deadline *time.Time `json:"deadline"`
	Priority int        `json:"priority"`
}


text:
"""
This module provides a set of permission lock functions for use
with Evennia's permissions system.

To call these locks, make sure this module is included in the
settings tuple `PERMISSION_FUNC_MODULES` then define a lock on the form
'<access_type>:func(args)' and add it to the object's lockhandler.
Run the `access()` method of the handler to execute the lock check.

Note that `accessing_obj` and `accessed_obj` can be any object type
with a lock variable/field, so be careful to not expect
a certain object type.

**Appendix: MUX locks**

Below is a list nicked from the MUX help file on the locks available
in standard MUX. Most of these are not relevant to core Evennia since
locks in Evennia are considerably more flexible and can be implemented
on an individual command/typeclass basis rather than as globally
available like the MUX ones. So many of these are not available in
basic Evennia, but could all be implemented easily if needed for the
individual game.

```
MUX Name:      Affects:        Effect:
----------------------------------------------------------------------
DefaultLock:   Exits:          controls who may traverse the exit to
                               its destination.
                                 Evennia: "traverse:<lockfunc()>"
               Rooms:          controls whether the player sees the
                               SUCC or FAIL message for the room
                               following the room description when
                               looking at the room.
                                 Evennia: Custom typeclass
               Players/Things: controls who may GET the object.
                                 Evennia: "get:<lockfunc()"
 EnterLock:    Players/Things: controls who may ENTER the object
                                 Evennia:
 GetFromLock:  All but Exits:  controls who may gets things from a
                               given location.
                                 Evennia:
 GiveLock:     Players/Things: controls who may give the object.
                                 Evennia:
 LeaveLock:    Players/Things: controls who may LEAVE the object.
                                 Evennia:
 LinkLock:     All but Exits:  controls who may link to the location
                               if the location is LINK_OK (for linking
                               exits or setting drop-tos) or ABODE (for
                               setting homes)
                                 Evennia:
 MailLock:     Players:        controls who may @mail the player.
                               Evennia:
 OpenLock:     All but Exits:  controls who may open an exit.
                                 Evennia:
 PageLock:     Players:        controls who may page the player.
                                 Evennia: "send:<lockfunc()>"
 ParentLock:   All:            controls who may make @parent links to
                               the object.
                                 Evennia: Typeclasses and
                               "puppet:<lockstring()>"
 ReceiveLock:  Players/Things: controls who may give things to the
                               object.
                                 Evennia:
 SpeechLock:   All but Exits:  controls who may speak in that location
                                 Evennia:
 TeloutLock:   All but Exits:  controls who may teleport out of the
                               location.
                                 Evennia:
 TportLock:    Rooms/Things:   controls who may teleport there
                                 Evennia:
 UseLock:      All but Exits:  controls who may USE the object, GIVE
                               the object money and have the PAY
                               attributes run, have their messages
                               heard and possibly acted on by LISTEN
                               and AxHEAR, and invoke $-commands
                               stored on the object.
                                 Evennia: Commands and Cmdsets.
 DropLock:     All but rooms:  controls who may drop that object.
                                 Evennia:
 VisibleLock:  All:            Controls object visibility when the
                               object is not dark and the looker
                               passes the lock. In DARK locations, the
                               object must also be set LIGHT and the
                               viewer must pass the VisibleLock.
                                 Evennia: Room typeclass with
                                          Dark/light script
```
"""

from django.conf import settings
from evennia.utils import utils

_PERMISSION_HIERARCHY = [p.lower() for p in settings.PERMISSION_HIERARCHY]

def _to_player(accessing_obj):
    "Helper function. Makes sure an accessing object is a player object"
    if utils.inherits_from(accessing_obj, "evennia.objects.objects.DefaultObject"):
        # an object. Convert to player.
        accessing_obj = accessing_obj.player
    return accessing_obj

# lock functions

def true(*args, **kwargs):
    "Always returns True."
    return True

def all(*args, **kwargs):
    return True

def false(*args, **kwargs):
    "Always returns False"
    return False

def none(*args, **kwargs):
    return False

def self(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Check if accessing_obj is the same as accessed_obj

    Usage:
       self()

    This can be used to lock specifically only to
    the same object that the lock is defined on.
    """
    return accessing_obj == accessed_obj

def perm(accessing_obj, accessed_obj, *args, **kwargs):
    """
    The basic permission-checker. Ignores case.

    Usage:
       perm(<permission>)

    where <permission> is the permission accessing_obj must
    have in order to pass the lock.

    If the given permission is part of settings.PERMISSION_HIERARCHY,
    permission is also granted to all ranks higher up in the hierarchy.

    If accessing_object is an Object controlled by a Player, the
    permissions of the Player is used unless the Attribute _quell
    is set to True on the Object. In this case however, the
    LOWEST hieararcy-permission of the Player/Object-pair will be used
    (this is order to avoid Players potentially escalating their own permissions
    by use of a higher-level Object)

    """
    # this allows the perm_above lockfunc to make use of this function too
    gtmode = kwargs.pop("_greater_than", False)

    try:
        perm = args[0].lower()
        perms_object = [p.lower() for p in accessing_obj.permissions.all()]
    except (AttributeError, IndexError):
        return False

    if utils.inherits_from(accessing_obj, "evennia.objects.objects.DefaultObject") and accessing_obj.player:
        player = accessing_obj.player
        perms_player = [p.lower() for p in player.permissions.all()]
        is_quell = player.attributes.get("_quell")

        if perm in _PERMISSION_HIERARCHY:
            # check hierarchy without allowing escalation obj->player
            hpos_target = _PERMISSION_HIERARCHY.index(perm)
            hpos_player = [hpos for hpos, hperm in enumerate(_PERMISSION_HIERARCHY) if hperm in perms_player]
            hpos_player = hpos_player and hpos_player[-1] or -1
            if is_quell:
                hpos_object = [hpos for hpos, hperm in enumerate(_PERMISSION_HIERARCHY) if hperm in perms_object]
                hpos_object = hpos_object and hpos_object[-1] or -1
                if gtmode:
                    return hpos_target < min(hpos_player, hpos_object)
                else:
                    return hpos_target <= min(hpos_player, hpos_object)
            elif gtmode:
                return hpos_target < hpos_player
            else:
                return hpos_target <= hpos_player
        elif not is_quell and perm in perms_player:
            # if we get here, check player perms first, otherwise
            # continue as normal
            return True

    if perm in perms_object:
        # simplest case - we have direct match
        return True
    if perm in _PERMISSION_HIERARCHY:
        # check if we have a higher hierarchy position
        hpos_target = _PERMISSION_HIERARCHY.index(perm)
        return any(1 for hpos, hperm in enumerate(_PERMISSION_HIERARCHY)
                   if hperm in perms_object and hpos_target < hpos)
    return False

def perm_above(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Only allow objects with a permission *higher* in the permission
    hierarchy than the one given. If there is no such higher rank,
    it's assumed we refer to superuser. If no hierarchy is defined,
    this function has no meaning and returns False.
    """
    kwargs["_greater_than"] = True
    return perm(accessing_obj, accessed_obj, *args, **kwargs)

def pperm(accessing_obj, accessed_obj, *args, **kwargs):
    """
    The basic permission-checker only for Player objects. Ignores case.

    Usage:
       pperm(<permission>)

    where <permission> is the permission accessing_obj must
    have in order to pass the lock. If the given permission
    is part of _PERMISSION_HIERARCHY, permission is also granted
    to all ranks higher up in the hierarchy.
    """
    return perm(_to_player(accessing_obj), accessed_obj, *args, **kwargs)

def pperm_above(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Only allow Player objects with a permission *higher* in the permission
    hierarchy than the one given. If there is no such higher rank,
    it's assumed we refer to superuser. If no hierarchy is defined,
    this function has no meaning and returns False.
    """
    return perm_above(_to_player(accessing_obj), accessed_obj, *args, **kwargs)

def dbref(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
      dbref(3)

    This lock type checks if the checking object
    has a particular dbref. Note that this only
    works for checking objects that are stored
    in the database (e.g. not for commands)
    """
    if not args:
        return False
    try:
        dbref = int(args[0].strip().strip('#'))
    except ValueError:
        return False
    if hasattr(accessing_obj, 'dbid'):
        return dbref == accessing_obj.dbid
    return False

def pdbref(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Same as dbref, but making sure accessing_obj is a player.
    """
    return dbref(_to_player(accessing_obj), accessed_obj, *args, **kwargs)

def id(accessing_obj, accessed_obj, *args, **kwargs):
    "Alias to dbref"
    return dbref(accessing_obj, accessed_obj, *args, **kwargs)

def pid(accessing_obj, accessed_obj, *args, **kwargs):
    "Alias to dbref, for Players"
    return dbref(_to_player(accessing_obj), accessed_obj, *args, **kwargs)

# this is more efficient than multiple if ... elif statments
CF_MAPPING = {'eq': lambda val1, val2: val1 == val2 or str(val1) == str(val2) or float(val1) == float(val2),
              'gt': lambda val1, val2: float(val1) >  float(val2),
              'lt': lambda val1, val2: float(val1) <  float(val2),
              'ge': lambda val1, val2: float(val1) >= float(val2),
              'le': lambda val1, val2: float(val1) <= float(val2),
              'ne': lambda val1, val2: float(val1) != float(val2),
              'default': lambda val1, val2: False}

def attr(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
      attr(attrname)
      attr(attrname, value)
      attr(attrname, value, compare=type)

    where compare's type is one of (eq,gt,lt,ge,le,ne) and signifies
    how the value should be compared with one on accessing_obj (so
    compare=gt means the accessing_obj must have a value greater than
    the one given).

    Searches attributes *and* properties stored on the accessing_obj.
    if accessing_obj has a property "obj", then this is used as
    accessing_obj (this makes this usable for Commands too)

    The first form works like a flag - if the attribute/property
    exists on the object, the value is checked for True/False. The
    second form also requires that the value of the attribute/property
    matches. Note that all retrieved values will be converted to
    strings before doing the comparison.
    """
    # deal with arguments
    if not args:
        return False
    attrname = args[0].strip()
    value = None
    if len(args) > 1:
        value = args[1].strip()
    compare = 'eq'
    if kwargs:
        compare = kwargs.get('compare', 'eq')

    def valcompare(val1, val2, typ='eq'):
        "compare based on type"
        try:
            return CF_MAPPING.get(typ, CF_MAPPING['default'])(val1, val2)
        except Exception:
            # this might happen if we try to compare two things that
            # cannot be compared
            return False

    if hasattr(accessing_obj, "obj"):
        # NOTE: this is relevant for Commands. It may clash with scripts
        # (they have Attributes and .obj) , but are scripts really
        # used so that one ever wants to check the property on the
        # Script rather than on its owner?
        accessing_obj = accessing_obj.obj

    # first, look for normal properties on the object trying to gain access
    if hasattr(accessing_obj, attrname):
        if value:
            return valcompare(str(getattr(accessing_obj, attrname)), value, compare)
        # will return Fail on False value etc
        return bool(getattr(accessing_obj, attrname))
    # check attributes, if they exist
    if (hasattr(accessing_obj, 'attributes') and accessing_obj.attributes.has(attrname)):
        if value:
            return (hasattr(accessing_obj, 'attributes')
                    and valcompare(accessing_obj.attributes.get(attrname), value, compare))
        # fails on False/None values
        return bool(accessing_obj.attributes.get(attrname))
    return False

def objattr(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
      objattr(attrname)
      objattr(attrname, value)
      objattr(attrname, value, compare=type)

    Works like attr, except it looks for an attribute on
    accessed_obj instead.

    """
    return attr(accessed_obj, accessed_obj, *args, **kwargs)

def locattr(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
      locattr(attrname)
      locattr(attrname, value)
      locattr(attrname, value, compare=type)

    Works like attr, except it looks for an attribute on
    accessing_obj.location, if such an entity exists.

    if accessing_obj has a property ".obj" (such as is the case for a
    Command), then accessing_obj.obj.location is used instead.

    """
    if hasattr(accessing_obj, "obj"):
        accessing_obj = accessing_obj.obj
    if hasattr(accessing_obj, "location"):
        return attr(accessing_obj.location, accessed_obj, *args, **kwargs)

def objlocattr(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
      locattr(attrname)
      locattr(attrname, value)
      locattr(attrname, value, compare=type)

    Works like attr, except it looks for an attribute on
    accessed_obj.location, if such an entity exists.

    if accessed_obj has a property ".obj" (such as is the case for a
    Command), then accessing_obj.obj.location is used instead.

    """
    if hasattr(accessed_obj, "obj"):
        accessed_obj = accessed_obj.obj
    if hasattr(accessed_obj, "location"):
        return attr(accessed_obj.location, accessed_obj, *args, **kwargs)

def attr_eq(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
       attr_gt(attrname, 54)
    """
    return attr(accessing_obj, accessed_obj, *args, **kwargs)

def attr_gt(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
       attr_gt(attrname, 54)

    Only true if access_obj's attribute > the value given.
    """
    return attr(accessing_obj, accessed_obj, *args, **{'compare': 'gt'})

def attr_ge(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
       attr_gt(attrname, 54)

    Only true if access_obj's attribute >= the value given.
    """
    return attr(accessing_obj, accessed_obj, *args, **{'compare': 'ge'})

def attr_lt(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
       attr_gt(attrname, 54)

    Only true if access_obj's attribute < the value given.
    """
    return attr(accessing_obj, accessed_obj, *args, **{'compare': 'lt'})

def attr_le(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
       attr_gt(attrname, 54)

    Only true if access_obj's attribute <= the value given.
    """
    return attr(accessing_obj, accessed_obj, *args, **{'compare': 'le'})

def attr_ne(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
       attr_gt(attrname, 54)

    Only true if access_obj's attribute != the value given.
    """
    return attr(accessing_obj, accessed_obj, *args, **{'compare': 'ne'})

def tag(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
        tag(tagkey)
        tag(tagkey, category)

    Only true if accessing_obj has the specified tag and optional
    category.
    If accessing_obj has the ".obj" property (such as is the case for
    a command), then accessing_obj.obj is used instead.
    """
    if hasattr(accessing_obj, "obj"):
        accessing_obj = accessing_obj = accessing_obj.obj
    print "tag:", args, accessing_obj, accessing_obj.tags.get(*args)
    return accessing_obj.tags.get(*args)

def objtag(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
        objtag(tagkey)
        objtag(tagkey, category)

    Only true if accessed_obj has the specified tag and optional
    category.
    """
    return accessed_obj.tags.get(*args)

def inside(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
       inside()

    Only true if accessing_obj is "inside" accessed_obj
    """
    return accessing_obj.location == accessed_obj

def holds(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Usage:
      holds()            checks if accessed_obj or accessed_obj.obj
                         is held by accessing_obj
      holds(key/dbref)   checks if accessing_obj holds an object
                          with given key/dbref
      holds(attrname, value)   checks if accessing_obj holds an
                               object with the given attrname and value

    This is passed if accessed_obj is carried by accessing_obj (that is,
    accessed_obj.location == accessing_obj), or if accessing_obj itself holds
    an object matching the given key.
    """
    try:
        # commands and scripts don't have contents, so we are usually looking
        # for the contents of their .obj property instead (i.e. the object the
        # command/script is attached to).
        contents = accessing_obj.contents
    except AttributeError:
        try:
            contents = accessing_obj.obj.contents
        except AttributeError:
            return False

    def check_holds(objid):
        # helper function. Compares both dbrefs and keys/aliases.
        objid = str(objid)
        dbref = utils.dbref(objid, reqhash=False)
        if dbref and any((True for obj in contents if obj.dbid == dbref)):
            return True
        objid = objid.lower()
        return any((True for obj in contents
                    if obj.key.lower() == objid or objid in [al.lower() for al in obj.aliases.all()]))
    if not args:
        # holds() - check if accessed_obj or accessed_obj.obj is held by accessing_obj
        try:
            if check_holds(accessed_obj.dbid):
                return True
        except Exception:
            pass
        return hasattr(accessed_obj, "obj") and check_holds(accessed_obj.obj.dbid)
    if len(args) == 1:
        # command is holds(dbref/key) - check if given objname/dbref is held by accessing_ob
        return check_holds(args[0])
    elif len(args = 2):
        # command is holds(attrname, value) check if any held object has the given attribute and value
        for obj in contents:
            if obj.attributes.get(args[0]) == args[1]:
                return True

def superuser(*args, **kwargs):
    """
    Only accepts an accesing_obj that is superuser (e.g. user #1)

    Since a superuser would not ever reach this check (superusers
    bypass the lock entirely), any user who gets this far cannot be a
    superuser, hence we just return False. :)
    """
    return False

def has_player(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Only returns true if accessing_obj has_player is true, that is,
    this is a player-controlled object. It fails on actual players!

    This is a useful lock for traverse-locking Exits to restrain NPC
    mobiles from moving outside their areas.
    """
    return hasattr(accessing_obj, "has_player") and accessing_obj.has_player

def serversetting(accessing_obj, accessed_obj, *args, **kwargs):
    """
    Only returns true if the Evennia settings exists, alternatively has
    a certain value.

    Usage:
      serversetting(IRC_ENABLED)
      serversetting(BASE_SCRIPT_PATH, ['types'])

    A given True/False or integers will be converted properly.
    """
    if not args or not args[0]:
        return False
    if len(args) < 2:
        setting = args[0]
        val = "True"
    else:
        setting, val = args[0], args[1]
    # convert
    if val == 'True':
        val = True
    elif val == 'False':
        val = False
    elif val.isdigit():
        val = int(val)
    if setting in settings._wrapped.__dict__:
        return settings._wrapped.__dict__[setting] == val
    return False


text:
pymatgen.apps.battery package
=============================

Subpackages
-----------

.. toctree::

Submodules
----------

.. toctree::

   pymatgen.apps.battery.analyzer
   pymatgen.apps.battery.battery_abc
   pymatgen.apps.battery.conversion_battery
   pymatgen.apps.battery.insertion_battery
   pymatgen.apps.battery.plotter

Module contents
---------------

.. automodule:: pymatgen.apps.battery
    :members:
    :undoc-members:
    :show-inheritance:


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<TITLE>CLHS: Macro WHEN, UNLESS</TITLE>
<META HTTP-EQUIV="Author" CONTENT="Kent M. Pitman">
<META HTTP-EQUIV="Organization" CONTENT="The Harlequin Group Limited">
<LINK REL=TOP HREF="../FrontMatter/index.html">
<LINK REL=COPYRIGHT HREF="../FrontMatter/About-HyperSpec.html#Legal">
<LINK REL=DISCLAIMER HREF="../FrontMatter/About-HyperSpec.html#Disclaimer">
<LINK REL=PREV HREF="mac_or.html">
<LINK REL=UP HREF="sec_the_data__w_dictionary.html">
<LINK REL=NEXT HREF="mac_casecm_ccasecm_ecase.html">

Macro WHEN, UNLESS

Syntax:

when test-form form* => result*

unless test-form form* => result*

Arguments and Values:

test-form---a form.

forms---an implicit progn.

results---the values of the forms in a when form if the test-form yields true or in an unless form if the test-form yields false; otherwise nil.

Description:

when and unless allow the execution of forms to be dependent on a single test-form.

In a when form, if the test-form yields true, the forms are evaluated in order from left to right and the values returned by the forms are returned from the when form. Otherwise, if the test-form yields false, the forms are not evaluated, and the when form returns nil.

In an unless form, if the test-form yields false, the forms are evaluated in order from left to right and the values returned by the forms are returned from the unless form. Otherwise, if the test-form yields false, the forms are not evaluated, and the unless form returns nil.

Examples:

 (when t 'hello) =>  HELLO
 (unless t 'hello) =>  NIL
 (when nil 'hello) =>  NIL
 (unless nil 'hello) =>  HELLO
 (when t) =>  NIL
 (unless nil) =>  NIL
 (when t (prin1 1) (prin1 2) (prin1 3))
>>  123
=>  3
 (unless t (prin1 1) (prin1 2) (prin1 3)) =>  NIL
 (when nil (prin1 1) (prin1 2) (prin1 3)) =>  NIL
 (unless nil (prin1 1) (prin1 2) (prin1 3))
>>  123
=>  3
 (let ((x 3))
   (list (when (oddp x) (incf x) (list x))
         (when (oddp x) (incf x) (list x))
         (unless (oddp x) (incf x) (list x))
         (unless (oddp x) (incf x) (list x))
         (if (oddp x) (incf x) (list x))
         (if (oddp x) (incf x) (list x))
         (if (not (oddp x)) (incf x) (list x))
         (if (not (oddp x)) (incf x) (list x))))
=>  ((4) NIL (5) NIL 6 (6) 7 (7))

</TT>

Side Effects: None.

Affected By: None.

Exceptional Situations: None.

See Also:

and, cond, if, or

Notes:

 (when test {form}+) ==  (and test (progn {form}+))
 (when test {form}+) ==  (cond (test {form}+))
 (when test {form}+) ==  (if test (progn {form}+) nil)
 (when test {form}+) ==  (unless (not test) {form}+)
 (unless test {form}+) ==  (cond ((not test) {form}+))
 (unless test {form}+) ==  (if test nil (progn {form}+))
 (unless test {form}+) ==  (when (not test) {form}+)

</TT>

Copyright 1996, The Harlequin Group Limited.  All Rights Reserved.


text:
package org.apache.camel.converter.jaxb.springboot;

import javax.annotation.Generated;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Camel JAXB support
 *
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
@ConfigurationProperties(prefix = "camel.dataformat.jaxb")
public class JaxbDataFormatConfiguration {

    /**
     * Package name where your JAXB classes are located.
     */
    private String contextPath;
    /**
     * To validate against an existing schema. Your can use the prefix
     * classpath: file: or http: to specify how the resource should by resolved.
     * You can separate multiple schema files by using the '' character.
     */
    private String schema;
    /**
     * To enable pretty printing output nicely formatted. Is by default false.
     */
    private Boolean prettyPrint = false;
    /**
     * Whether to allow using ObjectFactory classes to create the POJO classes
     * during marshalling. This only applies to POJO classes that has not been
     * annotated with JAXB and providing jaxb.index descriptor files.
     */
    private Boolean objectFactory = false;
    /**
     * Whether to ignore JAXBElement elements - only needed to be set to false
     * in very special use-cases.
     */
    private Boolean ignoreJAXBElement = false;
    /**
     * Whether marhsalling must be java objects with JAXB annotations. And if
     * not then it fails. This option can be set to false to relax that such as
     * when the data is already in XML format.
     */
    private Boolean mustBeJAXBElement = false;
    /**
     * To ignore non xml characheters and replace them with an empty space.
     */
    private Boolean filterNonXmlChars = false;
    /**
     * To overrule and use a specific encoding
     */
    private String encoding;
    /**
     * To turn on marshalling XML fragment trees. By default JAXB looks for
     * XmlRootElement annotation on given class to operate on whole XML tree.
     * This is useful but not always - sometimes generated code does not have
     * XmlRootElement annotation sometimes you need unmarshall only part of
     * tree. In that case you can use partial unmarshalling. To enable this
     * behaviours you need set property partClass. Camel will pass this class to
     * JAXB's unmarshaler.
     */
    private Boolean fragment = false;
    /**
     * Name of class used for fragment parsing. See more details at the fragment
     * option.
     */
    private String partClass;
    /**
     * XML namespace to use for fragment parsing. See more details at the
     * fragment option.
     */
    private String partNamespace;
    /**
     * When marshalling using JAXB or SOAP then the JAXB implementation will
     * automatic assign namespace prefixes such as ns2 ns3 ns4 etc. To control
     * this mapping Camel allows you to refer to a map which contains the
     * desired mapping.
     */
    private String namespacePrefixRef;
    /**
     * To use a custom xml stream writer.
     */
    private String xmlStreamWriterWrapper;
    /**
     * To define the location of the schema
     */
    private String schemaLocation;
    /**
     * To define the location of the namespaceless schema
     */
    private String noNamespaceSchemaLocation;
    /**
     * Refers to a custom java.util.Map to lookup in the registry containing
     * custom JAXB provider properties to be used with the JAXB marshaller.
     */
    private String jaxbProviderProperties;
    /**
     * Whether the data format should set the Content-Type header with the type
     * from the data format if the data format is capable of doing so. For
     * example application/xml for data formats marshalling to XML or
     * application/json for data formats marshalling to JSon etc.
     */
    private Boolean contentTypeHeader = false;

    public String getContextPath() {
        return contextPath;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    public String getSchema() {
        return schema;
    }

    public void setSchema(String schema) {
        this.schema = schema;
    }

    public Boolean getPrettyPrint() {
        return prettyPrint;
    }

    public void setPrettyPrint(Boolean prettyPrint) {
        this.prettyPrint = prettyPrint;
    }

    public Boolean getObjectFactory() {
        return objectFactory;
    }

    public void setObjectFactory(Boolean objectFactory) {
        this.objectFactory = objectFactory;
    }

    public Boolean getIgnoreJAXBElement() {
        return ignoreJAXBElement;
    }

    public void setIgnoreJAXBElement(Boolean ignoreJAXBElement) {
        this.ignoreJAXBElement = ignoreJAXBElement;
    }

    public Boolean getMustBeJAXBElement() {
        return mustBeJAXBElement;
    }

    public void setMustBeJAXBElement(Boolean mustBeJAXBElement) {
        this.mustBeJAXBElement = mustBeJAXBElement;
    }

    public Boolean getFilterNonXmlChars() {
        return filterNonXmlChars;
    }

    public void setFilterNonXmlChars(Boolean filterNonXmlChars) {
        this.filterNonXmlChars = filterNonXmlChars;
    }

    public String getEncoding() {
        return encoding;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public Boolean getFragment() {
        return fragment;
    }

    public void setFragment(Boolean fragment) {
        this.fragment = fragment;
    }

    public String getPartClass() {
        return partClass;
    }

    public void setPartClass(String partClass) {
        this.partClass = partClass;
    }

    public String getPartNamespace() {
        return partNamespace;
    }

    public void setPartNamespace(String partNamespace) {
        this.partNamespace = partNamespace;
    }

    public String getNamespacePrefixRef() {
        return namespacePrefixRef;
    }

    public void setNamespacePrefixRef(String namespacePrefixRef) {
        this.namespacePrefixRef = namespacePrefixRef;
    }

    public String getXmlStreamWriterWrapper() {
        return xmlStreamWriterWrapper;
    }

    public void setXmlStreamWriterWrapper(String xmlStreamWriterWrapper) {
        this.xmlStreamWriterWrapper = xmlStreamWriterWrapper;
    }

    public String getSchemaLocation() {
        return schemaLocation;
    }

    public void setSchemaLocation(String schemaLocation) {
        this.schemaLocation = schemaLocation;
    }

    public String getNoNamespaceSchemaLocation() {
        return noNamespaceSchemaLocation;
    }

    public void setNoNamespaceSchemaLocation(String noNamespaceSchemaLocation) {
        this.noNamespaceSchemaLocation = noNamespaceSchemaLocation;
    }

    public String getJaxbProviderProperties() {
        return jaxbProviderProperties;
    }

    public void setJaxbProviderProperties(String jaxbProviderProperties) {
        this.jaxbProviderProperties = jaxbProviderProperties;
    }

    public Boolean getContentTypeHeader() {
        return contentTypeHeader;
    }

    public void setContentTypeHeader(Boolean contentTypeHeader) {
        this.contentTypeHeader = contentTypeHeader;
    }
}


text:
class Node:
    def __init__(self, value):
        self._value = value
        self._next_node = None

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, x):
        self._value = x

    @property
    def next_node(self):
        return self._next_node

    @next_node.setter
    def next_node(self, node):
        self._next_node = node

class LinkedList:

    def __init__(self, val=None):
        if val:
            self._set_first(val)
        else:
            self._head = None
            self._tail = None
            self._length = 0

    def _set_first(self, val):
        self._head = Node(val)
        self._tail = self._head
        self._length = 1

    @property
    def tail(self):
        """

        :return: Returns the last node in the linked list
        :rtype: Node
        """
        return self._tail

    @tail.setter
    def tail(self, node):
        self._tail = node

    @property
    def head(self):
        """

        :return: Linked List Starting Value
        :rtype: Node
        """
        return self._head

    @head.setter
    def head(self, node):
        self._head = node

    def add(self, val):
        n = Node(val)
        if not self.head:
            self._set_first(val)
        else:
            self.tail.next_node = n
            self.tail = n
            self._length += 1

    def __len__(self):
        return self._length

def reverse_list(linked_list):
    current_node = linked_list.head
    prev_node = None
    while current_node is not None:
        t = current_node.next_node
        current_node.next_node = prev_node
        current_node, prev_node = t, current_node
    linked_list.head = prev_node
    return linked_list

def main():
    empty = LinkedList()
    print('LinkedList is empty', len(empty) == 0)
    one_node = LinkedList(2)
    print('Head and tail match and length is 1', one_node.head == one_node.tail and len(one_node) == 1)
    several_nodes = LinkedList()
    several_nodes.add(1)
    several_nodes.add(2)
    several_nodes.add(3)
    several_nodes.add(4)
    print('Length is 4', len(several_nodes) == 4)
    n = several_nodes.head
    while n is not None:
        print('Node val:', n.value)
        n = n.next_node
    reverse_list(several_nodes)
    n = several_nodes.head
    while n is not None:
        print('Node val:', n.value)
        n = n.next_node

if __name__ == '__main__':
    main()


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping default-lazy="false">

  <!-- Can't name the class user, clashes with postgres database -->
  <class name="org.olat.data.note.NoteImpl" table="o_note">

    <id name="key" column="note_id" type="long" unsaved-value="null">
      <generator class="hilo"/>
    </id>

	<version name="version" access="field" column="version" type="int"/>
	<property  name="lastModified" column="lastmodified" type="timestamp" />
	<property  name="creationDate" column="creationdate" type="timestamp" />

  	<many-to-one name="owner" class="org.olat.data.basesecurity.IdentityImpl" outer-join="auto" cascade="none">
		<column name="owner_id" not-null="false" index="owner_idx"/>
  	</many-to-one>

  	<property name="resourceTypeName"	type="string">
  		<column name="resourcetypename" length="50" not-null="true" index="restype_idx0"/>
  	</property>

    <property name="resourceTypeId"	type="long">
    	<column name="resourcetypeid" not-null="true" index="resid_idx2"/>
    </property>

	<property name="subtype" column="sub_type" unique="false" type="string" not-null="false" length="50"/>

    <property name="noteTitle" column="notetitle" unique="false" type="string" not-null="false" length="255"/>

    <property name="noteText" unique="false" type="string" not-null="false">
    	<column name="notetext" length="16777210"/>
	</property>

  </class>

</hibernate-mapping>


text:
#include "caffe2/core/context.h"
#include "caffe2/core/operator.h"
#include "caffe2/mkl/mkl_utils.h"

#ifdef CAFFE2_HAS_MKL_DNN

namespace caffe2 {
namespace mkl {

template <typename T>
class MKLFullyConnectedOp final : public MKLOperator<T> {
 public:
  MKLFullyConnectedOp(const OperatorDef& operator_def, Workspace* ws)
      : MKLOperator<T>(operator_def, ws),
        axis_(OperatorBase::GetSingleArgument<int32_t>("axis", 1)) {}
  ~MKLFullyConnectedOp() {}

  bool RunOnDevice() override {
    auto& X = OperatorBase::Input<MKLMemory<float>>(INPUT);
    auto& filter = OperatorBase::Input<MKLMemory<float>>(FILTER);
    auto& bias = OperatorBase::Input<MKLMemory<float>>(BIAS);
    MKLMemory<float>* Y = OperatorBase::Output<MKLMemory<float>>(0);

    CAFFE_ENFORCE(filter.ndim() == 2, filter.ndim());
    CAFFE_ENFORCE(bias.ndim() == 1, bias.ndim());

    bool dims_changed;
    CHECK_INPUT_FILTER_DIMS(X, filter, dims_changed);
    if (dims_changed || FLAGS_caffe2_mkl_memonger_in_use) {
      const int N = filter.dim32(0);
      CAFFE_ENFORCE(N == bias.dim32(0));

      auto Y_shape = X.dims();
      Y_shape[1] = N;
      Y_shape.resize(2);

      size_t inputSizes[4];
      if (X.ndim() == 2) {
        inputSizes[0] = X.dim32(1);
        inputSizes[1] = X.dim32(0);
      } else {
        CAFFE_ENFORCE(X.ndim(), 4);
        inputSizes[0] = X.dim32(3);
        inputSizes[1] = X.dim32(2);
        inputSizes[2] = X.dim32(1);
        inputSizes[3] = X.dim32(0);
      }

      size_t outputSizes[2] = {Y_shape[1], Y_shape[0]};

      primitive_.Reset(
          dnnInnerProductCreateForwardBias<float>,
          nullptr,
          X.ndim(),
          inputSizes,
          outputSizes[0]);

      Y->Reset(Y_shape, primitive_, dnnResourceDst);
      buffer_.Reset(Y_shape, primitive_, dnnResourceDst, true);

      input_layout_.Reset(primitive_, dnnResourceSrc);
      filter_layout_.Reset(primitive_, dnnResourceFilter);
    }

    // Try to share from the output: this allows us to avoid unnecessary copy
    // operations, if the output is already allocated and is having the same
    // layout as the buffer has.
    bool shared = buffer_.ShareFrom(*Y);

    std::shared_ptr<void> X_view =
        X.View(input_layout_, primitive_, dnnResourceSrc);
    std::shared_ptr<void> filter_view =
        filter.View(filter_layout_, primitive_, dnnResourceFilter);

    resources_[dnnResourceSrc] = X_view.get();
    resources_[dnnResourceFilter] = filter_view.get();

    resources_[dnnResourceBias] = bias.buffer();
    resources_[dnnResourceDst] = buffer_.buffer();

    MKLDNN_SAFE_CALL(mkl::dnnExecute<T>(primitive_, resources_));
    buffer_.CopyTo(Y, primitive_, dnnResourceDst);
    if (FLAGS_caffe2_mkl_memonger_in_use && !shared) {
      buffer_.Reset();
    }
    return true;
  }

 private:
  // Input: X, W, b
  // Output: Y
  size_t axis_{1};
  vector<TIndex> cached_input_dims_;
  vector<TIndex> cached_filter_dims_;
  PrimitiveWrapper<T> primitive_;
  LayoutWrapper<T> input_layout_;
  LayoutWrapper<T> filter_layout_;
  LayoutWrapper<T> bias_layout_;
  MKLMemory<T> buffer_;
  void* resources_[dnnResourceNumber] = {0};
  INPUT_TAGS(INPUT, FILTER, BIAS);
};

} // namespace mkl

REGISTER_MKL_OPERATOR(FC, mkl::MKLFullyConnectedOp<float>);

} // namespace caffe2

#endif // CAFFE2_HAS_MKL_DNN


text:
The jQuery plugin for equalizing the height or width of elements. The purpose of stacktable.js is to give you an easy way of converting wide tables to a format that will work better on small screens. It creates a copy of the table that is converted into a 2-column key/value format. For more info, go to [the project page](http://johnpolacek.github.com/stacktable.js).

[Follow me on Twitter](http://twitter.com/johnpolacek)

# Legal

Author & copyright (c) 2012: [John Polacek](http://johnpolacek.com)

Dual MIT & GPL license


text:
class UTrackSlider : public QWidget {
	Q_OBJECT

public:
	explicit UTrackSlider(QWidget *parent = 0);

signals:

public slots:

protected:
	void paintEvent(QPaintEvent *event) override;

private:
	int duration; // PERCENTAGE!
	int cue;
	int intro;
};

#endif // UTRACKSLIDER_H


text:
<?php

namespace Drupal\KernelTests\Core\RouteProcessor;

use Drupal\Core\Cache\Cache;
use Drupal\Core\GeneratedUrl;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;

/**
 * Tests the <current> route processor.
 *
 * @see \Drupal\Core\RouteProcessor\RouteProcessorCurrent
 * @group route_processor
 */
class RouteProcessorCurrentIntegrationTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = ['system'];

  /**
   * The URL generator.
   *
   * @var \Drupal\Core\Routing\UrlGeneratorInterface
   */
  protected $urlGenerator;

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

    $this->urlGenerator = \Drupal::urlGenerator();
  }

  /**
   * Tests the output process.
   */
  public function testProcessOutbound() {
    $expected_cacheability = (new BubbleableMetadata())
      ->addCacheContexts(['route'])
      ->setCacheMaxAge(Cache::PERMANENT);

    $request_stack = \Drupal::requestStack();
    /** @var \Symfony\Component\Routing\RequestContext $request_context */
    $request_context = \Drupal::service('router.request_context');

    // Test request with subdir on homepage.
    $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => \Drupal::root() . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/subdir/', 'GET', [], [], [], $server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));

    $request_stack->push($request);
    $request_context->fromRequest($request);
    $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/subdir/');
    $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));

    // Test request with subdir on other page.
    $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => \Drupal::root() . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/subdir/node/add', 'GET', [], [], [], $server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));

    $request_stack->push($request);
    $request_context->fromRequest($request);
    $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/subdir/node/add');
    $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));

    // Test request without subdir on the homepage.
    $server = [
      'SCRIPT_NAME' => '/index.php',
      'SCRIPT_FILENAME' => \Drupal::root() . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/', 'GET', [], [], [], $server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));

    $request_stack->push($request);
    $request_context->fromRequest($request);
    $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/');
    $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));

    // Test request without subdir on other page.
    $server = [
      'SCRIPT_NAME' => '/index.php',
      'SCRIPT_FILENAME' => \Drupal::root() . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/node/add', 'GET', [], [], [], $server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));

    $request_stack->push($request);
    $request_context->fromRequest($request);
    $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/node/add');
    $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));

    // Test request without a found route. This happens for example on an
    // not found exception page.
    $server = [
      'SCRIPT_NAME' => '/index.php',
      'SCRIPT_FILENAME' => \Drupal::root() . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/invalid-path', 'GET', [], [], [], $server);

    $request_stack->push($request);
    $request_context->fromRequest($request);
    // In case we have no routing, the current route should point to the front,
    // and the cacheability does not depend on the 'route' cache context, since
    // no route was involved at all: this is fallback behavior.
    $url = GeneratedUrl::createFromObject((new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT))->setGeneratedUrl('/');
    $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="concept" name="DC.Type" />
<meta name="DC.Title" content="Deadlocks" />
<meta name="abstract" content="In a database, a deadlock is a situation in which two or more transactions are waiting for one another to give up locks." />
<meta name="description" content="In a database, a deadlock is a situation in which two or more transactions are waiting for one another to give up locks." />
<meta content="deadlocks, description" name="DC.subject" />
<meta content="deadlocks, description" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts15366.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts22300.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts23810.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts36402.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts30291.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts53677.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts95005.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts89097.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts16400.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts50894.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts32861.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="cdevconcepts28436" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Deadlocks</title>

Deadlocks

In a database, a deadlock is a situation in which two or more transactions
are waiting for one another to give up locks.

For example, Transaction A might hold a lock on some rows in the Accounts table
and needs to update some rows in the Orders table to finish. Transaction
B holds locks on those very rows in the Orders table but needs to update
the rows in the Accounts table held by Transaction A. Transaction A
cannot complete its transaction because of the lock on Orders. Transaction
B cannot complete its transaction because of the lock on Accounts.
All activity comes to a halt and remains at a standstill forever unless the
DBMS detects the deadlock and aborts one of the transactions. The following
figure shows this situation.

Figure 1. A deadlock where two transactions are waiting
for one another to give up locks

Avoiding deadlocks

Using both row-level locking and the TRANSACTION_READ_COMMITTED isolation level makes it likely that you will avoid deadlocks (both settings are Derby defaults). However, deadlocks are still possible.

Deadlock detection

When a transaction waits more than a specific amount of time to obtain a lock (called the deadlock timeout), Derby can detect whether the transaction is involved in a deadlock.

Lock wait timeouts

Even if a transaction is not involved in a deadlock, it might have to wait a considerable amount of time to obtain a lock because of a long-running transaction or transactions holding locks on the tables it needs.

Configuring deadlock detection and lock wait timeouts

You configure the amount of time a transaction waits before Derby does any deadlock checking with the derby.locks.deadlockTimeout property.

Debugging deadlocks

If deadlocks occur frequently in your multi-user system with a particular application, you might need to do some debugging.

Programming applications to handle deadlocks

When you configure your system for deadlock and lockwait timeouts and an application could be chosen as a victim when the transaction times out, you should program your application to handle them.

Parent topic: Locking, concurrency, and isolation

Related concepts

Isolation levels and concurrency

Configuring isolation levels

Lock granularity

Types and scope of locks in Derby systems


text:
class CreateSnippets < ActiveRecord::Migration
  def change
    create_table :snippets do |t|
      t.string :title
      t.text :content
      t.integer :author_id, :null => false
      t.integer :project_id, :null => false

      t.timestamps
    end
  end
end


text:
Releases are managed using github's release feature. We use [Semantic Versioning](http://semver.org) for all
the releases. Every change made to the code base will be referred to in the release notes (except for
cleanups and refactorings).