text:
struct PV
{
	unsigned short px, py, pz;
	unsigned char nu, nv; // octahedron encoded normal, aliases .pw
	unsigned short tx, ty;
};

// note: 4 6 5 triangle here is a combo-breaker:
// we encode it without rotating, a=next, c=next - this means we do *not* bump next to 6
// which means that the next triangle can't be encoded via next sequencing!
static const unsigned int kIndexBuffer[] = {0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9};

static const unsigned char kIndexDataV0[] = {
    0xe0, 0xf0, 0x10, 0xfe, 0xff, 0xf0, 0x0c, 0xff, 0x02, 0x02, 0x02, 0x00, 0x76, 0x87, 0x56, 0x67,
    0x78, 0xa9, 0x86, 0x65, 0x89, 0x68, 0x98, 0x01, 0x69, 0x00, 0x00, // clang-format :-/
};

// note: this exercises two features of v1 format, restarts (0 1 2) and last
static const unsigned int kIndexBufferTricky[] = {0, 1, 2, 2, 1, 3, 0, 1, 2, 2, 1, 5, 2, 1, 4};

static const unsigned char kIndexDataV1[] = {
    0xe1, 0xf0, 0x10, 0xfe, 0x1f, 0x3d, 0x00, 0x0a, 0x00, 0x76, 0x87, 0x56, 0x67, 0x78, 0xa9, 0x86,
    0x65, 0x89, 0x68, 0x98, 0x01, 0x69, 0x00, 0x00, // clang-format :-/
};

static const unsigned int kIndexSequence[] = {0, 1, 51, 2, 49, 1000};

static const unsigned char kIndexSequenceV1[] = {
    0xd1, 0x00, 0x04, 0xcd, 0x01, 0x04, 0x07, 0x98, 0x1f, 0x00, 0x00, 0x00, 0x00, // clang-format :-/
};

static const PV kVertexBuffer[] = {
    {0, 0, 0, 0, 0, 0, 0},
    {300, 0, 0, 0, 0, 500, 0},
    {0, 300, 0, 0, 0, 0, 500},
    {300, 300, 0, 0, 0, 500, 500},
};

static const unsigned char kVertexDataV0[] = {
    0xa0, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x58, 0x57, 0x58, 0x01, 0x26, 0x00, 0x00, 0x00, 0x01,
    0x0c, 0x00, 0x00, 0x00, 0x58, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
    0x3f, 0x00, 0x00, 0x00, 0x17, 0x18, 0x17, 0x01, 0x26, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x00,
    0x00, 0x00, 0x17, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // clang-format :-/
};

static void decodeIndexV0()
{
	const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);

	std::vector<unsigned char> buffer(kIndexDataV0, kIndexDataV0 + sizeof(kIndexDataV0));

	unsigned int decoded[index_count];
	assert(meshopt_decodeIndexBuffer(decoded, index_count, &buffer[0], buffer.size()) == 0);
	assert(memcmp(decoded, kIndexBuffer, sizeof(kIndexBuffer)) == 0);
}

static void decodeIndexV1()
{
	const size_t index_count = sizeof(kIndexBufferTricky) / sizeof(kIndexBufferTricky[0]);

	std::vector<unsigned char> buffer(kIndexDataV1, kIndexDataV1 + sizeof(kIndexDataV1));

	unsigned int decoded[index_count];
	assert(meshopt_decodeIndexBuffer(decoded, index_count, &buffer[0], buffer.size()) == 0);
	assert(memcmp(decoded, kIndexBufferTricky, sizeof(kIndexBufferTricky)) == 0);
}

static void decodeIndex16()
{
	const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
	const size_t vertex_count = 10;

	std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));

	unsigned short decoded[index_count];
	assert(meshopt_decodeIndexBuffer(decoded, index_count, &buffer[0], buffer.size()) == 0);

	for (size_t i = 0; i < index_count; ++i)
		assert(decoded[i] == kIndexBuffer[i]);
}

static void encodeIndexMemorySafe()
{
	const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
	const size_t vertex_count = 10;

	std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));

	// check that encode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
	for (size_t i = 0; i <= buffer.size(); ++i)
	{
		std::vector<unsigned char> shortbuffer(i);
		size_t result = meshopt_encodeIndexBuffer(i == 0 ? 0 : &shortbuffer[0], i, kIndexBuffer, index_count);

		if (i == buffer.size())
			assert(result == buffer.size());
		else
			assert(result == 0);
	}
}

static void decodeIndexMemorySafe()
{
	const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
	const size_t vertex_count = 10;

	std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));

	// check that decode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
	unsigned int decoded[index_count];

	for (size_t i = 0; i <= buffer.size(); ++i)
	{
		std::vector<unsigned char> shortbuffer(buffer.begin(), buffer.begin() + i);
		int result = meshopt_decodeIndexBuffer(decoded, index_count, i == 0 ? 0 : &shortbuffer[0], i);

		if (i == buffer.size())
			assert(result == 0);
		else
			assert(result < 0);
	}
}

static void decodeIndexRejectExtraBytes()
{
	const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
	const size_t vertex_count = 10;

	std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));

	// check that decoder doesn't accept extra bytes after a valid stream
	std::vector<unsigned char> largebuffer(buffer);
	largebuffer.push_back(0);

	unsigned int decoded[index_count];
	assert(meshopt_decodeIndexBuffer(decoded, index_count, &largebuffer[0], largebuffer.size()) < 0);
}

static void decodeIndexRejectMalformedHeaders()
{
	const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
	const size_t vertex_count = 10;

	std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));

	// check that decoder doesn't accept malformed headers
	std::vector<unsigned char> brokenbuffer(buffer);
	brokenbuffer[0] = 0;

	unsigned int decoded[index_count];
	assert(meshopt_decodeIndexBuffer(decoded, index_count, &brokenbuffer[0], brokenbuffer.size()) < 0);
}

static void decodeIndexRejectInvalidVersion()
{
	const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
	const size_t vertex_count = 10;

	std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));

	// check that decoder doesn't accept invalid version
	std::vector<unsigned char> brokenbuffer(buffer);
	brokenbuffer[0] |= 0x0f;

	unsigned int decoded[index_count];
	assert(meshopt_decodeIndexBuffer(decoded, index_count, &brokenbuffer[0], brokenbuffer.size()) < 0);
}

static void decodeIndexMalformedVByte()
{
	const unsigned char input[] = {
	    0xe1, 0x20, 0x20, 0x20, 0xff, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
	    0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
	    0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
	    0x20, 0x20, 0x20, // clang-format :-/
	};

	unsigned int decoded[66];
	assert(meshopt_decodeIndexBuffer(decoded, 66, input, sizeof(input)) < 0);
}

static void roundtripIndexTricky()
{
	const size_t index_count = sizeof(kIndexBufferTricky) / sizeof(kIndexBufferTricky[0]);
	const size_t vertex_count = 6;

	std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBufferTricky, index_count));

	unsigned int decoded[index_count];
	assert(meshopt_decodeIndexBuffer(decoded, index_count, &buffer[0], buffer.size()) == 0);
	assert(memcmp(decoded, kIndexBufferTricky, sizeof(kIndexBufferTricky)) == 0);
}

static void encodeIndexEmpty()
{
	std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(0, 0));
	buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), NULL, 0));

	assert(meshopt_decodeIndexBuffer(static_cast<unsigned int*>(NULL), 0, &buffer[0], buffer.size()) == 0);
}

static void decodeIndexSequence()
{
	const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);

	std::vector<unsigned char> buffer(kIndexSequenceV1, kIndexSequenceV1 + sizeof(kIndexSequenceV1));

	unsigned int decoded[index_count];
	assert(meshopt_decodeIndexSequence(decoded, index_count, &buffer[0], buffer.size()) == 0);
	assert(memcmp(decoded, kIndexSequence, sizeof(kIndexSequence)) == 0);
}

static void decodeIndexSequence16()
{
	const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
	const size_t vertex_count = 1001;

	std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));

	unsigned short decoded[index_count];
	assert(meshopt_decodeIndexSequence(decoded, index_count, &buffer[0], buffer.size()) == 0);

	for (size_t i = 0; i < index_count; ++i)
		assert(decoded[i] == kIndexSequence[i]);
}

static void encodeIndexSequenceMemorySafe()
{
	const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
	const size_t vertex_count = 1001;

	std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));

	// check that encode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
	for (size_t i = 0; i <= buffer.size(); ++i)
	{
		std::vector<unsigned char> shortbuffer(i);
		size_t result = meshopt_encodeIndexSequence(i == 0 ? 0 : &shortbuffer[0], i, kIndexSequence, index_count);

		if (i == buffer.size())
			assert(result == buffer.size());
		else
			assert(result == 0);
	}
}

static void decodeIndexSequenceMemorySafe()
{
	const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
	const size_t vertex_count = 1001;

	std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));

	// check that decode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
	unsigned int decoded[index_count];

	for (size_t i = 0; i <= buffer.size(); ++i)
	{
		std::vector<unsigned char> shortbuffer(buffer.begin(), buffer.begin() + i);
		int result = meshopt_decodeIndexSequence(decoded, index_count, i == 0 ? 0 : &shortbuffer[0], i);

		if (i == buffer.size())
			assert(result == 0);
		else
			assert(result < 0);
	}
}

static void decodeIndexSequenceRejectExtraBytes()
{
	const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
	const size_t vertex_count = 1001;

	std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));

	// check that decoder doesn't accept extra bytes after a valid stream
	std::vector<unsigned char> largebuffer(buffer);
	largebuffer.push_back(0);

	unsigned int decoded[index_count];
	assert(meshopt_decodeIndexSequence(decoded, index_count, &largebuffer[0], largebuffer.size()) < 0);
}

static void decodeIndexSequenceRejectMalformedHeaders()
{
	const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
	const size_t vertex_count = 1001;

	std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));

	// check that decoder doesn't accept malformed headers
	std::vector<unsigned char> brokenbuffer(buffer);
	brokenbuffer[0] = 0;

	unsigned int decoded[index_count];
	assert(meshopt_decodeIndexSequence(decoded, index_count, &brokenbuffer[0], brokenbuffer.size()) < 0);
}

static void decodeIndexSequenceRejectInvalidVersion()
{
	const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
	const size_t vertex_count = 1001;

	std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
	buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));

	// check that decoder doesn't accept invalid version
	std::vector<unsigned char> brokenbuffer(buffer);
	brokenbuffer[0] |= 0x0f;

	unsigned int decoded[index_count];
	assert(meshopt_decodeIndexSequence(decoded, index_count, &brokenbuffer[0], brokenbuffer.size()) < 0);
}

static void encodeIndexSequenceEmpty()
{
	std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(0, 0));
	buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), NULL, 0));

	assert(meshopt_decodeIndexSequence(static_cast<unsigned int*>(NULL), 0, &buffer[0], buffer.size()) == 0);
}

static void decodeVertexV0()
{
	const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);

	std::vector<unsigned char> buffer(kVertexDataV0, kVertexDataV0 + sizeof(kVertexDataV0));

	PV decoded[vertex_count];
	assert(meshopt_decodeVertexBuffer(decoded, vertex_count, sizeof(PV), &buffer[0], buffer.size()) == 0);
	assert(memcmp(decoded, kVertexBuffer, sizeof(kVertexBuffer)) == 0);
}

static void encodeVertexMemorySafe()
{
	const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);

	std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(vertex_count, sizeof(PV)));
	buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), kVertexBuffer, vertex_count, sizeof(PV)));

	// check that encode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
	for (size_t i = 0; i <= buffer.size(); ++i)
	{
		std::vector<unsigned char> shortbuffer(i);
		size_t result = meshopt_encodeVertexBuffer(i == 0 ? 0 : &shortbuffer[0], i, kVertexBuffer, vertex_count, sizeof(PV));

		if (i == buffer.size())
			assert(result == buffer.size());
		else
			assert(result == 0);
	}
}

static void decodeVertexMemorySafe()
{
	const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);

	std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(vertex_count, sizeof(PV)));
	buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), kVertexBuffer, vertex_count, sizeof(PV)));

	// check that decode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
	PV decoded[vertex_count];

	for (size_t i = 0; i <= buffer.size(); ++i)
	{
		std::vector<unsigned char> shortbuffer(buffer.begin(), buffer.begin() + i);
		int result = meshopt_decodeVertexBuffer(decoded, vertex_count, sizeof(PV), i == 0 ? 0 : &shortbuffer[0], i);
		(void)result;

		if (i == buffer.size())
			assert(result == 0);
		else
			assert(result < 0);
	}
}

static void decodeVertexRejectExtraBytes()
{
	const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);

	std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(vertex_count, sizeof(PV)));
	buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), kVertexBuffer, vertex_count, sizeof(PV)));

	// check that decoder doesn't accept extra bytes after a valid stream
	std::vector<unsigned char> largebuffer(buffer);
	largebuffer.push_back(0);

	PV decoded[vertex_count];
	assert(meshopt_decodeVertexBuffer(decoded, vertex_count, sizeof(PV), &largebuffer[0], largebuffer.size()) < 0);
}

static void decodeVertexRejectMalformedHeaders()
{
	const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);

	std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(vertex_count, sizeof(PV)));
	buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), kVertexBuffer, vertex_count, sizeof(PV)));

	// check that decoder doesn't accept malformed headers
	std::vector<unsigned char> brokenbuffer(buffer);
	brokenbuffer[0] = 0;

	PV decoded[vertex_count];
	assert(meshopt_decodeVertexBuffer(decoded, vertex_count, sizeof(PV), &brokenbuffer[0], brokenbuffer.size()) < 0);
}

static void decodeVertexBitGroups()
{
	unsigned char data[16 * 4];

	// this tests 0/2/4/8 bit groups in one stream
	for (size_t i = 0; i < 16; ++i)
	{
		data[i * 4 + 0] = 0;
		data[i * 4 + 1] = (unsigned char)(i * 1);
		data[i * 4 + 2] = (unsigned char)(i * 2);
		data[i * 4 + 3] = (unsigned char)(i * 8);
	}

	std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(16, 4));
	buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), data, 16, 4));

	unsigned char decoded[16 * 4];
	assert(meshopt_decodeVertexBuffer(decoded, 16, 4, &buffer[0], buffer.size()) == 0);
	assert(memcmp(decoded, data, sizeof(data)) == 0);
}

static void decodeVertexBitGroupSentinels()
{
	unsigned char data[16 * 4];

	// this tests 0/2/4/8 bit groups and sentinels in one stream
	for (size_t i = 0; i < 16; ++i)
	{
		if (i == 7 || i == 13)
		{
			data[i * 4 + 0] = 42;
			data[i * 4 + 1] = 42;
			data[i * 4 + 2] = 42;
			data[i * 4 + 3] = 42;
		}
		else
		{
			data[i * 4 + 0] = 0;
			data[i * 4 + 1] = (unsigned char)(i * 1);
			data[i * 4 + 2] = (unsigned char)(i * 2);
			data[i * 4 + 3] = (unsigned char)(i * 8);
		}
	}

	std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(16, 4));
	buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), data, 16, 4));

	unsigned char decoded[16 * 4];
	assert(meshopt_decodeVertexBuffer(decoded, 16, 4, &buffer[0], buffer.size()) == 0);
	assert(memcmp(decoded, data, sizeof(data)) == 0);
}

static void decodeVertexLarge()
{
	unsigned char data[128 * 4];

	// this tests 0/2/4/8 bit groups in one stream
	for (size_t i = 0; i < 128; ++i)
	{
		data[i * 4 + 0] = 0;
		data[i * 4 + 1] = (unsigned char)(i * 1);
		data[i * 4 + 2] = (unsigned char)(i * 2);
		data[i * 4 + 3] = (unsigned char)(i * 8);
	}

	std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(128, 4));
	buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), data, 128, 4));

	unsigned char decoded[128 * 4];
	assert(meshopt_decodeVertexBuffer(decoded, 128, 4, &buffer[0], buffer.size()) == 0);
	assert(memcmp(decoded, data, sizeof(data)) == 0);
}

static void encodeVertexEmpty()
{
	std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(0, 16));
	buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), NULL, 0, 16));

	assert(meshopt_decodeVertexBuffer(NULL, 0, 16, &buffer[0], buffer.size()) == 0);
}

static void decodeFilterOct8()
{
	const unsigned char data[4 * 4] = {
	    0, 1, 127, 0,
	    0, 187, 127, 1,
	    255, 1, 127, 0,
	    14, 130, 127, 1, // clang-format :-/
	};

	const unsigned char expected[4 * 4] = {
	    0, 1, 127, 0,
	    0, 159, 82, 1,
	    255, 1, 127, 0,
	    1, 130, 241, 1, // clang-format :-/
	};

	// Aligned by 4
	unsigned char full[4 * 4];
	memcpy(full, data, sizeof(full));
	meshopt_decodeFilterOct(full, 4, 4);
	assert(memcmp(full, expected, sizeof(full)) == 0);

	// Tail processing for unaligned data
	unsigned char tail[3 * 4];
	memcpy(tail, data, sizeof(tail));
	meshopt_decodeFilterOct(tail, 3, 4);
	assert(memcmp(tail, expected, sizeof(tail)) == 0);
}

static void decodeFilterOct12()
{
	const unsigned short data[4 * 4] = {
	    0, 1, 2047, 0,
	    0, 1870, 2047, 1,
	    2017, 1, 2047, 0,
	    14, 1300, 2047, 1, // clang-format :-/
	};

	const unsigned short expected[4 * 4] = {
	    0, 16, 32767, 0,
	    0, 32621, 3088, 1,
	    32764, 16, 471, 0,
	    307, 28541, 16093, 1, // clang-format :-/
	};

	// Aligned by 4
	unsigned short full[4 * 4];
	memcpy(full, data, sizeof(full));
	meshopt_decodeFilterOct(full, 4, 8);
	assert(memcmp(full, expected, sizeof(full)) == 0);

	// Tail processing for unaligned data
	unsigned short tail[3 * 4];
	memcpy(tail, data, sizeof(tail));
	meshopt_decodeFilterOct(tail, 3, 8);
	assert(memcmp(tail, expected, sizeof(tail)) == 0);
}

static void decodeFilterQuat12()
{
	const unsigned short data[4 * 4] = {
	    0, 1, 0, 0x7fc,
	    0, 1870, 0, 0x7fd,
	    2017, 1, 0, 0x7fe,
	    14, 1300, 0, 0x7ff, // clang-format :-/
	};

	const unsigned short expected[4 * 4] = {
	    32767, 0, 11, 0,
	    0, 25013, 0, 21166,
	    11, 0, 23504, 22830,
	    158, 14715, 0, 29277, // clang-format :-/
	};

	// Aligned by 4
	unsigned short full[4 * 4];
	memcpy(full, data, sizeof(full));
	meshopt_decodeFilterQuat(full, 4, 8);
	assert(memcmp(full, expected, sizeof(full)) == 0);

	// Tail processing for unaligned data
	unsigned short tail[3 * 4];
	memcpy(tail, data, sizeof(tail));
	meshopt_decodeFilterQuat(tail, 3, 8);
	assert(memcmp(tail, expected, sizeof(tail)) == 0);
}

static void decodeFilterExp()
{
	const unsigned int data[4] = {
	    0,
	    0xff000003,
	    0x02fffff7,
	    0xfe7fffff, // clang-format :-/
	};

	const unsigned int expected[4] = {
	    0,
	    0x3fc00000,
	    0xc2100000,
	    0x49fffffe, // clang-format :-/
	};

	// Aligned by 4
	unsigned int full[4];
	memcpy(full, data, sizeof(full));
	meshopt_decodeFilterExp(full, 4, 4);
	assert(memcmp(full, expected, sizeof(full)) == 0);

	// Tail processing for unaligned data
	unsigned int tail[3];
	memcpy(tail, data, sizeof(tail));
	meshopt_decodeFilterExp(tail, 3, 4);
	assert(memcmp(tail, expected, sizeof(tail)) == 0);
}

void encodeFilterOct8()
{
	const float data[4 * 4] = {
	    1, 0, 0, 0,
	    0, -1, 0, 0,
	    0.7071068f, 0, 0.707168f, 1,
	    -0.7071068f, 0, -0.707168f, 1, // clang-format :-/
	};

	const unsigned char expected[4 * 4] = {
	    0x7f, 0, 0x7f, 0,
	    0, 0x81, 0x7f, 0,
	    0x3f, 0, 0x7f, 0x7f,
	    0x81, 0x40, 0x7f, 0x7f, // clang-format :-/
	};

	unsigned char encoded[4 * 4];
	meshopt_encodeFilterOct(encoded, 4, 4, 8, data);

	assert(memcmp(encoded, expected, sizeof(expected)) == 0);

	signed char decoded[4 * 4];
	memcpy(decoded, encoded, sizeof(decoded));
	meshopt_decodeFilterOct(decoded, 4, 4);

	for (size_t i = 0; i < 4 * 4; ++i)
		assert(fabsf(decoded[i] / 127.f - data[i]) < 1e-2f);
}

void encodeFilterOct12()
{
	const float data[4 * 4] = {
	    1, 0, 0, 0,
	    0, -1, 0, 0,
	    0.7071068f, 0, 0.707168f, 1,
	    -0.7071068f, 0, -0.707168f, 1, // clang-format :-/
	};

	const unsigned short expected[4 * 4] = {
	    0x7ff, 0, 0x7ff, 0,
	    0x0, 0xf801, 0x7ff, 0,
	    0x3ff, 0, 0x7ff, 0x7fff,
	    0xf801, 0x400, 0x7ff, 0x7fff, // clang-format :-/
	};

	unsigned short encoded[4 * 4];
	meshopt_encodeFilterOct(encoded, 4, 8, 12, data);

	assert(memcmp(encoded, expected, sizeof(expected)) == 0);

	short decoded[4 * 4];
	memcpy(decoded, encoded, sizeof(decoded));
	meshopt_decodeFilterOct(decoded, 4, 8);

	for (size_t i = 0; i < 4 * 4; ++i)
		assert(fabsf(decoded[i] / 32767.f - data[i]) < 1e-3f);
}

void encodeFilterQuat12()
{
	const float data[4 * 4] = {
	    1, 0, 0, 0,
	    0, -1, 0, 0,
	    0.7071068f, 0, 0, 0.707168f,
	    -0.7071068f, 0, 0, -0.707168f, // clang-format :-/
	};

	const unsigned short expected[4 * 4] = {
	    0, 0, 0, 0x7fc,
	    0, 0, 0, 0x7fd,
	    0x7ff, 0, 0, 0x7ff,
	    0x7ff, 0, 0, 0x7ff, // clang-format :-/
	};

	unsigned short encoded[4 * 4];
	meshopt_encodeFilterQuat(encoded, 4, 8, 12, data);

	assert(memcmp(encoded, expected, sizeof(expected)) == 0);

	short decoded[4 * 4];
	memcpy(decoded, encoded, sizeof(decoded));
	meshopt_decodeFilterQuat(decoded, 4, 8);

	for (size_t i = 0; i < 4; ++i)
	{
		float dx = decoded[i * 4 + 0] / 32767.f;
		float dy = decoded[i * 4 + 1] / 32767.f;
		float dz = decoded[i * 4 + 2] / 32767.f;
		float dw = decoded[i * 4 + 3] / 32767.f;

		float dp =
		    data[i * 4 + 0] * dx +
		    data[i * 4 + 1] * dy +
		    data[i * 4 + 2] * dz +
		    data[i * 4 + 3] * dw;

		assert(fabsf(fabsf(dp) - 1.f) < 1e-4f);
	}
}

void encodeFilterExp()
{
	const float data[3] = {
	    1,
	    -23.4f,
	    -0.1f,
	};

	const unsigned int expected[3] = {
	    0xf7000200,
	    0xf7ffd133,
	    0xf7ffffcd,
	};

	unsigned int encoded[3];
	meshopt_encodeFilterExp(encoded, 1, 12, 15, data);

	assert(memcmp(encoded, expected, sizeof(expected)) == 0);

	float decoded[3];
	memcpy(decoded, encoded, sizeof(decoded));
	meshopt_decodeFilterExp(decoded, 3, 4);

	for (size_t i = 0; i < 3; ++i)
		assert(fabsf(decoded[i] - data[i]) < 1e-3f);
}

static void clusterBoundsDegenerate()
{
	const float vbd[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
	const unsigned int ibd[] = {0, 0, 0};
	const unsigned int ib1[] = {0, 1, 2};

	// all of the bounds below are degenerate as they use 0 triangles, one topology-degenerate triangle and one position-degenerate triangle respectively
	meshopt_Bounds bounds0 = meshopt_computeClusterBounds(0, 0, 0, 0, 12);
	meshopt_Bounds boundsd = meshopt_computeClusterBounds(ibd, 3, vbd, 3, 12);
	meshopt_Bounds bounds1 = meshopt_computeClusterBounds(ib1, 3, vbd, 3, 12);

	assert(bounds0.center[0] == 0 && bounds0.center[1] == 0 && bounds0.center[2] == 0 && bounds0.radius == 0);
	assert(boundsd.center[0] == 0 && boundsd.center[1] == 0 && boundsd.center[2] == 0 && boundsd.radius == 0);
	assert(bounds1.center[0] == 0 && bounds1.center[1] == 0 && bounds1.center[2] == 0 && bounds1.radius == 0);

	const float vb1[] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
	const unsigned int ib2[] = {0, 1, 2, 0, 2, 1};

	// these bounds have a degenerate cone since the cluster has two triangles with opposite normals
	meshopt_Bounds bounds2 = meshopt_computeClusterBounds(ib2, 6, vb1, 3, 12);

	assert(bounds2.cone_apex[0] == 0 && bounds2.cone_apex[1] == 0 && bounds2.cone_apex[2] == 0);
	assert(bounds2.cone_axis[0] == 0 && bounds2.cone_axis[1] == 0 && bounds2.cone_axis[2] == 0);
	assert(bounds2.cone_cutoff == 1);
	assert(bounds2.cone_axis_s8[0] == 0 && bounds2.cone_axis_s8[1] == 0 && bounds2.cone_axis_s8[2] == 0);
	assert(bounds2.cone_cutoff_s8 == 127);

	// however, the bounding sphere needs to be in tact (here we only check bbox for simplicity)
	assert(bounds2.center[0] - bounds2.radius <= 0 && bounds2.center[0] + bounds2.radius >= 1);
	assert(bounds2.center[1] - bounds2.radius <= 0 && bounds2.center[1] + bounds2.radius >= 1);
	assert(bounds2.center[2] - bounds2.radius <= 0 && bounds2.center[2] + bounds2.radius >= 1);
}

static size_t allocCount;
static size_t freeCount;

static void* customAlloc(size_t size)
{
	allocCount++;

	return malloc(size);
}

static void customFree(void* ptr)
{
	freeCount++;

	free(ptr);
}

static void customAllocator()
{
	meshopt_setAllocator(customAlloc, customFree);

	assert(allocCount == 0 && freeCount == 0);

	float vb[] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
	unsigned int ib[] = {0, 1, 2};
	unsigned short ibs[] = {0, 1, 2};

	// meshopt_computeClusterBounds doesn't allocate
	meshopt_computeClusterBounds(ib, 3, vb, 3, 12);
	assert(allocCount == 0 && freeCount == 0);

	// ... unless IndexAdapter is used
	meshopt_computeClusterBounds(ibs, 3, vb, 3, 12);
	assert(allocCount == 1 && freeCount == 1);

	// meshopt_optimizeVertexFetch allocates internal remap table and temporary storage for in-place remaps
	meshopt_optimizeVertexFetch(vb, ib, 3, vb, 3, 12);
	assert(allocCount == 3 && freeCount == 3);

	// ... plus one for IndexAdapter
	meshopt_optimizeVertexFetch(vb, ibs, 3, vb, 3, 12);
	assert(allocCount == 6 && freeCount == 6);

	meshopt_setAllocator(operator new, operator delete);

	// customAlloc & customFree should not get called anymore
	meshopt_optimizeVertexFetch(vb, ib, 3, vb, 3, 12);
	assert(allocCount == 6 && freeCount == 6);

	allocCount = freeCount = 0;
}

static void emptyMesh()
{
	meshopt_optimizeVertexCache(0, 0, 0, 0);
	meshopt_optimizeVertexCacheFifo(0, 0, 0, 0, 16);
	meshopt_optimizeOverdraw(0, 0, 0, 0, 0, 12, 1.f);
}

static void simplifyStuck()
{
	// tetrahedron can't be simplified due to collapse error restrictions
	float vb1[] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1};
	unsigned int ib1[] = {0, 1, 2, 0, 2, 3, 0, 3, 1, 2, 1, 3};

	assert(meshopt_simplify(ib1, ib1, 12, vb1, 4, 12, 6, 1e-3f) == 12);

	// 5-vertex strip can't be simplified due to topology restriction since middle triangle has flipped winding
	float vb2[] = {0, 0, 0, 1, 0, 0, 2, 0, 0, 0.5f, 1, 0, 1.5f, 1, 0};
	unsigned int ib2[] = {0, 1, 3, 3, 1, 4, 1, 2, 4}; // ok
	unsigned int ib3[] = {0, 1, 3, 1, 3, 4, 1, 2, 4}; // flipped

	assert(meshopt_simplify(ib2, ib2, 9, vb2, 5, 12, 6, 1e-3f) == 6);
	assert(meshopt_simplify(ib3, ib3, 9, vb2, 5, 12, 6, 1e-3f) == 9);

	// 4-vertex quad with a locked corner can't be simplified due to border error-induced restriction
	float vb4[] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0};
	unsigned int ib4[] = {0, 1, 3, 0, 3, 2};

	assert(meshopt_simplify(ib4, ib4, 6, vb4, 4, 12, 3, 1e-3f) == 6);

	// 4-vertex quad with a locked corner can't be simplified due to border error-induced restriction
	float vb5[] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0};
	unsigned int ib5[] = {0, 1, 4, 0, 3, 2};

	assert(meshopt_simplify(ib5, ib5, 6, vb5, 5, 12, 3, 1e-3f) == 6);
}

static void simplifySloppyStuck()
{
	const float vb[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
	const unsigned int ib[] = {0, 1, 2, 0, 1, 2};

	unsigned int* target = NULL;

	// simplifying down to 0 triangles results in 0 immediately
	assert(meshopt_simplifySloppy(target, ib, 3, vb, 3, 12, 0, 0.f) == 0);

	// simplifying down to 2 triangles given that all triangles are degenerate results in 0 as well
	assert(meshopt_simplifySloppy(target, ib, 6, vb, 3, 12, 6, 0.f) == 0);
}

static void simplifyPointsStuck()
{
	const float vb[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};

	// simplifying down to 0 points results in 0 immediately
	assert(meshopt_simplifyPoints(0, vb, 3, 12, 0) == 0);
}

static void simplifyFlip()
{
	// this mesh has been constructed by taking a tessellated irregular grid with a square cutout
	// and progressively collapsing edges until the only ones left violate border or flip constraints.
	// there is only one valid non-flip collapse, so we validate that we take it; when flips are allowed,
	// the wrong collapse is picked instead.
	float vb[] = {
	    1.000000f, 1.000000f, -1.000000f,
	    1.000000f, 1.000000f, 1.000000f,
	    1.000000f, -1.000000f, 1.000000f,
	    1.000000f, -0.200000f, -0.200000f,
	    1.000000f, 0.200000f, -0.200000f,
	    1.000000f, -0.200000f, 0.200000f,
	    1.000000f, 0.200000f, 0.200000f,
	    1.000000f, 0.500000f, -0.500000f,
	    1.000000f, -1.000000f, 0.000000f, // clang-format :-/
	};

	// the collapse we expect is 7 -> 0
	unsigned int ib[] = {
	    7, 4, 3,
	    1, 2, 5,
	    7, 1, 6,
	    7, 8, 0, // gets removed
	    7, 6, 4,
	    8, 5, 2,
	    8, 7, 3,
	    8, 3, 5,
	    5, 6, 1,
	    7, 0, 1, // gets removed
	};

	unsigned int expected[] = {
	    0, 4, 3,
	    1, 2, 5,
	    0, 1, 6,
	    0, 6, 4,
	    8, 5, 2,
	    8, 0, 3,
	    8, 3, 5,
	    5, 6, 1, // clang-format :-/
	};

	assert(meshopt_simplify(ib, ib, 30, vb, 9, 12, 3, 1e-3f) == 24);
	assert(memcmp(ib, expected, sizeof(expected)) == 0);
}

static void simplifyScale()
{
	const float vb[] = {0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3};

	assert(meshopt_simplifyScale(vb, 4, 12) == 3.f);
}

static void simplifyDegenerate()
{
	float vb[] = {
	    0.000000f, 0.000000f, 0.000000f,
	    0.000000f, 1.000000f, 0.000000f,
	    0.000000f, 2.000000f, 0.000000f,
	    1.000000f, 0.000000f, 0.000000f,
	    2.000000f, 0.000000f, 0.000000f,
	    1.000000f, 1.000000f, 0.000000f, // clang-format :-/
	};

	// 0 1 2
	// 3 5
	// 4

	unsigned int ib[] = {
	    0, 1, 3,
	    3, 1, 5,
	    1, 2, 5,
	    3, 5, 4,
	    1, 0, 1, // these two degenerate triangles create a fake reverse edge
	    0, 3, 0, // which breaks border classification
	};

	unsigned int expected[] = {
	    0, 1, 4,
	    4, 1, 2, // clang-format :-/
	};

	assert(meshopt_simplify(ib, ib, 18, vb, 6, 12, 3, 1e-3f) == 6);
	assert(memcmp(ib, expected, sizeof(expected)) == 0);
}

static void simplifyLockBorder()
{
	float vb[] = {
	    0.000000f, 0.000000f, 0.000000f,
	    0.000000f, 1.000000f, 0.000000f,
	    0.000000f, 2.000000f, 0.000000f,
	    1.000000f, 0.000000f, 0.000000f,
	    1.000000f, 1.000000f, 0.000000f,
	    1.000000f, 2.000000f, 0.000000f,
	    2.000000f, 0.000000f, 0.000000f,
	    2.000000f, 1.000000f, 0.000000f,
	    2.000000f, 2.000000f, 0.000000f, // clang-format :-/
	};

	// 0 1 2
	// 3 4 5
	// 6 7 8

	unsigned int ib[] = {
	    0, 1, 3,
	    3, 1, 4,
	    1, 2, 4,
	    4, 2, 5,
	    3, 4, 6,
	    6, 4, 7,
	    4, 5, 7,
	    7, 5, 8, // clang-format :-/
	};

	unsigned int expected[] = {
	    0, 1, 3,
	    1, 2, 3,
	    3, 2, 5,
	    6, 3, 7,
	    3, 5, 7,
	    7, 5, 8, // clang-format :-/
	};

	assert(meshopt_simplify(ib, ib, 24, vb, 9, 12, 3, 1e-3f, meshopt_SimplifyLockBorder) == 18);
	assert(memcmp(ib, expected, sizeof(expected)) == 0);
}

static void adjacency()
{
	// 0 1/4
	// 2/5 3
	const float vb[] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0};
	const unsigned int ib[] = {0, 1, 2, 5, 4, 3};

	unsigned int adjib[12];
	meshopt_generateAdjacencyIndexBuffer(adjib, ib, 6, vb, 6, 12);

	unsigned int expected[] = {
	    // patch 0
	    0, 0,
	    1, 3,
	    2, 2,

	    // patch 1
	    5, 0,
	    4, 4,
	    3, 3,

	    // clang-format :-/
	};

	assert(memcmp(adjib, expected, sizeof(expected)) == 0);
}

static void tessellation()
{
	// 0 1/4
	// 2/5 3
	const float vb[] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0};
	const unsigned int ib[] = {0, 1, 2, 5, 4, 3};

	unsigned int tessib[24];
	meshopt_generateTessellationIndexBuffer(tessib, ib, 6, vb, 6, 12);

	unsigned int expected[] = {
	    // patch 0
	    0, 1, 2,
	    0, 1,
	    4, 5,
	    2, 0,
	    0, 1, 2,

	    // patch 1
	    5, 4, 3,
	    2, 1,
	    4, 3,
	    3, 5,
	    2, 1, 3,

	    // clang-format :-/
	};

	assert(memcmp(tessib, expected, sizeof(expected)) == 0);
}

void runTests()
{
	decodeIndexV0();
	decodeIndexV1();
	decodeIndex16();
	encodeIndexMemorySafe();
	decodeIndexMemorySafe();
	decodeIndexRejectExtraBytes();
	decodeIndexRejectMalformedHeaders();
	decodeIndexRejectInvalidVersion();
	decodeIndexMalformedVByte();
	roundtripIndexTricky();
	encodeIndexEmpty();

	decodeIndexSequence();
	decodeIndexSequence16();
	encodeIndexSequenceMemorySafe();
	decodeIndexSequenceMemorySafe();
	decodeIndexSequenceRejectExtraBytes();
	decodeIndexSequenceRejectMalformedHeaders();
	decodeIndexSequenceRejectInvalidVersion();
	encodeIndexSequenceEmpty();

	decodeVertexV0();
	encodeVertexMemorySafe();
	decodeVertexMemorySafe();
	decodeVertexRejectExtraBytes();
	decodeVertexRejectMalformedHeaders();
	decodeVertexBitGroups();
	decodeVertexBitGroupSentinels();
	decodeVertexLarge();
	encodeVertexEmpty();

	decodeFilterOct8();
	decodeFilterOct12();
	decodeFilterQuat12();
	decodeFilterExp();

	encodeFilterOct8();
	encodeFilterOct12();
	encodeFilterQuat12();
	encodeFilterExp();

	clusterBoundsDegenerate();

	customAllocator();

	emptyMesh();

	simplifyStuck();
	simplifySloppyStuck();
	simplifyPointsStuck();
	simplifyFlip();
	simplifyScale();
	simplifyDegenerate();
	simplifyLockBorder();

	adjacency();
	tessellation();
}


text:
import { ServerURL } from '../../constants/Constants';
import Auth from '../../modules/Auth';

function handeResponse(response) {
  if(response.status !== 200) {
    throw new Error('Looks like there was a problem. Status Code: ' +
      response.status);
  }

  // Examine the text in the response
  return response.json().then(data => {
    return data;
  });
}

exports.getAllUsers = async () => {
  let users;

  try {
    const response = await fetch(ServerURL + 'user/users', {
      method: 'GET',
      headers: {
        'x-auth-token': Auth.getToken()
      },
      body: {}
    });
    users = response.json();
  } catch (err) {
    console.log('Fetch Error :-S', err);
  }
  console.log(users);
  return users;
}

exports.getUser = async (id) => {
  let user;

  try {
    const response = await fetch(ServerURL + '/user/users/' + id, {
      method: "GET",
      headers: {
        'x-auth-token': Auth.getToken()
      },
      body: {}
    }
  );
    user = await handeResponse(response);
  } catch (err) {
    console.log('Fetch Error :-S', err);
  }

  return user;
}

exports.register = async (user) => {
  const response = await fetch(ServerURL + 'user/register', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: user.email,
      firstName: user.firstName,
      lastName: user.lastName,
      password: user.password,
      passportId: user.passportId,
      admin: false,
      phone: "+375" + user.phonePrefix + user.phone,
    })
  })
  return response;
}

exports.edit = async (user) => {
  const response = await fetch(ServerURL + 'user/edit', {
    method: 'PUT',
    headers: {
      'x-auth-token': Auth.getToken(),
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      id: user.id,
      firstName: user.firstName,
      lastName: user.lastName,
      passportId: user.passportId,
      phone: user.phone,
      email: user.email,
      admin: false,
      password: user.password
    })
  })
  return response;
}

exports.deleteUser = async (id) => {
  let response;

  try {
    response = await fetch(ServerURL + 'user/delete/' + id, {
      method: 'DELETE',
      headers: {
        'x-auth-token': Auth.getToken(),
        "Content-Type": "application/json"
      },
      body: {}
    });
  } catch (err) {
    console.log('Fetch Error :-S', err);
  }
  return response;
}

exports.login = async (user) => {
  let response;

  try {
    response = await fetch(ServerURL + "auth/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        email: user.email,
        password: user.password
      })
    });
  } catch (err) {
    console.log(err);
  }

  return response;
}

redpajama_set_name: RedPajamaGithub


text:
package com.twitter.scalding.typed

import org.specs._

import com.twitter.scalding._

private[typed] object LongIntPacker {
  def lr(l: Int, r: Int): Long = (l.toLong << 32) | r
  def l(rowCol: Long) = (rowCol >>> 32).toInt
  def r(rowCol: Long) = (rowCol & 0xFFFFFFFF).toInt
}

class MutatedSourceJob(args: Args) extends Job(args) {
  import com.twitter.bijection._
  implicit val bij = new AbstractBijection[Long, (Int, Int)] {
    override def apply(x: Long) = (LongIntPacker.l(x), LongIntPacker.r(x))
    override def invert(y: (Int, Int)) = LongIntPacker.lr(y._1, y._2)
  }

  val in0: TypedPipe[(Int, Int)] = TypedPipe.from(BijectedSourceSink(TypedTsv[Long]("input0")))

  in0.map { tup: (Int, Int) =>
    (tup._1 * 2, tup._2 * 2)
  }
    .write(BijectedSourceSink(TypedTsv[Long]("output")))
}

class MutatedSourceTest extends Specification {
  import Dsl._
  "A MutatedSourceJob" should {
    "Not throw when using a converted source" in {
      JobTest(new MutatedSourceJob(_))
        .source(TypedTsv[Long]("input0"), List(8L, 4123423431L, 12L))
        .sink[Long](TypedTsv[Long]("output")) { outBuf =>
          val unordered = outBuf.toSet
          // Size should be unchanged
          unordered.size must be_==(3)

          // Simple case, 2*8L won't run into the packer logic
          unordered(16L) must be_==(true)
          // Big one that should be in both the high and low 4 bytes of the Long
          val big = 4123423431L
          val newBig = LongIntPacker.lr(LongIntPacker.l(big) * 2, LongIntPacker.r(big) * 2)
          unordered(newBig) must be_==(true)
        }
        .run
        .runHadoop
        .finish
    }
  }
}

class ContraMappedAndThenSourceJob(args: Args) extends Job(args) {
  TypedPipe.from(TypedTsv[Long]("input0").andThen { x => (LongIntPacker.l(x), LongIntPacker.r(x)) })
    .map { case (l, r) => (l * 2, r * 2) }
    .write(TypedTsv[Long]("output").contraMap { case (l, r) => LongIntPacker.lr(l, r) })
}

class ContraMappedAndThenSourceTest extends Specification {
  import Dsl._
  "A ContraMappedAndThenSourceJob" should {
    "Not throw when using a converted source" in {
      JobTest(new ContraMappedAndThenSourceJob(_))
        .source(TypedTsv[Long]("input0"), List(8L, 4123423431L, 12L))
        .sink[Long](TypedTsv[Long]("output")) { outBuf =>
          val unordered = outBuf.toSet
          // Size should be unchanged
          unordered.size must be_==(3)

          // Simple case, 2*8L won't run into the packer logic
          unordered(16L) must be_==(true)
          // Big one that should be in both the high and low 4 bytes of the Long
          val big = 4123423431L
          val newBig = LongIntPacker.lr(LongIntPacker.l(big) * 2, LongIntPacker.r(big) * 2)
          unordered(newBig) must be_==(true)
        }
        .run
        .runHadoop
        .finish
    }
  }
}


text:
class Thread;
class Worker {
  bool running_;
  Poller* poller_;
  Thread* thread_;
  Dispatcher* dispatcher_;

  Worker(const Worker&);
  Worker& operator =(const Worker&);
public:
  explicit Worker(void);
  ~Worker(void);

  inline void Attach(Dispatcher* dispatcher)
  {
    dispatcher_ = dispatcher;
  }
public:
  bool Start(void);
  void Stop(void);

  bool AddConnector(Connector* conn);
private:
  static void Routine(void* argument);
};

#endif  //! __WORKER_HEADER_H__


text:
module RGUI
  module Action

    class Interpolator
      def initialize(start)
        @start_status = start
      end

      def to(end_status)
        @end_status = end_status
        self
      end

      def easing(easing_proc)
        @proc = easing_proc
        self
      end

      def start(count)
        @count = count
        self
      end

      def get(index)
        @start_status + @proc[(@end_status - @start_status), @count, index]
      end

    end

    module Easing

      EasingBase = Struct.new(:in, :out, :in_out)
      Quadratic = EasingBase.new
      Linear = EasingBase.new

      class << self

        def linear_init
          callback = proc {|v, c, i| (v * i.to_f / c).to_i }
          Linear.out = callback
          Linear.in = callback
          Linear.in_out = callback
        end

        def quadratic_init
          # Quadratic.define_singleton_method(:out) {}
          # Quadratic.define_singleton_method(:in) {}
          # Quadratic.define_singleton_method(:in_out) {}
        end

      end

    end

    Easing.linear_init
    Easing.quadratic_init
  end
end


text:
package com.tectonica.jonix.codelist;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DON'T EDIT MANUALLY
 */

/**
 * Enum that corresponds to ONIX Codelist 157
 *

 * Description: Content source type
 *
 * @see ONIX Codelists
 */
public enum ContentSourceTypes
{
	Printed_media("01"), //

	Website("02"), //

	Radio("03"), //

	TV("04");

	public final String value;

	private ContentSourceTypes(String value)
	{
		this.value = value;
	}

	public static ContentSourceTypes byValue(String value)
	{
		if (value == null || value.isEmpty())
			return null;
		for (ContentSourceTypes e : values())
			if (e.value.equals(value))
				return e;
		return null;
	}
}


text:
using System;
using System.Drawing;
using SpaceSim.Kernels;
using SpaceSim.Orbits;

using SpaceSim.Properties;
using VectorMath;

namespace SpaceSim.SolarSystem.Planets
{
    class Earth : MassiveBodyBase
    {
        public override string ApoapsisName { get { return "Apogee"; } }
        public override string PeriapsisName { get { return "Perigee"; } }

        private double inclination = 0.0;

        public override double Mass
        {
            get { return 5.97219e24; }
        }

        public override double SurfaceRadius
        {
            get { return BaseKernel.EARTH_RADIUS; }
        }

        public override double AtmosphereHeight
        {
            get { return BaseKernel.EARTH_ATMOSPHERE; }
        }

        public override double RotationRate
        {
            get { return -7.2722052166e-5 * inclination; }
        }

        public override double RotationPeriod
        {
            get { return 86400 / inclination; }
        }

        public override Color IconColor { get { return Color.Green; } }
        public override Color IconAtmopshereColor { get { return Color.LightSkyBlue; } }

        public Earth(double inclination)
            : base(OrbitHelper.FromJplEphemeris(1.470669705624798E+08, -3.465263667484938E+07),
                   OrbitHelper.FromJplEphemeris(6.445708901348731E+00, 2.887242866160539E+01), new EarthKernel())
        {
            this.inclination = Math.Cos(inclination * MathHelper.DegreesToRadians); ;
        }

        // Realistic density model based off https://www.grc.nasa.gov/www/k-12/rocket/atmos.html
        public override double GetAtmosphericDensity(double altitude)
        {
            if (altitude > AtmosphereHeight) return 0;

            double temperature;
            double pressure;

            if (altitude > 25000)
            {
                temperature = -131.21 + 0.00299 * altitude;

                pressure = 2.448 * Math.Pow((temperature + 273.1) / 216.6, -11.388);
            }
            else if (altitude > 11000)
            {
                temperature = -56.46;

                pressure = 22.65 * Math.Exp(1.73 - 0.000157 * altitude);
            }
            else
            {
                temperature = 15.04 - 0.00649 * altitude;

                pressure = 101.29 * Math.Pow((temperature + 273.1) / 288.08, 5.256);
            }

            return pressure / (0.2869 * (temperature + 273.1));
        }

        // Quickly approximated using temperature from here https://www.grc.nasa.gov/www/k-12/rocket/atmos.html
        // and a calculator here http://www.mhtl.uwaterloo.ca/old/onlinetools/airprop/airprop.html
        public override double GetAtmosphericViscosity(double altitude)
        {
            if (altitude > AtmosphereHeight) return 0;

            if (altitude > 10668) return 0.0000089213;

            return -5.37e-10 * altitude + 1.458e-5;
        }

        public override string ToString()
        {
            return "Earth";
        }
    }
}


text:
package ru.job4j.task1.persistent.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.job4j.task1.logic.entity.User;
import ru.job4j.task1.persistent.Store;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * The class DatabaseStoreImpl is an implementation of Store interface
 * for a database usage.
 *
 * @author Alex Proshak (olexandr_proshak@ukr.net)
 */
public class DatabaseStoreImpl implements Store {

    /**
     * The logger.
     */
    private static final Logger LOG = LoggerFactory.getLogger(DatabaseStoreImpl.class);

    /**
     * The implementation the DataSource interface with connection pool HikariCP.
     */
    private static DataSource source = new DaoManager();

    /**
     * The private field to store only one instance of the class.
     */
    private static final DatabaseStoreImpl INSTANCE = new DatabaseStoreImpl();

    /**
     * The getter for the only one instance of the class.
     * @return INSTANCE.
     */
    public static DatabaseStoreImpl getInstance() {
        return INSTANCE;
    }

    /**
     * The private constructor to avoid create instance.
     */
    private DatabaseStoreImpl() {
    }

    /**
     * The query string for inserting user to database.
     */
    private static final String INSERT = "INSERT INTO "
            + "users(id, name, login, email, date) "
            + "VALUES(?, ?, ?, ?, ?);";

    /**
     * The query string for updating the user by id.
     */
    private static final String UPDATE = "UPDATE users SET "
            + "name = ?,"
            + "login = ?,"
            + "email = ? WHERE users.id = ?;";

    /**
     * The query string for removing the user by id from database.
     */
    private static final String DELETE_BY_ID = "DELETE FROM users WHERE id = ?;";

    /**
     * The query string for selecting all user from database.
     */
    private static final String SELECT_ALL = "SELECT "
            + "users.id AS id, "
            + "users.name AS name, "
            + "users.login AS login, "
            + "users.email AS email, "
            + "users.date AS date FROM users;";

    /**
     * The query string for selecting the user by id from database.
     */
    private static final String SELECT_BY_ID = "SELECT "
            + "users.id AS id, "
            + "users.name AS name, "
            + "users.login AS login, "
            + "users.email AS email, "
            + "users.date AS date FROM users WHERE id = ?;";

    @Override
    public void add(User user) {
        if (user != null) {
            try (Connection con = source.getConnection();
                 PreparedStatement statement = con.prepareStatement(INSERT)) {
                statement.setInt(1, user.getId());
                statement.setString(2, user.getName());
                statement.setString(3, user.getLogin());
                statement.setString(4, user.getEmail());
                statement.setTimestamp(5, user.getCrateDate());
                statement.execute();
            } catch (SQLException e) {
                LOG.error(e.getSQLState(), e);
            }
        } else {
            LOG.error("Trying to add null user.");
        }
    }

    @Override
    public void update(User user) {
        if (user != null) {
            try (Connection con = source.getConnection();
                 PreparedStatement statement = con.prepareStatement(UPDATE)) {
                statement.setString(1, user.getName());
                statement.setString(2, user.getLogin());
                statement.setString(3, user.getEmail());
                statement.setInt(4, user.getId());
                statement.executeUpdate();
            } catch (SQLException e) {
                LOG.error(e.getSQLState(), e);
            }
        } else {
            LOG.error("Trying to update null user.");
        }
    }

    @Override
    public void delete(int id) {
        if (id >= 0) {
            try (Connection conn = source.getConnection();
                 PreparedStatement statement = conn.prepareStatement(DELETE_BY_ID)) {
                statement.setInt(1, id);
                statement.executeUpdate();
            } catch (SQLException e) {
                LOG.error(e.getSQLState(), e);
            }
        } else {
            LOG.error("Trying to remove users by negative id.");
        }
    }

    @Override
    public Collection<User> findAll() {
        List<User> result = new LinkedList<>();
        try (Connection con = source.getConnection();
             PreparedStatement statement = con.prepareStatement(SELECT_ALL)) {
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                User user = new User();
                user.setId(Integer.valueOf(resultSet.getInt("id")));
                user.setName(resultSet.getString("name"));
                user.setLogin(resultSet.getString("login"));
                user.setEmail((resultSet.getString("email")));
                user.setCrateDate(resultSet.getTimestamp("date"));
                result.add(user);
            }
        } catch (SQLException e) {
            LOG.error(e.getSQLState(), e);
        }
        return result;
    }

    @Override
    public User findById(int id) {
        User user = null;
        if (id >= 0) {
            try (Connection conn = source.getConnection();
                 PreparedStatement statement = conn.prepareStatement(SELECT_BY_ID)) {
                statement.setInt(1, id);
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    user = new User();
                    user.setId(Integer.valueOf(resultSet.getInt("id")));
                    user.setName(resultSet.getString("name"));
                    user.setLogin(resultSet.getString("login"));
                    user.setEmail((resultSet.getString("email")));
                    user.setCrateDate(resultSet.getTimestamp("date"));
                }
            } catch (SQLException e) {
                LOG.error(e.getSQLState(), e);
            }
        } else {
            LOG.error("Negative id to find");
        }
        return user;
    }
}


text:
[![Join the chat at https://gitter.im/ikesyo/Himotoki](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/ikesyo/Himotoki?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

[![GitHub release](https://img.shields.io/github/release/ikesyo/Himotoki.svg)](https://github.com/ikesyo/Himotoki/releases)
[![CI Status](https://travis-ci.org/ikesyo/Himotoki.svg)](https://travis-ci.org/ikesyo/Himotoki)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

Himotoki (紐解き) is a type-safe JSON decoding library purely written in Swift. This library is highly inspired by popular JSON parsing libraries in Swift: [Argo](https://github.com/thoughtbot/Argo) and [ObjectMapper](https://github.com/Hearst-DD/ObjectMapper).

_Himotoki_ has the same meaning of 'decoding' in Japanese.

- Just do JSON decoding (deserialization) well. JSON encoding (serialization) would not be supported going forward. :wink:
- Much simpler API.
- Fail-fast conditional model building. This is useful for some `struct`s with non-optional `let` properties.
- No external dependencies.

See a simple example from a test code:

```swift
struct Group: Decodable {
    let name: String
    let floor: Int
    let locationName: String
    let optional: [String]?

    // MARK: Decodable

    static func decode(e: Extractor) throws -> Group {
        return try Group(
            name: e <| "name",
            floor: e <| "floor",
            locationName: e <| [ "location", "name" ], // Parse nested objects
            optional: e <||? "optional" // Parse optional arrays of values
        )
    }
}

func testGroup() {
    var JSON: [String: AnyObject] = [ "name": "Himotoki", "floor": 12 ]

    let g: Group? = try? decode(JSON)
    XCTAssert(g != nil)
    XCTAssert(g?.name == "Himotoki")
    XCTAssert(g?.floor == 12)
    XCTAssert(g?.optional == nil)

    JSON["name"] = nil
    do {
        try decode(JSON) as Group
    } catch let DecodeError.MissingKeyPath(keyPath) {
        XCTAssert(keyPath == "name")
    } catch {
        XCTFail()
    }
}
```

## Operators

Himotoki supports the following operators to decode JSON elements, where `T` is a generic type conforming to `Decodable` protocol.

| Operator                        | Decode element as | Remarks                          |
|:--------------------------------|:------------------|:---------------------------------|
| <|         | `T`               | A value                          |
| <|?        | `T?`              | An optional value                |
| <||   | `[T]`             | An array of values               |
| <||?  | `[T]?`            | An optional array of values      |
| <|-|  | `[String: T]`     | A dictionary of values           |
| <|-|? | `[String: T]?`    | An optional dictionary of values |

## Requirements

- Swift 2.1 / Xcode 7.2
- OS X 10.9 or later
- iOS 8.0 or later (by Carthage or CocoaPods) / iOS 7 (by copying the source files directly)
- tvOS 9.0 or later
- watchOS 2.0 or later

## Installation

There are 3 options. If your app support iOS 7, you can only use the last way.

### Framework with Carthage (preferable)

Himotoki is [Carthage](https://github.com/Carthage/Carthage) compatible.

- Add `github "ikesyo/Himotoki" ~> 1.3` to your Cartfile.
- Run `carthage update`.

### Framework with CocoaPods

Himotoki also can be used by [CocoaPods](https://cocoapods.org/).

- Add the followings to your Podfile:

    ```ruby
    use_frameworks!
    pod "Himotoki", "~> 1.3"
    ```

- Run `pod install`.

### Copying the source files directly

- Add this repository as a git submodule:

    ```swift
    $ git submodule add https://github.com/ikesyo/Himotoki.git PATH_TO_SUBMODULE

    // or

    $ carthage update --use-submodules
    ```

- Then just add references of `Sources/*.swift` to your Xcode project.

## License

Himotoki is released under the [MIT License](LICENSE.md).


text:
export default function makeEventOptions(content='fake_content', type='application/json') {
  let fileName = 'fake_name',
      blob = new window.Blob([content], { type }),
      file = new window.File([blob], fileName);
  return { target: { files: [file] } };
}


text:
#ifndef SQLFRONT_h
#define SQLFRONT_h

#include "./sybfront.h"

static const char rcsid_sqlfront_h[] = "$Id: sqlfront.h,v 1.10 2011-07-13 11:06:31 freddy77 Exp $";
static const void *const no_unused_sqlfront_h_warn[] = { rcsid_sqlfront_h, no_unused_sqlfront_h_warn };

typedef DBPROCESS * PDBPROCESS;
typedef LOGINREC  * PLOGINREC;
typedef DBCURSOR  * PDBCURSOR;

typedef       int  *	LPINT;
typedef       char *	LPSTR;
#if !defined(PHP_MSSQL_H) || !defined(PHP_MSSQL_API)
typedef       BYTE *	LPBYTE;
#endif
typedef       void *	LPVOID;
typedef const char *	LPCSTR;

typedef const LPINT          LPCINT;
#ifndef _LPCBYTE_DEFINED
#define _LPCBYTE_DEFINED
typedef const BYTE *         LPCBYTE;
#endif
typedef       USHORT *       LPUSHORT;
typedef const LPUSHORT       LPCUSHORT;
typedef       DBINT *        LPDBINT;
typedef const LPDBINT        LPCDBINT;
typedef       DBBINARY *     LPDBBINARY;
typedef const LPDBBINARY     LPCDBBINARY;
typedef       DBDATEREC *    LPDBDATEREC;
typedef const LPDBDATEREC    LPCDBDATEREC;
typedef       DBDATETIME *   LPDBDATETIME;
typedef const LPDBDATETIME   LPCDBDATETIME;

#endif


text:
The nes protocol consists of JSON messages sent between the client and server.

Each incoming request from the client to the server contains:
- `type` - the message type:
    - `'ping'` - heartbeat response.
    - `'hello'` - connection initialization and authentication.
    - `'request'` - endpoint request.
    - `'sub'` - subscribe to a path.
    - `'unsub'` - unsubscribe from a path.
    - `'message'` - send custom message.
- `id` - a unique per-client request id (number or string).
- additional type-specific fields.

Each outgoing request from the server to the client contains:
- `type` - the message type:
    - `'ping'` - heartbeat request.
    - `'hello'` - connection initialization and authentication.
    - `'request'` - endpoint request.
    - `'sub'` - subscribe to a path.
    - `'message'` - send custom message.
    - `'update'` - an custom message push from the server.
    - `'pub'` - a subscription update.
- additional type-specific fields.

## Errors

When a message indicates an error, the message will include in addition to the message-specific fields:
- `statusCode` - an HTTP equivalent status code (4xx, 5xx).
- `headers` - optional headers related to the request.
- `payload` - the error details which include:
    - `error` - the HTTP equivalent error message.
    - `message` - a description of the error.
    - additional error-specific fields.

For example:

```js
{
    type: 'hello',
    id: 1,
    statusCode: 401,
    payload: {
        error: 'Unauthorized',
        message: 'Unknown username or incorrect password'
    }
}
```

## Heartbeat

Flow: `server` -> `client` -> `server`

For cases where it is not possible for the TCP connection to determine if the connection is still active,
the server sends a heartbeat message to the client every configured interval, and then expects the client
to respond within a configured timeout. The server sends:
- `type` - set to `'ping'`.

For example:

```js
{
    type: 'ping'
}
```

When the client receives the message, it sends back:
- `type` - set to `'ping'`.
- `id` - a unique per-client request id (number or string).

For example:

```js
{
    type: 'ping',
    id: 6
}
```

## Hello

Flow: `client` -> `server` -> `client`

Every client connection must first be initialized with a `hello` message. The client sends a message to the server
with the following:
- `type` - set to `'hello'`.
- `id` - a unique per-client request id (number or string).
- `auth` - optional authentication credentials. Can be any value understood by the server.
- `subs` - an optional array of strings indicating the path subscriptions the client is interested in.

For example:

```js
{
    type: 'hello',
    id: 1,
    auth: {
        headers: {
            authorization: 'Basic am9objpzZWNyZXQ='
        }
    },
    subs: ['/a', '/b']
}
```

The server respond by sending a message back with the following:
- `type` - set to `'hello'`.
- `id` - the same `id` received from the client.
- `heartbeat` - the server heartbeat configuration which can be:
    - `false` - no heartbeats will be sent.
    - an object with:
        - `interval` - the heartbeat interval in milliseconds.
        - `timeout` - the time from sending a heartbeat to the client until a response is expected
          before a connection is considered closed by the server.

Note: the client should assume the connection is closed if it has not heard from the server in
heartbeat.interval + heartbeat.timeout.

For example:

```js
{
    type: 'hello',
    id: 1,
    heartbeat: {
        interval: 15000,
        timeout: 5000
    }
}
```

If the request failed, the server includes the [standard error fields](#errors).

For example:

```js
{
    type: 'hello',
    id: 1,
    statusCode: 401,
    payload: {
        error: 'Unauthorized',
        message: 'Unknown username or incorrect password'
    }
}
```

If any of the subscription requests fail, the server will send separate messages before the `'hello'` response:
- `type` - set to `'sub'`.
- `path` - the requested path which failed to subscribe.
- the [standard error fields](#errors)

For example:

```js
{
    type: 'sub',
    path: '/a',
    statusCode: 403,
    payload: {
        error: 'Forbidden'
    }
}
```

## Request

Flow: `client` -> `server` -> `client`

Request a resource from the server where:
- `type` - set to `'request'`.
- `id` - a unique per-client request id (number or string).
- `method` - the corresponding HTTP method (e.g. `'GET'`).
- `path` - the requested resource (can be an HTTP path of resource name).
- `headers` - an optional object with the request headers (each header name is a key with a corresponding value).
- `payload` - an optional value to send with the request.

For example:

```js
{
    type: 'request',
    id: 2,
    method: 'POST',
    path: '/item/5',
    payload: {
        id: 5,
        status: 'done'
    }
}
```

The server response includes:
- `type` - set to `'request'`.
- `id` - the same `id` received from the client.
- `statusCode` - an HTTP equivalent status code.
- `payload` - the requested resource.
- `headers` - optional headers related to the request (e.g. `{ 'content-type': 'text/html; charset=utf-8' }').

For example:

```js
{
    type: 'request',
    id: 2,
    statusCode: 200,
    payload: {
        status: 'ok'
    }
}
```

If the request fails, the `statusCode`, `headers`, and `payload` fields will comply with the
[standard error values](#errors).

## Message

Flow: `client` -> `server` [-> `client`]

Sends a custom message to the server where:
- `type` - set to `'message'`.
- `id` - a unique per-client request id (number or string).
- `message` - any value (string, object, etc.).

For example:

```js
{
    type: 'message',
    id: 3,
    message: 'hi'
}
```

The server may respond which includes:
- `type` - set to `'message'`.
- `id` - the same `id` received from the client.
- `message` - any value (string, object, etc.).

For example:

```js
{
    type: 'message',
    id: 3,
    message: 'hello back'
}
```

If the request fails, the response will include the [standard error fields](#errors).

## Subscribe

Flow: `client` -> `server` [-> `client`]

Sends a subscription request to the server:
- `type` - set to `'sub'`.
- `id` - a unique per-client request id (number or string).
- `path` - the requested subscription path.

For example:

```js
{
    type: 'sub',
    id: 4,
    path: '/box/blue'
}
```

The server responds only if an error occurred:
- `type` - set to `'sub'`.
- `path` - the requested path which failed to subscribe.
- the [standard error fields](#errors)

For example:

```js
{
    type: 'sub',
    path: '/box/blue',
    statusCode: 403,
    payload: {
        error: 'Forbidden'
    }
}
```

## Unsubscribe

Flow: `client` -> `server`

Unsubscribe from a server subscription:
- `type` - set to `'unsub'`.
- `id` - a unique per-client request id (number or string).
- `path` - the subscription path.

For example:

```js
{
    type: 'unsub',
    id: 5,
    path: '/box/blue'
}
```

There is no server response.

## Update

Flow: `server` -> `client`

A custom message sent from the server to a specific client or to all connected clients:
- `type` - set to `'update'`.
- `message` - any value (string, object, etc.).

```js
{
    type: 'update',
    message: {
        some: 'message'
    }
}
```

## Publish

Flow: `server` -> `client`

A message sent from the server to all subscribed clients:
- `type` - set to `'pub'`.
- `path` - the subscription path.
- `message` - any value (string, object, etc.).

```js
{
    type: 'pub',
    path: '/box/blue',
    message: {
        status: 'closed'
    }
}
```


text:
package es.upm.fi.dia.oeg.map4rdf.server.dao.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.vocabulary.RDFS;

import es.upm.fi.dia.oeg.map4rdf.share.conf.ParameterNames;
import es.upm.fi.dia.oeg.map4rdf.server.dao.DaoException;
import es.upm.fi.dia.oeg.map4rdf.server.dao.Map4rdfDao;
import es.upm.fi.dia.oeg.map4rdf.server.vocabulary.Geo;
import es.upm.fi.dia.oeg.map4rdf.share.BoundingBox;
import es.upm.fi.dia.oeg.map4rdf.share.Facet;
import es.upm.fi.dia.oeg.map4rdf.share.FacetConstraint;
import es.upm.fi.dia.oeg.map4rdf.share.GeoResource;
import es.upm.fi.dia.oeg.map4rdf.share.GeoResourceOverlay;
import es.upm.fi.dia.oeg.map4rdf.share.PointBean;
import es.upm.fi.dia.oeg.map4rdf.share.RDFModelProcessor;
import es.upm.fi.dia.oeg.map4rdf.share.Resource;
import es.upm.fi.dia.oeg.map4rdf.share.StatisticDefinition;
import es.upm.fi.dia.oeg.map4rdf.share.Year;

/**
 * @author Alexander De Leon
 */
public class DbPediaDaoImpl extends CommonDaoImpl implements Map4rdfDao {

	private static final Logger LOG = Logger.getLogger(DbPediaDaoImpl.class);

	@Inject
	public DbPediaDaoImpl(@Named(ParameterNames.ENDPOINT_URL) String endpointUri) {
		super(endpointUri);
	}

	@Override
	public List<GeoResource> getGeoResources(BoundingBox boundingBox) throws DaoException {
		return getGeoResources(boundingBox, null);
	}

	@Override
	public GeoResource getGeoResource(String uri) throws DaoException {
		QueryExecution execution = QueryExecutionFactory.sparqlService(endpointUri, createGetResourceQuery(uri));

		try {
			ResultSet queryResult = execution.execSelect();
			GeoResource resource = null;
			while (queryResult.hasNext()) {
				QuerySolution solution = queryResult.next();
				try {
					double lat = solution.getLiteral("lat").getDouble();
					double lng = solution.getLiteral("lng").getDouble();

					if (resource == null) {
						resource = new GeoResource(uri, new PointBean(uri, lng, lat));
					}
					if (solution.contains("label")) {
						Literal labelLiteral = solution.getLiteral("label");
						resource.addLabel(labelLiteral.getLanguage(), labelLiteral.getString());
					}
				} catch (NumberFormatException e) {
					LOG.warn("Invalid Latitud or Longitud value: " + e.getMessage());
				}
			}
			return resource;
		} catch (Exception e) {
			throw new DaoException("Unable to execute SPARQL query", e);
		} finally {
			execution.close();
		}
	}

	@Override
	public List<GeoResource> getGeoResources(BoundingBox boundingBox, Set<FacetConstraint> constraints)
			throws DaoException {
		return getGeoResources(boundingBox, constraints, null);
	}

	@Override
	public List<GeoResource> getGeoResources(BoundingBox boundingBox, Set<FacetConstraint> constraints, int max)
			throws DaoException {
		return getGeoResources(boundingBox, constraints, new Integer(max));
	}

        @Override
        public List<GeoResource> getGeoResources(String modelConfiguration)
                        throws DaoException {
                // TODO(jonathangsc): Uncomment this once the repository is uploaded.
                // ShpToRdf shpConverter = new ShpToRdf(configuration);
                // return RDFModelProcessor.processRdfModel(shpConverter.getRdfModel());
                return RDFModelProcessor.parseRdfFile(modelConfiguration);
        }

	@Override
	public List<GeoResourceOverlay> getGeoResourceOverlays(StatisticDefinition statisticDefinition,
			BoundingBox boundingBox, Set<FacetConstraint> constraints) throws DaoException {
		// TODO What can be done here?
		return Collections.emptyList();
	}

	@Override
	public List<Facet> getFacets(String predicateUri, BoundingBox boundingBox) throws DaoException {
		Map<String, Facet> result = new HashMap<String, Facet>();

		StringBuilder queryBuffer = new StringBuilder();
		queryBuffer.append("select distinct ?class ?label where { ");
		queryBuffer.append("?x <" + Geo.lat + "> _:lat. ");
		queryBuffer.append("?x <" + Geo.lng + "> _:lng. ");
		queryBuffer.append("?x <" + predicateUri + "> ?class . ");
		queryBuffer.append("optional {?class <" + RDFS.label + "> ?label . }}");

		QueryExecution execution = QueryExecutionFactory.sparqlService(endpointUri, queryBuffer.toString());

		try {
			ResultSet queryResult = execution.execSelect();
			while (queryResult.hasNext()) {
				QuerySolution solution = queryResult.next();
				String uri = solution.getResource("class").getURI();
				Facet value = null;
				if (result.containsKey(uri)) {
					value = result.get(uri);
				} else {
					value = new Facet(uri);
					result.put(uri, value);
				}
				if (solution.contains("label")) {
					Literal label = solution.getLiteral("label");
					value.addLabel(label.getLanguage(), label.getString());
				}
			}
			return new ArrayList<Facet>(result.values());
		} catch (Exception e) {
			throw new DaoException("Unable to execute SPARQL query", e);
		} finally {
			execution.close();
		}
	}

	@Override
	public List<Year> getYears(String datasetUri) throws DaoException {
		// TODO not applicable
		return Collections.emptyList();
	}

	@Override
	public List<Resource> getStatisticDatasets() throws DaoException {
		// TODO What can be done here?
		return Collections.emptyList();
	}

	/* --------------------- helper methods --- */

	private List<GeoResource> getGeoResources(BoundingBox boundingBox, Set<FacetConstraint> constraints, Integer max)
			throws DaoException {
		// TODO: use location to restrict the query to the specifies geographic
		// area.

		HashMap<String, GeoResource> result = new HashMap<String, GeoResource>();

		QueryExecution execution = QueryExecutionFactory.sparqlService(endpointUri,
				createGetResourcesQuery(boundingBox, constraints, max));

		try {
			ResultSet queryResult = execution.execSelect();
			while (queryResult.hasNext()) {
				QuerySolution solution = queryResult.next();
				try {
					String uri = solution.getResource("r").getURI();
					double lat = solution.getLiteral("lat").getDouble();
					double lng = solution.getLiteral("lng").getDouble();

					GeoResource resource = result.get(uri);
					if (resource == null) {
						resource = new GeoResource(uri, new PointBean(uri, lng, lat));
						result.put(uri, resource);
					}
					if (solution.contains("label")) {
						Literal labelLiteral = solution.getLiteral("label");
						resource.addLabel(labelLiteral.getLanguage(), labelLiteral.getString());
					}
				} catch (NumberFormatException e) {
					LOG.warn("Invalid Latitud or Longitud value: " + e.getMessage());
				}
			}

			return new ArrayList<GeoResource>(result.values());
		} catch (Exception e) {
			throw new DaoException("Unable to execute SPARQL query", e);
		} finally {
			execution.close();
		}
	}

	/**
	 * @param boundingBox
	 * @param constraints
	 * @param max
	 * @return
	 */

	private String createGetResourcesQuery(BoundingBox boundingBox, Set<FacetConstraint> constraints, Integer limit) {
		StringBuilder query = new StringBuilder("PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> SELECT distinct ?r ?label ?lat ?lng ");
		query.append("WHERE { ");
		query.append("?r <" + Geo.lat + "> ?lat. ");
		query.append("?r <" + Geo.lng + "> ?lng . ");
		query.append("OPTIONAL { ?r <" + RDFS.label + "> ?label } .");
		if (constraints != null) {
			for (FacetConstraint constraint : constraints) {
				query.append("{ ?r <" + constraint.getFacetId() + "> <" + constraint.getFacetValueId() + ">. } UNION");
			}
			query.delete(query.length() - 5, query.length());
		}

		//filters
		if (boundingBox!=null) {
			query = addBoundingBoxFilter(query, boundingBox);
		}

		query.append("}");
		if (limit != null) {
			query.append(" LIMIT " + limit);
		}
		return query.toString();
	}

	private String createGetResourceQuery(String uri) {
		StringBuilder query = new StringBuilder("SELECT distinct ?lat ?lng ?label ");
		query.append("WHERE { ");
		query.append("<" + uri + "> <" + Geo.lat + "> ?lat. ");
		query.append("<" + uri + "> <" + Geo.lng + "> ?lng . ");
		query.append("OPTIONAL { <" + uri + "> <" + RDFS.label + "> ?label } .");
		query.append("}");
		return query.toString();
	}
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python;

import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;
import com.jetbrains.pyqt.QtUIFileType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

/**
 * @author yole
 */
public class PythonFileTypeFactory extends FileTypeFactory {
  @Override
  public void createFileTypes(@NonNls @NotNull final FileTypeConsumer consumer) {
    consumer.consume(PythonFileType.INSTANCE, "py;pyw;");
    consumer.consume(QtUIFileType.INSTANCE, "ui");
    consumer.consume(XmlFileType.INSTANCE, "qrc");
  }
}


text:
package com.blazebit.persistence.spi;

import javax.persistence.Query;
import java.util.List;

/**
 * Interface for CTE queries.
 *
 * @author Christian Beikov
 * @since 1.1.0
 */
public interface CteQueryWrapper {

    /**
     * Returns the list of queries that are participating in this aggregate query.
     *
     * @return The participating queries
     */
    public List<Query> getParticipatingQueries();
}


text:
class CreditCard
  def initialize(number)
    @number = number
    raise ArgumentError.new("Your card number is 16 digits!") if @number.to_s.length != 16
  end

  def check_card
    individual= @number.to_s.split("")
    individual.map! { |number|
      if individual.index(number)%2 == 0
        number.to_i * 2
      else
        number.to_i
      end
      }
     individual.map! { |number|
      if number > 9
        number.to_s.split("")
      else number = number
      end
      }
    individual.flatten!
    individual.map! { |number|
      number = number.to_i
      }
    sum = individual.inject{|sum,x| sum + x }
    if sum %10 == 0
      return true
    else
      return false
    end
  end
end

# Refactored Solution
class CreditCard
  def initialize(number)
    @number = number
    raise ArgumentError.new("Your card number is 16 digits!") if @number.to_s.length != 16
  end

  def check_card
    individual= @number.to_s.split("")
    individual.map! { |number|
    individual.index(number)%2 == 0 ? (number.to_i * 2).to_s.split("") : number.to_i
  }
    individual.flatten!.map! { |number| number = number.to_i }
    individual.inject{|sum,x| sum + x } %10 == 0
  end
end

# Reflection
# What was the most difficult part of this challenge for you and your pair?
# The most difficult challenge was splitting numbers greater 10 into individual numbers.
# However, I was able to change it into a string and do the split method to split them into individual numbers
# and change it back to integer.

# What new methods did you find to help you when you refactored?
# I learned a new method called flatten, which takes the objects within the subarray and turns it into a single array

# What concepts or learnings were you able to solidify in this challenge?
# I was able to solidify my knowledge of map! that it will change its original state.
# I also learned that split method will return an array


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="@drawable/gradient"
    tools:context="com.example.michael.ui.activities.JoinGameActivity"
    android:keepScreenOn="true"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/joinGameLayout"
        android:layout_above="@+id/joinButton">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Join Game"
            android:paddingTop="40dp"
            android:textColor="@color/white"
            android:textSize="40dp"
            android:id="@+id/textView2"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Nickname:"
        android:id="@+id/nickNameView"
        android:layout_centerVertical="true"
        android:textColor="@color/white"
        />

    <EditText
        android:layout_width="wrap_content"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/nickNameView"
        android:id="@+id/playerName"
        android:hint="Enter name"
        android:gravity="center"
        android:textColor="@color/white"
        android:layout_alignLeft="@+id/gameCode"
        android:layout_gravity="center_vertical"
        android:inputType="text"
        android:layout_alignRight="@+id/gameCode"
        android:layout_alignEnd="@+id/gameCode" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Game code:"
        android:id="@+id/gameCodeView"
        android:layout_centerVertical="true"
        android:textColor="@color/white"
        android:layout_alignBaseline="@+id/gameCode"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/gameCode"
        android:hint="Enter game code"
        android:gravity="center"
        android:textColor="@color/white"
        android:layout_gravity="center_vertical"
        android:layout_below="@+id/playerName"
        android:layout_toRightOf="@+id/gameCodeView"
        android:inputType="text"/>

    </RelativeLayout>

    <Button
        style="?android:attr/buttonStyleSmall"
        android:background="@drawable/joinbutton"
        android:layout_width="115dp"
        android:layout_height="wrap_content"
        android:textSize="18dp"
        android:id="@+id/joinButton"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:text="Join"
        android:textAllCaps="false"
        android:onClick="joinButton"/>

</RelativeLayout>


text:
from app import baza
from peewee import *

class BaseModel(Model):
    class Meta:
        database = baza

class Pytanie(BaseModel):
    pytanie = CharField(unique = True)
    odpok = CharField()

class Odpowiedz(BaseModel):
    pnr = ForeignKeyField(Pytanie, related_name = 'odpowiedzi', on_delete = 'CASCADE')
    odpowiedz = CharField()


text:
module Batsir
  module DSL
    class ConditionalNotifierDeclaration
      attr_reader :notifier_declarations

      NotifierConditionDeclaration = Struct.new(:condition, :notifier, :options)

      def initialize
        @notifier_declarations = []
      end

      def add_conditional(condition, notifier_class, options)
        @notifier_declarations << NotifierConditionDeclaration.new(condition, notifier_class, options)
      end

      def compile(code, stage_worker)
        code << <<-EOF
              notifier = Batsir::Notifiers::ConditionalNotifier.new
        EOF
        notifier_declarations.each do |notifier_declaration|
          code << <<-EOF
              condition = ->(message){#{notifier_declaration.condition}}
              notifier.add_notifier condition, #{notifier_declaration.notifier}.new(#{notifier_declaration.options.to_s})
          EOF
        end
        stage_worker.add_transformers_to_notifier(code)
        stage_worker.add_notifier(code)
      end
    end
  end
end


text:
from datetime import datetime, timedelta
from nose import tools as nt

from tests.base import OsfTestCase
from tests.factories import CommentFactory, AuthUserFactory
from website.project.model import Comment

from scripts import migrate_spam
from website.project.spam.model import SpamStatus

class TestMigrateSpam(OsfTestCase):
    def setUp(self):
        super(TestMigrateSpam, self).setUp()
        self.generic_report = {
            'category': 'spam',
            'text': 'spammer spam',
            'date': datetime.utcnow(),
            'retracted': False
        }
        Comment.remove()
        self.user = AuthUserFactory()
        self.comment_1 = CommentFactory()
        self.comment_1.spam_status = 0
        self.comment_1.reports[self.user._id] = self.generic_report
        self.comment_1.save()
        self.comment_2 = CommentFactory()
        self.comment_2.spam_status = 0
        self.comment_2.reports[self.user._id] = self.generic_report
        self.comment_2.save()
        self.comment_3 = CommentFactory()
        self.comment_3.spam_status = 0
        self.comment_3.save()
        self.comment_4 = CommentFactory()
        self.comment_4.date_last_reported = None
        self.comment_4.spam_status = SpamStatus.FLAGGED
        self.comment_4.reports[self.user._id] = self.generic_report
        self.comment_4.save()
        self.comment_5 = CommentFactory()
        self.comment_5.date_last_reported = None
        self.comment_5.spam_status = SpamStatus.UNKNOWN
        self.comment_5.save()
        self.comment_6 = CommentFactory()
        self.comment_6.date_last_reported = None
        self.comment_6.spam_status = SpamStatus.SPAM
        self.comment_6.reports[self.user._id] = self.generic_report
        self.comment_6.save()

    def test_get_status_targets(self):
        targets = migrate_spam.get_no_status_targets()
        nt.assert_equal(len(targets), 3)

    def test_get_latest_targets(self):
        migrate_spam.migrate_status(migrate_spam.get_no_status_targets())
        targets = migrate_spam.get_no_latest_targets()
        nt.assert_equal(len(targets), 4)

    def test_migrate_status(self):
        migrate_spam.migrate_status(migrate_spam.get_no_status_targets())
        self.comment_2.reload()
        self.comment_1.reload()
        self.comment_3.reload()
        nt.assert_equal(self.comment_1.spam_status, SpamStatus.FLAGGED)
        nt.assert_equal(self.comment_2.spam_status, SpamStatus.FLAGGED)
        nt.assert_equal(self.comment_3.spam_status, SpamStatus.UNKNOWN)

    def test_migrate_latest(self):
        migrate_spam.migrate_status(migrate_spam.get_no_status_targets())
        migrate_spam.migrate_latest(migrate_spam.get_no_latest_targets())
        date = self.generic_report['date']
        self.comment_4.reload()
        self.comment_6.reload()
        nt.assert_almost_equal(
            self.comment_4.date_last_reported, date,
            delta=timedelta(microseconds=1000)
        )
        nt.assert_almost_equal(
            self.comment_6.date_last_reported, date,
            delta=timedelta(microseconds=1000)
        )


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

define(function(require) {
  require('jquery');

  // Clone the local config object in a private var
  var _config = $.extend(true, {}, config);

  var Config = {
    'isTabEnabled': function(tabName) {
      var enabled = _config['view']['enabled_tabs'][tabName];
      return enabled;
    },

    "isTabActionEnabled": function(tabName, actionName, panelName) {
      var enabled = false;
      var configTab = _config['view']['tabs'][tabName];

      if (configTab != undefined) {
        if (panelName) {
          enabled = configTab['panel_tabs_actions'][panelName][actionName];
        } else {
          enabled = configTab['actions'][actionName];
        }
      }

      return enabled;
    },

    "isTabPanelEnabled": function(tabName, panelTabName) {
      if (_config['view']['tabs'][tabName]) {
        var enabled = _config['view']['tabs'][tabName]['panel_tabs'][panelTabName];
        return enabled;
      } else {
        return false;
      }
    },

    "isProvisionTabEnabled": function(tabName, panelTabName) {
      if (_config['view']['tabs'][tabName]) {
        var enabled = _config['view']['tabs'][tabName]['provision_tabs'][panelTabName];
        return enabled;
      } else {
        return false;
      }
    },

    "isFeatureEnabled": function(featureName) {
      if (_config['view']['features'] && _config['view']['features'][featureName]) {
        return true;
      } else {
        return false;
      }
    },

    "tabTableColumns": function(tabName) {
      if (!_config['view']['tabs'][tabName]) {
        return [];
      }

      var columns = _config['view']['tabs'][tabName]['table_columns'];

      if (columns) {
        return columns;
      } else {
        return [];
      }
    },

    "isTemplateCreationTabEnabled": function(templateTabName) {
      if (_config['view']['tabs']['templates-tab']) {
        var enabled = _config['view']['tabs']['templates-tab']['template_creation_tabs'][templateTabName];
        return enabled;
      } else {
        return false;
      }
    },

    "dashboardWidgets": function(perRow) {
      if (!_config['view']['tabs']['dashboard-tab']) {
        return []
      }

      var widgets = _config['view']['tabs']['dashboard-tab'][perRow];

      if (widgets) {
        return widgets;
      } else {
        return [];
      }
    },

    "tableOrder": function() {
      return _config['user_config']["table_order"];
    },

    "provision": {
      "dashboard": {
        "isEnabled": function(widget) {
          if (_config['view']['tabs']['provision-tab']) {
            var enabled = _config['view']['tabs']['provision-tab']['dashboard'][widget];
            return enabled;
          } else {
            return false;
          }
        }
      },
      "create_vm": {
        "isEnabled": function(widget) {
          if (_config['view']['tabs']['provision-tab'] && _config['view']['tabs']['provision-tab']["create_vm"]) {
            return _config['view']['tabs']['provision-tab']['create_vm'][widget];
          } else {
            return false;
          }
        }
      },
      "logo": (_config['view']["provision_logo"] || "images/one_small_logo.png")
    },

    'autoRefresh' : _config['view']['autorefresh'],
    'tableOrder': _config['user_config']['table_order'],
    'vncProxyPort': _config['system_config']['vnc_proxy_port'],
    'vncWSS': _config['user_config']['vnc_wss'],
    'logo': (_config['view']["small_logo"] || "images/one_small_logo.png")
  }

  return Config;
});


text:
package com.firebase.uidemo.database;

import android.graphics.PorterDuff;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.RotateDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.firebase.uidemo.R;

public class ChatHolder extends RecyclerView.ViewHolder {
    private final TextView mNameField;
    private final TextView mTextField;
    private final FrameLayout mLeftArrow;
    private final FrameLayout mRightArrow;
    private final RelativeLayout mMessageContainer;
    private final LinearLayout mMessage;
    private final int mGreen300;
    private final int mGray300;

    public ChatHolder(View itemView) {
        super(itemView);
        mNameField = (TextView) itemView.findViewById(R.id.name_text);
        mTextField = (TextView) itemView.findViewById(R.id.message_text);
        mLeftArrow = (FrameLayout) itemView.findViewById(R.id.left_arrow);
        mRightArrow = (FrameLayout) itemView.findViewById(R.id.right_arrow);
        mMessageContainer = (RelativeLayout) itemView.findViewById(R.id.message_container);
        mMessage = (LinearLayout) itemView.findViewById(R.id.message);
        mGreen300 = ContextCompat.getColor(itemView.getContext(), R.color.material_green_300);
        mGray300 = ContextCompat.getColor(itemView.getContext(), R.color.material_gray_300);
    }

    public void setIsSender(boolean isSender) {
        final int color;
        if (isSender) {
            color = mGreen300;
            mLeftArrow.setVisibility(View.GONE);
            mRightArrow.setVisibility(View.VISIBLE);
            mMessageContainer.setGravity(Gravity.END);
        } else {
            color = mGray300;
            mLeftArrow.setVisibility(View.VISIBLE);
            mRightArrow.setVisibility(View.GONE);
            mMessageContainer.setGravity(Gravity.START);
        }

        ((GradientDrawable) mMessage.getBackground()).setColor(color);
        ((RotateDrawable) mLeftArrow.getBackground()).getDrawable()
                .setColorFilter(color, PorterDuff.Mode.SRC);
        ((RotateDrawable) mRightArrow.getBackground()).getDrawable()
                .setColorFilter(color, PorterDuff.Mode.SRC);
    }

    public void setName(String name) {
        mNameField.setText(name);
    }

    public void setText(String text) {
        mTextField.setText(text);
    }
}


text:
MrGadget is a very lightweight utility library designed to do 4 things: 1) send a file to a remote server via SCP, 2) send a file to a remote server via SFTP, 3) execute a command on a remote server, 4) execute a SUDO command on a remote server. It uses the JSch library and leans heavily on the example code on the JSch website. Although MrGadget was built for my use in Gradle, it is a self-contained set of Groovy classes that should be useful anywhere.

File uploading allows progress to be reported via 'log.info' statements or via a Java Swing dialog box or both.

MrGadget will use the System.console to prompt the user for necessary passwords, and there is an option to save these passwords, using encryption, in the system preferences. The encryption scheme is better than plain text, but rather basic, and as this is open-source, NO GUARANTEE is made regarding the security of the encryption. It is certainly better than saving the passwords in plain text in a config file or build file, but an interested person could reverse engineer the key used and discover the password. SO USE THIS FEATURE AT YOUR OWN RISK.

# Usage (in general)

MrGadget is a plain-old Groovy library class and there's no reason he can't be used pretty much anywhere there's a JVM. I just happened to write him for my own use in gradle. Example Groovy usage would be:

	class ReallySimpleClass {

		MrGadget mrg

		public ReallySimpleClass(String user, String host) {
			mrg = new MrGadget(user:user, host:host)
			mrg.strictHostKeyChecking = false
			mrg.showProgressDialog = false
			mrg.logProgressGranularity = 10 // log.info file upload progress every 10%
		}

		void doIt() {
			mrg.copyToRemoteSFTP(localFile:'some/local/file.zip', remoteFile:'some/remote/file.zip')
		}

	}

# Usage with Gradle

### Use the plugin! https://github.com/moksamedia/mrgadget-gradle-plugin
### Or:

Download the jar-with-dependencies
Add the import statement and the dependency to the gradle buildscript block as shown:

	import com.moksamedia.mrgadget.MrGadget

	buildscript {

	  repositories {
	    mavenCentral()
		flatDir {
			dirs "path/to/jar"
		}
	  }

	  dependencies {
		classpath 'com.moksamedia:mrgadget:<DOWNLOADED-VERSION>:jar-with-dependencies' // OR CURRENT VERSION
	  }

	}

You could also import directly from the GitHub repo:

	buildscript {

		repositories {
			mavenCentral()
			add(new org.apache.ivy.plugins.resolver.URLResolver()) {
				name = 'mrgadget-plugin'
				basePath = 'https://raw.github.com/moksamedia/mrgadget/master/repo'
				addArtifactPattern "${basePath}/[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"
			}
		}

	  dependencies {
		classpath 'com_moksamedia:mrgadget:<DESIRED-VERSION>:jar-with-dependencies'
	  }

	}

Import from Maven Central.

	import com.moksamedia.mrgadget.MrGadget

	buildscript {

	  repositories {
	    mavenCentral()
	  }

	  dependencies {
		classpath 'com.moksamedia:mrgadget:latest.version:jar-with-dependencies'
		// or for 'light' jar: classpath 'com.moksamedia:mrgadget:latest.version'
		// but you'll have to add the dependencies to your build if they're not already present
	  }

	}

Of course, all of this assumes you're using MrGadget in the buildscript itself. To simply add his as a dependency to a project all you need is:

	repositories {
	  mavenCentral()
	}

	dependencies {
		classpath 'com.moksamedia:mrgadget:latest.version:jar-with-dependencies'
	}

# Dependencies

	groovy 'org.codehaus.groovy:groovy:1.8.6' ext { fatJarExclude = true }	// excluded from fatJar
	compile 'org.slf4j:slf4j-simple:1.6.3' ext { fatJarExclude = true }		// excluded from fatJar
	compile 'com.jcraft:jsch:0.1.48'	// JSch is the SSH java package
	compile 'org.jasypt:jasypt-acegisecurity:1.9.0'	// for encrypting the stored passwords

	<dependency>
		<groupId>org.jasypt</groupId>
		<artifactId>jasypt-acegisecurity</artifactId>
		<version>1.9.0</version>
		<scope>compile</scope>
	</dependency>
	<dependency>
		<groupId>com.jcraft</groupId>
		<artifactId>jsch</artifactId>
		<version>0.1.48</version>
		<scope>compile</scope>
	</dependency>
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-simple</artifactId>
		<version>1.6.3</version>
		<scope>compile</scope>
	</dependency>

# Use him in some tasks!

	task copyToServerOnly << {

		MrGadget mrg = new MrGadget(
			user:'someuser', 					// user and host must always be set
			host:'www.someuser.com',
			strictHostKeyChecking:false)		// can turn off strict host key checking to avoid host key errors

		logger.info "SENDING FILE"
		mrg.copyToRemoteSFTP(localFile:"$rootDir/build/libs/someapp.war", remoteFile:"/websites/someapp.war")

	}

	task copyToServerOnlyWithCustomKey << {

		MrGadget mrg = new MrGadget(
			user:'someuser',
			host:'www.someuser.com',
			strictHostKeyChecking:false,
			prefsEncryptionKey: someCustomKey) // can specify a custom key to use to encrypt passwords

		logger.info "SENDING FILE"
		mrg.copyToRemoteSFTP(localFile:"$rootDir/build/libs/someapp.war", remoteFile:"/websites/someapp.war")

	}

	task deployToServerAndFix << {

		MrGadget mrg = new MrGadget(
			user:'someuser',
			host:'www.someuser.com',
			strictHostKeyChecking:false,
			leaveSessionOpen:true)				// leave session open to avoid having to reconnect when executing
												// multiple successive commands

		logger.info "SENDING FILE"
		mrg.copyToRemoteSFTP(localFile:"$rootDir/build/libs/someapp.war", remoteFile:"/websites/someapp.war")

		logger.info "SETTING OWNER OF WAR"
		mrg.execRemoteSudo("chown tomcat6:tomcat6 /websites/someapp.war")

		logger.info "SETTING PERMISSION OF WAR"
		mrg.execRemoteSudo("chmod 775 /websites/someapp.war")

		logger.info "RESTARTING TOMCAT"
		mrg.execRemoteSudo("service tomcat6 restart")

		logger.info "FINISHED"
		mrg.closeSession()						// don't forget to close the session

	}

	task clearPasswords << {
		MrGadget mrg = new MrGadget(
			user:'someuser',
			host:'www.someuser.com',
			clearAllPasswords:true)				// passwords can be wiped from system prefs
	}