text:
#include <spine/Animation.h>
#include <spine/IkConstraint.h>
#include <limits.h>
#include <spine/extension.h>

spAnimation* spAnimation_create (const char* name, int timelinesCount) {
	spAnimation* self = NEW(spAnimation);
	MALLOC_STR(self->name, name);
	self->timelinesCount = timelinesCount;
	self->timelines = MALLOC(spTimeline*, timelinesCount);
	return self;
}

void spAnimation_dispose (spAnimation* self) {
	int i;
	for (i = 0; i < self->timelinesCount; ++i)
		spTimeline_dispose(self->timelines[i]);
	FREE(self->timelines);
	FREE(self->name);
	FREE(self);
}

void spAnimation_apply (const spAnimation* self, spSkeleton* skeleton, float lastTime, float time, int loop, spEvent** events,
		int* eventsCount) {
	int i, n = self->timelinesCount;

	if (loop && self->duration) {
		time = FMOD(time, self->duration);
		lastTime = FMOD(lastTime, self->duration);
	}

	for (i = 0; i < n; ++i)
		spTimeline_apply(self->timelines[i], skeleton, lastTime, time, events, eventsCount, 1);
}

void spAnimation_mix (const spAnimation* self, spSkeleton* skeleton, float lastTime, float time, int loop, spEvent** events,
		int* eventsCount, float alpha) {
	int i, n = self->timelinesCount;

	if (loop && self->duration) {
		time = FMOD(time, self->duration);
		lastTime = FMOD(lastTime, self->duration);
	}

	for (i = 0; i < n; ++i)
		spTimeline_apply(self->timelines[i], skeleton, lastTime, time, events, eventsCount, alpha);
}

/**/

typedef struct _spTimelineVtable {
	void (*apply) (const spTimeline* self, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
			int* eventsCount, float alpha);
	void (*dispose) (spTimeline* self);
} _spTimelineVtable;

void _spTimeline_init (spTimeline* self, spTimelineType type, /**/
void (*dispose) (spTimeline* self), /**/
		void (*apply) (const spTimeline* self, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
				int* eventsCount, float alpha)) {
	CONST_CAST(spTimelineType, self->type) = type;
	CONST_CAST(_spTimelineVtable*, self->vtable) = NEW(_spTimelineVtable);
	VTABLE(spTimeline, self)->dispose = dispose;
	VTABLE(spTimeline, self)->apply = apply;
}

void _spTimeline_deinit (spTimeline* self) {
	FREE(self->vtable);
}

void spTimeline_dispose (spTimeline* self) {
	VTABLE(spTimeline, self)->dispose(self);
}

void spTimeline_apply (const spTimeline* self, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
		int* eventsCount, float alpha) {
	VTABLE(spTimeline, self)->apply(self, skeleton, lastTime, time, firedEvents, eventsCount, alpha);
}

/**/

static const float CURVE_LINEAR = 0, CURVE_STEPPED = 1, CURVE_BEZIER = 2;
static const int BEZIER_SEGMENTS = 10, BEZIER_SIZE = 10 * 2 - 1;

void _spCurveTimeline_init (spCurveTimeline* self, spTimelineType type, int framesCount, /**/
void (*dispose) (spTimeline* self), /**/
		void (*apply) (const spTimeline* self, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
				int* eventsCount, float alpha)) {
	_spTimeline_init(SUPER(self), type, dispose, apply);
	self->curves = CALLOC(float, (framesCount - 1) * BEZIER_SIZE);
}

void _spCurveTimeline_deinit (spCurveTimeline* self) {
	_spTimeline_deinit(SUPER(self));
	FREE(self->curves);
}

void spCurveTimeline_setLinear (spCurveTimeline* self, int frameIndex) {
	self->curves[frameIndex * BEZIER_SIZE] = CURVE_LINEAR;
}

void spCurveTimeline_setStepped (spCurveTimeline* self, int frameIndex) {
	self->curves[frameIndex * BEZIER_SIZE] = CURVE_STEPPED;
}

void spCurveTimeline_setCurve (spCurveTimeline* self, int frameIndex, float cx1, float cy1, float cx2, float cy2) {
	float subdiv1 = 1.0f / BEZIER_SEGMENTS, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1;
	float pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3;
	float tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1;
	float dfx = cx1 * pre1 + tmp1x * pre2 + tmp2x * subdiv3, dfy = cy1 * pre1 + tmp1y * pre2 + tmp2y * subdiv3;
	float ddfx = tmp1x * pre4 + tmp2x * pre5, ddfy = tmp1y * pre4 + tmp2y * pre5;
	float dddfx = tmp2x * pre5, dddfy = tmp2y * pre5;
	float x = dfx, y = dfy;

	int i = frameIndex * BEZIER_SIZE, n = i + BEZIER_SIZE - 1;
	self->curves[i++] = CURVE_BEZIER;

	for (; i < n; i += 2) {
		self->curves[i] = x;
		self->curves[i + 1] = y;
		dfx += ddfx;
		dfy += ddfy;
		ddfx += dddfx;
		ddfy += dddfy;
		x += dfx;
		y += dfy;
	}
}

float spCurveTimeline_getCurvePercent (const spCurveTimeline* self, int frameIndex, float percent) {
	float x, y;
	int i = frameIndex * BEZIER_SIZE, start, n;
	float type = self->curves[i];
	if (type == CURVE_LINEAR) return percent;
	if (type == CURVE_STEPPED) return 0;
	i++;
	x = 0;
	for (start = i, n = i + BEZIER_SIZE - 1; i < n; i += 2) {
		x = self->curves[i];
		if (x >= percent) {
			float prevX, prevY;
			if (i == start) {
				prevX = 0;
				prevY = 0;
			} else {
				prevX = self->curves[i - 2];
				prevY = self->curves[i - 1];
			}
			return prevY + (self->curves[i + 1] - prevY) * (percent - prevX) / (x - prevX);
		}
	}
	y = self->curves[i - 1];
	return y + (1 - y) * (percent - x) / (1 - x); /* Last point is 1,1. */
}

/* @param target After the first and before the last entry. */
static int binarySearch (float *values, int valuesLength, float target, int step) {
	int low = 0, current;
	int high = valuesLength / step - 2;
	if (high == 0) return step;
	current = high >> 1;
	while (1) {
		if (values[(current + 1) * step] <= target)
			low = current + 1;
		else
			high = current;
		if (low == high) return (low + 1) * step;
		current = (low + high) >> 1;
	}
	return 0;
}

/* @param target After the first and before the last entry. */
static int binarySearch1 (float *values, int valuesLength, float target) {
	int low = 0, current;
	int high = valuesLength - 2;
	if (high == 0) return 1;
	current = high >> 1;
	while (1) {
		if (values[(current + 1)] <= target)
			low = current + 1;
		else
			high = current;
		if (low == high) return low + 1;
		current = (low + high) >> 1;
	}
	return 0;
}

/*static int linearSearch (float *values, int valuesLength, float target, int step) {
 int i, last = valuesLength - step;
 for (i = 0; i <= last; i += step) {
 if (values[i] <= target) continue;
 return i;
 }
 return -1;
 }*/

/**/

void _spBaseTimeline_dispose (spTimeline* timeline) {
	struct spBaseTimeline* self = SUB_CAST(struct spBaseTimeline, timeline);
	_spCurveTimeline_deinit(SUPER(self));
	FREE(self->frames);
	FREE(self);
}

/* Many timelines have structure identical to struct spBaseTimeline and extend spCurveTimeline. **/
struct spBaseTimeline* _spBaseTimeline_create (int framesCount, spTimelineType type, int frameSize, /**/
		void (*apply) (const spTimeline* self, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
				int* eventsCount, float alpha)) {
	struct spBaseTimeline* self = NEW(struct spBaseTimeline);
	_spCurveTimeline_init(SUPER(self), type, framesCount, _spBaseTimeline_dispose, apply);

	CONST_CAST(int, self->framesCount) = framesCount * frameSize;
	CONST_CAST(float*, self->frames) = CALLOC(float, self->framesCount);

	return self;
}

/**/

static const int ROTATE_PREV_FRAME_TIME = -2;
static const int ROTATE_FRAME_VALUE = 1;

void _spRotateTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
		int* eventsCount, float alpha) {
	spBone *bone;
	int frameIndex;
	float prevFrameValue, frameTime, percent, amount;

	spRotateTimeline* self = SUB_CAST(spRotateTimeline, timeline);

	if (time < self->frames[0]) return; /* Time is before first frame. */

	bone = skeleton->bones[self->boneIndex];

	if (time >= self->frames[self->framesCount - 2]) { /* Time is after last frame. */
		float amount = bone->data->rotation + self->frames[self->framesCount - 1] - bone->rotation;
		while (amount > 180)
			amount -= 360;
		while (amount < -180)
			amount += 360;
		bone->rotation += amount * alpha;
		return;
	}

	/* Interpolate between the previous frame and the current frame. */
	frameIndex = binarySearch(self->frames, self->framesCount, time, 2);
	prevFrameValue = self->frames[frameIndex - 1];
	frameTime = self->frames[frameIndex];
	percent = 1 - (time - frameTime) / (self->frames[frameIndex + ROTATE_PREV_FRAME_TIME] - frameTime);
	percent = spCurveTimeline_getCurvePercent(SUPER(self), (frameIndex >> 1) - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));

	amount = self->frames[frameIndex + ROTATE_FRAME_VALUE] - prevFrameValue;
	while (amount > 180)
		amount -= 360;
	while (amount < -180)
		amount += 360;
	amount = bone->data->rotation + (prevFrameValue + amount * percent) - bone->rotation;
	while (amount > 180)
		amount -= 360;
	while (amount < -180)
		amount += 360;
	bone->rotation += amount * alpha;
}

spRotateTimeline* spRotateTimeline_create (int framesCount) {
	return _spBaseTimeline_create(framesCount, SP_TIMELINE_ROTATE, 2, _spRotateTimeline_apply);
}

void spRotateTimeline_setFrame (spRotateTimeline* self, int frameIndex, float time, float angle) {
	frameIndex *= 2;
	self->frames[frameIndex] = time;
	self->frames[frameIndex + 1] = angle;
}

/**/

static const int TRANSLATE_PREV_FRAME_TIME = -3;
static const int TRANSLATE_FRAME_X = 1;
static const int TRANSLATE_FRAME_Y = 2;

void _spTranslateTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time,
		spEvent** firedEvents, int* eventsCount, float alpha) {
	spBone *bone;
	int frameIndex;
	float prevFrameX, prevFrameY, frameTime, percent;

	spTranslateTimeline* self = SUB_CAST(spTranslateTimeline, timeline);

	if (time < self->frames[0]) return; /* Time is before first frame. */

	bone = skeleton->bones[self->boneIndex];

	if (time >= self->frames[self->framesCount - 3]) { /* Time is after last frame. */
		bone->x += (bone->data->x + self->frames[self->framesCount - 2] - bone->x) * alpha;
		bone->y += (bone->data->y + self->frames[self->framesCount - 1] - bone->y) * alpha;
		return;
	}

	/* Interpolate between the previous frame and the current frame. */
	frameIndex = binarySearch(self->frames, self->framesCount, time, 3);
	prevFrameX = self->frames[frameIndex - 2];
	prevFrameY = self->frames[frameIndex - 1];
	frameTime = self->frames[frameIndex];
	percent = 1 - (time - frameTime) / (self->frames[frameIndex + TRANSLATE_PREV_FRAME_TIME] - frameTime);
	percent = spCurveTimeline_getCurvePercent(SUPER(self), frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));

	bone->x += (bone->data->x + prevFrameX + (self->frames[frameIndex + TRANSLATE_FRAME_X] - prevFrameX) * percent - bone->x)
			* alpha;
	bone->y += (bone->data->y + prevFrameY + (self->frames[frameIndex + TRANSLATE_FRAME_Y] - prevFrameY) * percent - bone->y)
			* alpha;
}

spTranslateTimeline* spTranslateTimeline_create (int framesCount) {
	return _spBaseTimeline_create(framesCount, SP_TIMELINE_TRANSLATE, 3, _spTranslateTimeline_apply);
}

void spTranslateTimeline_setFrame (spTranslateTimeline* self, int frameIndex, float time, float x, float y) {
	frameIndex *= 3;
	self->frames[frameIndex] = time;
	self->frames[frameIndex + 1] = x;
	self->frames[frameIndex + 2] = y;
}

/**/

void _spScaleTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
		int* eventsCount, float alpha) {
	spBone *bone;
	int frameIndex;
	float prevFrameX, prevFrameY, frameTime, percent;

	spScaleTimeline* self = SUB_CAST(spScaleTimeline, timeline);

	if (time < self->frames[0]) return; /* Time is before first frame. */

	bone = skeleton->bones[self->boneIndex];
	if (time >= self->frames[self->framesCount - 3]) { /* Time is after last frame. */
		bone->scaleX += (bone->data->scaleX * self->frames[self->framesCount - 2] - bone->scaleX) * alpha;
		bone->scaleY += (bone->data->scaleY * self->frames[self->framesCount - 1] - bone->scaleY) * alpha;
		return;
	}

	/* Interpolate between the previous frame and the current frame. */
	frameIndex = binarySearch(self->frames, self->framesCount, time, 3);
	prevFrameX = self->frames[frameIndex - 2];
	prevFrameY = self->frames[frameIndex - 1];
	frameTime = self->frames[frameIndex];
	percent = 1 - (time - frameTime) / (self->frames[frameIndex + TRANSLATE_PREV_FRAME_TIME] - frameTime);
	percent = spCurveTimeline_getCurvePercent(SUPER(self), frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));

	bone->scaleX += (bone->data->scaleX * (prevFrameX + (self->frames[frameIndex + TRANSLATE_FRAME_X] - prevFrameX) * percent)
			- bone->scaleX) * alpha;
	bone->scaleY += (bone->data->scaleY * (prevFrameY + (self->frames[frameIndex + TRANSLATE_FRAME_Y] - prevFrameY) * percent)
			- bone->scaleY) * alpha;
}

spScaleTimeline* spScaleTimeline_create (int framesCount) {
	return _spBaseTimeline_create(framesCount, SP_TIMELINE_SCALE, 3, _spScaleTimeline_apply);
}

void spScaleTimeline_setFrame (spScaleTimeline* self, int frameIndex, float time, float x, float y) {
	spTranslateTimeline_setFrame(self, frameIndex, time, x, y);
}

/**/

static const int COLOR_PREV_FRAME_TIME = -5;
static const int COLOR_FRAME_R = 1;
static const int COLOR_FRAME_G = 2;
static const int COLOR_FRAME_B = 3;
static const int COLOR_FRAME_A = 4;

void _spColorTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
		int* eventsCount, float alpha) {
	spSlot *slot;
	int frameIndex;
	float prevFrameR, prevFrameG, prevFrameB, prevFrameA, percent, frameTime;
	float r, g, b, a;
	spColorTimeline* self = (spColorTimeline*)timeline;

	if (time < self->frames[0]) return; /* Time is before first frame. */

	if (time >= self->frames[self->framesCount - 5]) {
		/* Time is after last frame. */
		int i = self->framesCount - 1;
		r = self->frames[i - 3];
		g = self->frames[i - 2];
		b = self->frames[i - 1];
		a = self->frames[i];
	} else {
		/* Interpolate between the previous frame and the current frame. */
		frameIndex = binarySearch(self->frames, self->framesCount, time, 5);
		prevFrameR = self->frames[frameIndex - 4];
		prevFrameG = self->frames[frameIndex - 3];
		prevFrameB = self->frames[frameIndex - 2];
		prevFrameA = self->frames[frameIndex - 1];
		frameTime = self->frames[frameIndex];
		percent = 1 - (time - frameTime) / (self->frames[frameIndex + COLOR_PREV_FRAME_TIME] - frameTime);
		percent = spCurveTimeline_getCurvePercent(SUPER(self), frameIndex / 5 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));

		r = prevFrameR + (self->frames[frameIndex + COLOR_FRAME_R] - prevFrameR) * percent;
		g = prevFrameG + (self->frames[frameIndex + COLOR_FRAME_G] - prevFrameG) * percent;
		b = prevFrameB + (self->frames[frameIndex + COLOR_FRAME_B] - prevFrameB) * percent;
		a = prevFrameA + (self->frames[frameIndex + COLOR_FRAME_A] - prevFrameA) * percent;
	}
	slot = skeleton->slots[self->slotIndex];
	if (alpha < 1) {
		slot->r += (r - slot->r) * alpha;
		slot->g += (g - slot->g) * alpha;
		slot->b += (b - slot->b) * alpha;
		slot->a += (a - slot->a) * alpha;
	} else {
		slot->r = r;
		slot->g = g;
		slot->b = b;
		slot->a = a;
	}
}

spColorTimeline* spColorTimeline_create (int framesCount) {
	return (spColorTimeline*)_spBaseTimeline_create(framesCount, SP_TIMELINE_COLOR, 5, _spColorTimeline_apply);
}

void spColorTimeline_setFrame (spColorTimeline* self, int frameIndex, float time, float r, float g, float b, float a) {
	frameIndex *= 5;
	self->frames[frameIndex] = time;
	self->frames[frameIndex + 1] = r;
	self->frames[frameIndex + 2] = g;
	self->frames[frameIndex + 3] = b;
	self->frames[frameIndex + 4] = a;
}

/**/

void _spAttachmentTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time,
		spEvent** firedEvents, int* eventsCount, float alpha) {
	int frameIndex;
	const char* attachmentName;
	spAttachmentTimeline* self = (spAttachmentTimeline*)timeline;

	if (time < self->frames[0]) {
		if (lastTime > time) _spAttachmentTimeline_apply(timeline, skeleton, lastTime, (float)INT_MAX, 0, 0, 0);
		return;
	} else if (lastTime > time) /**/
		lastTime = -1;

	frameIndex = time >= self->frames[self->framesCount - 1] ?
		self->framesCount - 1 : binarySearch1(self->frames, self->framesCount, time) - 1;
	if (self->frames[frameIndex] < lastTime) return;

	attachmentName = self->attachmentNames[frameIndex];
	spSlot_setAttachment(skeleton->slots[self->slotIndex],
			attachmentName ? spSkeleton_getAttachmentForSlotIndex(skeleton, self->slotIndex, attachmentName) : 0);
}

void _spAttachmentTimeline_dispose (spTimeline* timeline) {
	spAttachmentTimeline* self = SUB_CAST(spAttachmentTimeline, timeline);
	int i;

	_spTimeline_deinit(timeline);

	for (i = 0; i < self->framesCount; ++i)
		FREE(self->attachmentNames[i]);
	FREE(self->attachmentNames);
	FREE(self->frames);
	FREE(self);
}

spAttachmentTimeline* spAttachmentTimeline_create (int framesCount) {
	spAttachmentTimeline* self = NEW(spAttachmentTimeline);
	_spTimeline_init(SUPER(self), SP_TIMELINE_ATTACHMENT, _spAttachmentTimeline_dispose, _spAttachmentTimeline_apply);

	CONST_CAST(int, self->framesCount) = framesCount;
	CONST_CAST(float*, self->frames) = CALLOC(float, framesCount);
	CONST_CAST(char**, self->attachmentNames) = CALLOC(char*, framesCount);

	return self;
}

void spAttachmentTimeline_setFrame (spAttachmentTimeline* self, int frameIndex, float time, const char* attachmentName) {
	self->frames[frameIndex] = time;

	FREE(self->attachmentNames[frameIndex]);
	if (attachmentName)
		MALLOC_STR(self->attachmentNames[frameIndex], attachmentName);
	else
		self->attachmentNames[frameIndex] = 0;
}

/**/

/** Fires events for frames > lastTime and <= time. */
void _spEventTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
		int* eventsCount, float alpha) {
	spEventTimeline* self = (spEventTimeline*)timeline;
	int frameIndex;
	if (!firedEvents) return;

	if (lastTime > time) { /* Fire events after last time for looped animations. */
		_spEventTimeline_apply(timeline, skeleton, lastTime, (float)INT_MAX, firedEvents, eventsCount, alpha);
		lastTime = -1;
	} else if (lastTime >= self->frames[self->framesCount - 1]) /* Last time is after last frame. */
	return;
	if (time < self->frames[0]) return; /* Time is before first frame. */

	if (lastTime < self->frames[0])
		frameIndex = 0;
	else {
		float frame;
		frameIndex = binarySearch1(self->frames, self->framesCount, lastTime);
		frame = self->frames[frameIndex];
		while (frameIndex > 0) { /* Fire multiple events with the same frame. */
			if (self->frames[frameIndex - 1] != frame) break;
			frameIndex--;
		}
	}
	for (; frameIndex < self->framesCount && time >= self->frames[frameIndex]; ++frameIndex) {
		firedEvents[*eventsCount] = self->events[frameIndex];
		(*eventsCount)++;
	}
}

void _spEventTimeline_dispose (spTimeline* timeline) {
	spEventTimeline* self = SUB_CAST(spEventTimeline, timeline);
	int i;

	_spTimeline_deinit(timeline);

	for (i = 0; i < self->framesCount; ++i)
		spEvent_dispose(self->events[i]);
	FREE(self->events);
	FREE(self->frames);
	FREE(self);
}

spEventTimeline* spEventTimeline_create (int framesCount) {
	spEventTimeline* self = NEW(spEventTimeline);
	_spTimeline_init(SUPER(self), SP_TIMELINE_EVENT, _spEventTimeline_dispose, _spEventTimeline_apply);

	CONST_CAST(int, self->framesCount) = framesCount;
	CONST_CAST(float*, self->frames) = CALLOC(float, framesCount);
	CONST_CAST(spEvent**, self->events) = CALLOC(spEvent*, framesCount);

	return self;
}

void spEventTimeline_setFrame (spEventTimeline* self, int frameIndex, float time, spEvent* event) {
	self->frames[frameIndex] = time;

	FREE(self->events[frameIndex]);
	self->events[frameIndex] = event;
}

/**/

void _spDrawOrderTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time,
		spEvent** firedEvents, int* eventsCount, float alpha) {
	int i;
	int frameIndex;
	const int* drawOrderToSetupIndex;
	spDrawOrderTimeline* self = (spDrawOrderTimeline*)timeline;

	if (time < self->frames[0]) return; /* Time is before first frame. */

	if (time >= self->frames[self->framesCount - 1]) /* Time is after last frame. */
		frameIndex = self->framesCount - 1;
	else
		frameIndex = binarySearch1(self->frames, self->framesCount, time) - 1;

	drawOrderToSetupIndex = self->drawOrders[frameIndex];
	if (!drawOrderToSetupIndex)
		memcpy(skeleton->drawOrder, skeleton->slots, self->slotsCount * sizeof(spSlot*));
	else {
		for (i = 0; i < self->slotsCount; ++i)
			skeleton->drawOrder[i] = skeleton->slots[drawOrderToSetupIndex[i]];
	}
}

void _spDrawOrderTimeline_dispose (spTimeline* timeline) {
	spDrawOrderTimeline* self = SUB_CAST(spDrawOrderTimeline, timeline);
	int i;

	_spTimeline_deinit(timeline);

	for (i = 0; i < self->framesCount; ++i)
		FREE(self->drawOrders[i]);
	FREE(self->drawOrders);
	FREE(self->frames);
	FREE(self);
}

spDrawOrderTimeline* spDrawOrderTimeline_create (int framesCount, int slotsCount) {
	spDrawOrderTimeline* self = NEW(spDrawOrderTimeline);
	_spTimeline_init(SUPER(self), SP_TIMELINE_DRAWORDER, _spDrawOrderTimeline_dispose, _spDrawOrderTimeline_apply);

	CONST_CAST(int, self->framesCount) = framesCount;
	CONST_CAST(float*, self->frames) = CALLOC(float, framesCount);
	CONST_CAST(int**, self->drawOrders) = CALLOC(int*, framesCount);
	CONST_CAST(int, self->slotsCount) = slotsCount;

	return self;
}

void spDrawOrderTimeline_setFrame (spDrawOrderTimeline* self, int frameIndex, float time, const int* drawOrder) {
	self->frames[frameIndex] = time;

	FREE(self->drawOrders[frameIndex]);
	if (!drawOrder)
		self->drawOrders[frameIndex] = 0;
	else {
		self->drawOrders[frameIndex] = MALLOC(int, self->slotsCount);
		memcpy(CONST_CAST(int*, self->drawOrders[frameIndex]), drawOrder, self->slotsCount * sizeof(int));
	}
}

/**/

void _spFFDTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
		int* eventsCount, float alpha) {
	int frameIndex, i;
	float percent, frameTime;
	const float* prevVertices;
	const float* nextVertices;
	spFFDTimeline* self = (spFFDTimeline*)timeline;

	spSlot *slot = skeleton->slots[self->slotIndex];
	if (slot->attachment != self->attachment) return;

	if (time < self->frames[0]) return; /* Time is before first frame. */

	if (slot->attachmentVerticesCount < self->frameVerticesCount) {
		if (slot->attachmentVerticesCapacity < self->frameVerticesCount) {
			FREE(slot->attachmentVertices);
			slot->attachmentVertices = MALLOC(float, self->frameVerticesCount);
			slot->attachmentVerticesCapacity = self->frameVerticesCount;
		}
	}
	if (slot->attachmentVerticesCount != self->frameVerticesCount) alpha = 1; /* Don't mix from uninitialized slot vertices. */
	slot->attachmentVerticesCount = self->frameVerticesCount;

	if (time >= self->frames[self->framesCount - 1]) {
		/* Time is after last frame. */
		const float* lastVertices = self->frameVertices[self->framesCount - 1];
		if (alpha < 1) {
			for (i = 0; i < self->frameVerticesCount; ++i)
				slot->attachmentVertices[i] += (lastVertices[i] - slot->attachmentVertices[i]) * alpha;
		} else
			memcpy(slot->attachmentVertices, lastVertices, self->frameVerticesCount * sizeof(float));
		return;
	}

	/* Interpolate between the previous frame and the current frame. */
	frameIndex = binarySearch1(self->frames, self->framesCount, time);
	frameTime = self->frames[frameIndex];
	percent = 1 - (time - frameTime) / (self->frames[frameIndex - 1] - frameTime);
	percent = spCurveTimeline_getCurvePercent(SUPER(self), frameIndex - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));

	prevVertices = self->frameVertices[frameIndex - 1];
	nextVertices = self->frameVertices[frameIndex];

	if (alpha < 1) {
		for (i = 0; i < self->frameVerticesCount; ++i) {
			float prev = prevVertices[i];
			slot->attachmentVertices[i] += (prev + (nextVertices[i] - prev) * percent - slot->attachmentVertices[i]) * alpha;
		}
	} else {
		for (i = 0; i < self->frameVerticesCount; ++i) {
			float prev = prevVertices[i];
			slot->attachmentVertices[i] = prev + (nextVertices[i] - prev) * percent;
		}
	}
}

void _spFFDTimeline_dispose (spTimeline* timeline) {
	spFFDTimeline* self = SUB_CAST(spFFDTimeline, timeline);
	int i;

	_spCurveTimeline_deinit(SUPER(self));

	for (i = 0; i < self->framesCount; ++i)
		FREE(self->frameVertices[i]);
	FREE(self->frameVertices);
	FREE(self->frames);
	FREE(self);
}

spFFDTimeline* spFFDTimeline_create (int framesCount, int frameVerticesCount) {
	spFFDTimeline* self = NEW(spFFDTimeline);
	_spCurveTimeline_init(SUPER(self), SP_TIMELINE_FFD, framesCount, _spFFDTimeline_dispose, _spFFDTimeline_apply);
	CONST_CAST(int, self->framesCount) = framesCount;
	CONST_CAST(float*, self->frames) = CALLOC(float, self->framesCount);
	CONST_CAST(float**, self->frameVertices) = CALLOC(float*, framesCount);
	CONST_CAST(int, self->frameVerticesCount) = frameVerticesCount;
	return self;
}

void spFFDTimeline_setFrame (spFFDTimeline* self, int frameIndex, float time, float* vertices) {
	self->frames[frameIndex] = time;

	FREE(self->frameVertices[frameIndex]);
	if (!vertices)
		self->frameVertices[frameIndex] = 0;
	else {
		self->frameVertices[frameIndex] = MALLOC(float, self->frameVerticesCount);
		memcpy(CONST_CAST(float*, self->frameVertices[frameIndex]), vertices, self->frameVerticesCount * sizeof(float));
	}
}

/**/

static const int IKCONSTRAINT_PREV_FRAME_TIME = -3;
static const int IKCONSTRAINT_PREV_FRAME_MIX = -2;
static const int IKCONSTRAINT_PREV_FRAME_BEND_DIRECTION = -1;
static const int IKCONSTRAINT_FRAME_MIX = 1;

void _spIkConstraintTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time,
		spEvent** firedEvents, int* eventsCount, float alpha) {
	int frameIndex;
	float prevFrameMix, frameTime, percent, mix;
	spIkConstraint* ikConstraint;
	spIkConstraintTimeline* self = (spIkConstraintTimeline*)timeline;

	if (time < self->frames[0]) return; /* Time is before first frame. */

	ikConstraint = skeleton->ikConstraints[self->ikConstraintIndex];

	if (time >= self->frames[self->framesCount - 3]) { /* Time is after last frame. */
		ikConstraint->mix += (self->frames[self->framesCount - 2] - ikConstraint->mix) * alpha;
		ikConstraint->bendDirection = (int)self->frames[self->framesCount - 1];
		return;
	}

	/* Interpolate between the previous frame and the current frame. */
	frameIndex = binarySearch(self->frames, self->framesCount, time, 3);
	prevFrameMix = self->frames[frameIndex + IKCONSTRAINT_PREV_FRAME_MIX];
	frameTime = self->frames[frameIndex];
	percent = 1 - (time - frameTime) / (self->frames[frameIndex + IKCONSTRAINT_PREV_FRAME_TIME] - frameTime);
	percent = spCurveTimeline_getCurvePercent(SUPER(self), frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));

	mix = prevFrameMix + (self->frames[frameIndex + IKCONSTRAINT_FRAME_MIX] - prevFrameMix) * percent;
	ikConstraint->mix += (mix - ikConstraint->mix) * alpha;
	ikConstraint->bendDirection = (int)self->frames[frameIndex + IKCONSTRAINT_PREV_FRAME_BEND_DIRECTION];
}

spIkConstraintTimeline* spIkConstraintTimeline_create (int framesCount) {
	return (spIkConstraintTimeline*)_spBaseTimeline_create(framesCount, SP_TIMELINE_IKCONSTRAINT, 3, _spIkConstraintTimeline_apply);
}

void spIkConstraintTimeline_setFrame (spIkConstraintTimeline* self, int frameIndex, float time, float mix, int bendDirection) {
	frameIndex *= 3;
	self->frames[frameIndex] = time;
	self->frames[frameIndex + 1] = mix;
	self->frames[frameIndex + 2] = (float)bendDirection;
}

/**/

void _spFlipTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time,
		spEvent** firedEvents, int* eventsCount, float alpha) {
	int frameIndex;
	spFlipTimeline* self = (spFlipTimeline*)timeline;

	if (time < self->frames[0]) {
		if (lastTime > time) _spFlipTimeline_apply(timeline, skeleton, lastTime, (float)INT_MAX, 0, 0, 0);
		return;
	} else if (lastTime > time) /**/
		lastTime = -1;

	frameIndex = (time >= self->frames[self->framesCount - 2] ?
		self->framesCount : binarySearch(self->frames, self->framesCount, time, 2)) - 2;
	if (self->frames[frameIndex] < lastTime) return;

	if (self->x)
		skeleton->bones[self->boneIndex]->flipX = (int)self->frames[frameIndex + 1];
	else
		skeleton->bones[self->boneIndex]->flipY = (int)self->frames[frameIndex + 1];
}

void _spFlipTimeline_dispose (spTimeline* timeline) {
	spFlipTimeline* self = SUB_CAST(spFlipTimeline, timeline);
	_spTimeline_deinit(SUPER(self));
	FREE(self->frames);
	FREE(self);
}

spFlipTimeline* spFlipTimeline_create (int framesCount, int/*bool*/x) {
	spFlipTimeline* self = NEW(spFlipTimeline);
	_spTimeline_init(SUPER(self), x ? SP_TIMELINE_FLIPX : SP_TIMELINE_FLIPY, _spFlipTimeline_dispose, _spFlipTimeline_apply);
	CONST_CAST(int, self->x) = x;
	CONST_CAST(int, self->framesCount) = framesCount << 1;
	CONST_CAST(float*, self->frames) = CALLOC(float, self->framesCount);
	return self;
}

void spFlipTimeline_setFrame (spFlipTimeline* self, int frameIndex, float time, int/*bool*/flip) {
	frameIndex <<= 1;
	self->frames[frameIndex] = time;
	self->frames[frameIndex + 1] = (float)flip;
}

/**/


text:
package net.maiatday.a7minworkout.model;

import io.realm.RealmModel;
import io.realm.annotations.RealmClass;

/**
 * Remember the streak
 * Created by maia on 2017/03/30.
 */

@RealmClass
public class Streak implements RealmModel {
    int streak;
    Record lastWorkout;

    public int getStreak() {
        return streak;
    }

    public void setStreak(int streak) {
        this.streak = streak;
    }

    public Record getLastWorkout() {
        return lastWorkout;
    }

    public void setLastWorkout(Record lastWorkout) {
        this.lastWorkout = lastWorkout;
    }
}

redpajama_set_name: RedPajamaGithub


text:
title: "WithKeys"
---

# WithKeys

     Javadoc

Takes a `PCollection<V>` and produces a `PCollection<KV<K, V>>` by associating
each input element with a key.

There are two versions of `WithKeys`, depending on how the key should be determined:

* `WithKeys.of(SerializableFunction<V, K> fn)` takes a function to
  compute the key from each value.
* `WithKeys.of(K key)` associates each value with the specified key.

## Examples
**Example**
{{< highlight java >}}
PCollection<String> words = Create.of("Hello", "World", "Beam", "is", "fun");
PCollection<KV<Integer, String>> lengthAndWord =
  words.apply(WithKeys.of(new SerialiazableFunction<String, Integer>() {
    @Override
    public Integer apply(String s) {
      return s.length();
    }
  });
{{< /highlight >}}

## Related transforms
* [Keys](/documentation/transforms/java/elementwise/keys) for extracting the key of each component.
* [Values](/documentation/transforms/java/elementwise/values) for extracting the value of each element.
* [KvSwap](/documentation/transforms/java/elementwise/kvswap) swaps key-value pair values.


text:
@implementation UILabel (Addition)

+ (instancetype)labelWithText:(NSString*)text textColor:(UIColor*)textColor fontSize:(CGFloat)fontSize
{
    UILabel* label = [[self alloc] init];
    label.text = text;
    label.textColor = textColor;
    label.font = [UIFont systemFontOfSize:fontSize];
    return label;
}

@end


text:
class DressMonad {

  constructor(world, result, error) {
    this.world = world;
    this.result = result;
    this.error = error;
  }

  success(result) {
    return new DressMonad(this.world, result, undefined);
  }

  failure(context, error, causes) {
    error = { error };
    if (causes != null) { error.children = causes; }
    return new DressMonad(this.world, undefined, error);
  }

  find(collection, callback, onFailure) {
    const causes = [];
    for (const [i, element] of collection.entries()) {
      const m = callback(element, i);
      if (m.isSuccess()) {
        return m;
      } else {
        if (m.error.location == null) { setErrorLocation(m.error, element, i); }
        causes.push(m.error);
      }
    }
    return onFailure(causes);
  }

  refine(base, collection, callback, onFailure) {
    if (base.isSuccess()) {
      const causes = [];
      for (const [i, element] of collection.entries()) {
        const m = callback(base, element, i);
        if (m.isFailure()) {
          if (m.error.location == null) { setErrorLocation(m.error, element, i); }
          causes.push(m.error);
          if (this.isFailfast()) { break; }
        }
      }
      if (causes.length === 0) { return base; }
      return onFailure(causes);
    } else {
      return onFailure([base.error]);
    }
  }

  map(collection, mapper, onFailure) {
    const result = [];
    const success = this.success(result);
    const callback = function(_, elm, index) {
      const m = mapper(elm, index);
      return m.onSuccess((elmResult) => {
        result.push(elmResult);
        return m;
      });
    };
    return this.refine(success, collection, callback, onFailure);
  }

  isFailfast() {
    return this.world && this.world.failfast;
  }

  isSuccess() {
    return this.error === undefined;
  }

  isFailure() {
    return !this.isSuccess();
  }

  onSuccess(callback) {
    if (!this.isSuccess()) { return this; }
    return callback(this.result);
  }

  onFailure(callback) {
    if (this.isSuccess()) { return this; }
    return callback(this.error);
  }
}

const setErrorLocation = function(error, element, index) {
  let loc = element.name;
  if (loc == null) { loc = index; }
  return error.location = loc;
};

export default DressMonad;


text:
This Preprocessor sets your script to ignore backet errors.
This DOES NOT in any way, shape or form magically correct your script, it supresses the error log.

## Call

You can call the IgnoreBracketErrors Preprocessor by placing `#ignoreBracketErrors` inside your script file.
This Preprocessor is file-specific, so calling it on one file doesn't affect the others (at least not for what the processor's concerned.

## What it does

When the preprocessor is called on a file, all error logging on bracket errors will be supressed.
This doesn't change the affected lines in any way, instead the only change is that your log won't contain the regarding lines.


text:
package org.immutables.mongo.repository.internal;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Ints;
import com.google.common.primitives.UnsignedBytes;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonWriter;
import com.mongodb.DBCallback;
import com.mongodb.DBCollection;
import com.mongodb.DBDecoder;
import com.mongodb.DBDecoderFactory;
import com.mongodb.DBEncoder;
import com.mongodb.DBObject;
import com.mongodb.DefaultDBEncoder;
import com.mongodb.LazyDBCallback;
import de.undercouch.bson4jackson.BsonFactory;
import de.undercouch.bson4jackson.BsonGenerator;
import de.undercouch.bson4jackson.BsonParser;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.bson.BSONCallback;
import org.bson.BSONObject;
import org.bson.BasicBSONDecoder;
import org.bson.io.BasicOutputBuffer;
import org.bson.io.OutputBuffer;

/**
 * MongoDB driver specific encoding and jumping hoops.
 */
@SuppressWarnings("resource")
public final class BsonEncoding {
  private static final BsonFactory BSON_FACTORY = new BsonFactory()
      .enable(BsonParser.Feature.HONOR_DOCUMENT_LENGTH);

  private static final JsonFactory JSON_FACTORY = new JsonFactory()
      .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
      .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);

  /**
   * This field name will cause an MongoDB confuse if not unwrapped correctly so it's may be a good
   * choice.
   */
  private static final String PREENCODED_VALUE_WRAPPER_FIELD_NAME = "$";

  private BsonEncoding() {}

  /**
   * Although it may seem that re-parsing is bizarre, but it is one [of not so many] ways to do
   * proper marshaling. This kind of inefficiency will only hit query constraints that have many
   * object with custom marshaling, which considered to be a rare case.
   * @param adapted adapted value that know how to write itself to {@link JsonWriter}
   * @return object converted to MongoDB driver's {@link BSONObject}.
   */
  public static Object unwrapBsonable(Support.Adapted<?> adapted) {
    try {
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      BsonGenerator generator = BSON_FACTORY.createGenerator(outputStream);
      BsonWriter writer = new BsonWriter(generator);
      writer.beginObject().name(PREENCODED_VALUE_WRAPPER_FIELD_NAME);
      adapted.write(writer);
      writer.endObject();
      writer.close();
      BSONObject object = new BasicBSONDecoder().readObject(outputStream.toByteArray());
      return object.get(PREENCODED_VALUE_WRAPPER_FIELD_NAME);
    } catch (IOException ex) {
      throw Throwables.propagate(ex);
    }
  }

  public static DBObject unwrapJsonable(String json) {
    try {
      JsonParser parser = JSON_FACTORY.createParser(json);
      parser.nextToken();
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      BsonGenerator generator = BSON_FACTORY.createGenerator(outputStream);
      generator.copyCurrentStructure(parser);
      generator.close();
      parser.close();
      byte[] data = outputStream.toByteArray();
      return (DBObject) new LazyDBCallback(null).createObject(data, 0);
    } catch (IOException ex) {
      throw Throwables.propagate(ex);
    }
  }

  public static <T> T unmarshalDbObject(DBObject dbObject, TypeAdapter<T> adaper) throws IOException {
    BasicOutputBuffer buffer = new BasicOutputBuffer();
    encoder().writeObject(buffer, dbObject);
    BsonParser parser = BSON_FACTORY.createParser(buffer.toByteArray());
    BsonReader reader = new BsonReader(parser);
    T instance = adaper.read(reader);
    reader.close();
    return instance;
  }

  private static class CountingOutputBufferStream extends OutputStream {
    final OutputBuffer buffer;
    int count;

    CountingOutputBufferStream(OutputBuffer buffer) {
      this.buffer = buffer;
    }

    @Override
    public void write(byte[] bytes, int offset, int length) throws IOException {
      buffer.write(bytes, offset, length);
      count += length;
    }

    @Override
    public void write(int byteValue) throws IOException {
      buffer.write(byteValue);
      count++;
    }
  }

  public static DBEncoder encoder() {
    return Encoder.ENCODER;
  }

  enum Encoder implements DBEncoder {
    ENCODER;

    @Override
    public int writeObject(OutputBuffer buffer, BSONObject object) {
      try {
        if (object instanceof WritableObjectPosition) {
          return ((WritableObjectPosition) object).writePlainCurrent(buffer);
        }
        return DefaultDBEncoder.FACTORY.create().writeObject(buffer, object);
      } catch (IOException ex) {
        throw Throwables.propagate(ex);
      }
    }
  }

  public static <T> DBObject wrapUpdateObject(T instance, TypeAdapter<T> adaper) {
    return new UpdateObject<>(instance, adaper);
  }

  public static <T> List<DBObject> wrapInsertObjectList(ImmutableList<T> list, TypeAdapter<T> adaper) {
    return new InsertObjectList<>(list, adaper);
  }

  interface WritableObjectPosition {
    int writeCurrent(OutputBuffer buffer) throws IOException;

    int writePlainCurrent(OutputBuffer buffer) throws IOException;
  }

  private static class UpdateObject<T> implements DBObject, WritableObjectPosition {

    private final T instance;
    private final TypeAdapter<T> adaper;

    UpdateObject(T instance, TypeAdapter<T> adaper) {
      this.instance = instance;
      this.adaper = adaper;
    }

    @Override
    public int writeCurrent(OutputBuffer buffer) throws IOException {
      CountingOutputBufferStream outputStream = new CountingOutputBufferStream(buffer);
      BsonWriter writer = new BsonWriter(BSON_FACTORY.createGenerator(outputStream));
      adaper.write(writer, instance);
      writer.close();
      return outputStream.count;
    }

    @Override
    public int writePlainCurrent(OutputBuffer buffer) throws IOException {
      return writeCurrent(buffer);
    }

    @Override
    public Object put(String key, Object v) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(BSONObject o) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(Map m) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Object get(String key) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Map toMap() {
      throw new UnsupportedOperationException();
    }

    @Override
    public Object removeField(String key) {
      throw new UnsupportedOperationException();
    }

    @Deprecated
    @Override
    public boolean containsKey(String s) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean containsField(String s) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Set<String> keySet() {
      return ImmutableSet.of();
    }

    @Override
    public void markAsPartialObject() {}

    @Override
    public boolean isPartialObject() {
      return false;
    }
  }

  private static class InsertObjectList<T> implements DBObject, List<DBObject>, WritableObjectPosition {
    private final ImmutableList<T> list;
    private int position;
    @Nullable
    private JsonWriter writer;

    private CountingOutputBufferStream outputStream;
    private final TypeAdapter<T> adaper;

    InsertObjectList(ImmutableList<T> list, TypeAdapter<T> adaper) {
      this.list = list;
      this.adaper = adaper;
    }

    @Override
    public int writeCurrent(OutputBuffer buffer) throws IOException {
      createGeneratorIfNecessary(buffer);
      int previousByteCount = outputStream.count;
      adaper.write(writer, list.get(position));
      if (isLastPosition()) {
        closeWriter();
      }
      return outputStream.count - previousByteCount;
    }

    @Override
    public int writePlainCurrent(OutputBuffer buffer) throws IOException {
      CountingOutputBufferStream outputStream = new CountingOutputBufferStream(buffer);
      BsonWriter writer = new BsonWriter(BSON_FACTORY.createGenerator(outputStream));
      adaper.write(writer, list.get(position));
      writer.close();
      return outputStream.count;
    }

    private void closeWriter() throws IOException {
      if (writer != null) {
        writer.close();
        writer = null;
      }
    }

    private void createGeneratorIfNecessary(OutputBuffer buffer) throws IOException {
      if (writer == null) {
        outputStream = new CountingOutputBufferStream(buffer);
        writer = new BsonWriter(BSON_FACTORY.createGenerator(outputStream));
      }
    }

    private boolean isLastPosition() {
      return position == list.size() - 1;
    }

    @Override
    public DBObject get(int index) {
      position = index;
      return this;
    }

    @Override
    public int size() {
      return list.size();
    }

    @Override
    public Object put(String key, Object v) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(BSONObject o) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(Map m) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Object get(String key) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Map toMap() {
      throw new UnsupportedOperationException();
    }

    @Override
    public Object removeField(String key) {
      throw new UnsupportedOperationException();
    }

    @Deprecated
    @Override
    public boolean containsKey(String s) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean containsField(String s) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Set<String> keySet() {
      throw new UnsupportedOperationException();
    }

    @Override
    public void markAsPartialObject() {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean isPartialObject() {
      return false;
    }

    @Override
    public boolean add(DBObject e) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void add(int index, DBObject element) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean addAll(Collection<? extends DBObject> c) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean addAll(int index, Collection<? extends DBObject> c) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void clear() {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean contains(Object o) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean containsAll(Collection<?> c) {
      throw new UnsupportedOperationException();
    }

    @Override
    public int indexOf(Object o) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean isEmpty() {
      return false;
    }

    @Override
    public Iterator<DBObject> iterator() {
      return ImmutableSet.<DBObject>of().iterator();
    }

    @Override
    public int lastIndexOf(Object o) {
      throw new UnsupportedOperationException();
    }

    @Override
    public ListIterator<DBObject> listIterator() {
      return ImmutableList.<DBObject>of().listIterator();
    }

    @Override
    public ListIterator<DBObject> listIterator(int index) {
      return ImmutableList.<DBObject>of().listIterator();
    }

    @Override
    public DBObject set(int index, DBObject element) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean remove(Object o) {
      throw new UnsupportedOperationException();
    }

    @Override
    public DBObject remove(int index) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeAll(Collection<?> c) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean retainAll(Collection<?> c) {
      throw new UnsupportedOperationException();
    }

    @Override
    public List<DBObject> subList(int fromIndex, int toIndex) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Object[] toArray() {
      throw new UnsupportedOperationException();
    }

    @Override
    public <V> V[] toArray(V[] a) {
      throw new UnsupportedOperationException();
    }
  }

  public static <T> ImmutableList<T> unwrapResultObjectList(List<DBObject> result) {
    if (result.isEmpty()) {
      return ImmutableList.of();
    }
    // Safe as long as caller will use same T for decoder and unwrap
    @SuppressWarnings("unchecked") List<T> results = ((ResultDecoder<T>) result.get(0)).results;
    return ImmutableList.copyOf(results);
  }

  public static <T> DBDecoderFactory newResultDecoderFor(TypeAdapter<T> adaper, int expectedSize) {
    return new ResultDecoder<>(adaper, expectedSize);
  }

  /**
   * Special input stream that operates from as writable byte buffer that is filled with BSON object
   * from other input stream ({@link #resetObjectFrom(InputStream)}).
   * Extending buffered input stream
   * to prevent excessive wraping in another buffered stream by {@link BsonParser}
   */
  private static final class ObjectBufferInputStream extends BufferedInputStream {
    private byte[] buffer;
    private int position;
    private int limit;

    ObjectBufferInputStream(int capacity) {
      super(null, 1);
      ensureBufferWithCapacity(capacity);
    }

    private void ensureBufferWithCapacity(int capacity) {
      if (buffer == null || buffer.length < capacity) {
        Preconditions.checkArgument(capacity >= 4);
        byte[] temp = buffer;
        this.buffer = new byte[capacity];
        if (temp != null) {
          System.arraycopy(temp, 0, buffer, 0, temp.length);
        }
      }
    }

    void resetObjectFrom(InputStream inputStream) throws IOException {
      ByteStreams.readFully(inputStream, buffer, 0, Ints.BYTES);

      int objectSize = Ints.fromBytes(
          buffer[3],
          buffer[2],
          buffer[1],
          buffer[0]);

      ensureBufferWithCapacity(objectSize);

      ByteStreams.readFully(inputStream, buffer, Ints.BYTES, objectSize - Ints.BYTES);

      position = 0;
      limit = objectSize;
    }

    @Override
    public int available() throws IOException {
      return limit - position;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
      len = Math.min(len, available());
      System.arraycopy(buffer, position, b, off, len);
      position += len;
      return len;
    }

    @Override
    public int read() throws IOException {
      if (available() > 0) {
        return UnsignedBytes.toInt(buffer[position++]);
      }
      return -1;
    }
  }

  private static final class ResultDecoder<T> implements DBDecoderFactory, DBDecoder, DBObject {
    final List<T> results;
    private final TypeAdapter<T> adaper;
    @Nullable
    private BsonReader parser;

    private final ObjectBufferInputStream bufferStream = new ObjectBufferInputStream(2012);

    ResultDecoder(TypeAdapter<T> adaper, int expectedSize) {
      this.adaper = adaper;
      this.results = Lists.newArrayListWithExpectedSize(expectedSize);
    }

    private BsonReader createParserIfNecessary() throws IOException {
      if (parser != null) {
        parser.close();
      }
      parser = new BsonReader(BSON_FACTORY.createParser(bufferStream));
      return parser;
    }

    @Override
    public DBObject decode(InputStream inputStream, DBCollection collection) throws IOException {
      bufferStream.resetObjectFrom(inputStream);
      createParserIfNecessary();
      T object = adaper.read(parser);
      results.add(object);
      return this;
    }

    @Override
    public DBDecoder create() {
      return this;
    }

    @Override
    public BSONObject readObject(byte[] b) {
      throw new UnsupportedOperationException();
    }

    @Override
    public BSONObject readObject(InputStream in) throws IOException {
      throw new UnsupportedOperationException();
    }

    @Override
    public int decode(byte[] b, BSONCallback callback) {
      throw new UnsupportedOperationException();
    }

    @Override
    public int decode(InputStream in, BSONCallback callback) throws IOException {
      throw new UnsupportedOperationException();
    }

    @Override
    public DBCallback getDBCallback(DBCollection collection) {
      throw new UnsupportedOperationException();
    }

    @Override
    public DBObject decode(byte[] b, DBCollection collection) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Object put(String key, Object v) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(BSONObject o) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(Map m) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Object get(String key) {
      return null;
    }

    @Override
    public Map toMap() {
      throw new UnsupportedOperationException();
    }

    @Override
    public Object removeField(String key) {
      throw new UnsupportedOperationException();
    }

    @Deprecated
    @Override
    public boolean containsKey(String s) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean containsField(String s) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Set<String> keySet() {
      throw new UnsupportedOperationException();
    }

    @Override
    public void markAsPartialObject() {}

    @Override
    public boolean isPartialObject() {
      return false;
    }
  }
}


text:
namespace bbzy {
    namespace automatic {
        namespace detail {
            template<class ReleaseFunctionT>
            class ReleaseFunctionProperty {
            public:
                ReleaseFunctionProperty(ReleaseFunctionT &&releaseFunction) :
                        m_releaseFunction(std::forward<ReleaseFunctionT &&>(releaseFunction)) {
                }

            public:
                const ReleaseFunctionT &getReleaseFunction() const {
                    return m_releaseFunction;
                }

            protected:
                ReleaseFunctionT m_releaseFunction;
            };

            template<class ObjectT>
            class ReleaseObjectProperty {
            public:
                ReleaseObjectProperty(ObjectT *object) : m_object(object) {}

            public:
                ObjectT *getObject() const {
                    return m_object;
                }

            protected:
                ObjectT *m_object;
            };

            template<class ObjectT, class ReleaseFunctionT>
            class ReleaseObjectMemberFunction :
                    public ReleaseObjectProperty<ObjectT>,
                    public ReleaseFunctionProperty<ReleaseFunctionT> {
            public:
                ReleaseObjectMemberFunction(ObjectT *object, ReleaseFunctionT &&releaseFunction) :
                        ReleaseObjectProperty<ObjectT>(object),
                        ReleaseFunctionProperty<ReleaseFunctionT>(std::forward<ReleaseFunctionT &&>(releaseFunction)) {
                }

            protected:
                void release() {
                    release(nullptr);
                }

            private:
                template<class InnerReleaseFunctionT = ReleaseFunctionT,
                        class = EnableIf <type::IsMemberFunction<InnerReleaseFunctionT>::value>>
                void release(void *) {
                    (this->m_object->*this->m_releaseFunction)();
                }

                template<class InnerReleaseFunctionT = ReleaseFunctionT,
                        class = EnableIf < type::IsMemberFunction<InnerReleaseFunctionT>::value == false>,

                class

                = EnableIf<std::is_same<type::GetFunPT < 0, InnerReleaseFunctionT>, ObjectT *>::value>
                >

                void release(char *) {
                    this->m_releaseFunction(this->m_object);
                }

                template<class InnerReleaseFunctionT = ReleaseFunctionT,
                        class = EnableIf < type::IsMemberFunction<InnerReleaseFunctionT>::value == false>,

                class

                = EnableIf<std::is_same<type::GetFunPT < 0, InnerReleaseFunctionT>, ObjectT &>::value>
                >

                void release(short *) {
                    this->m_releaseFunction(*this->m_object);
                }
            };

            class CancellableProperty {
            public:
                void cancel() {
                    m_isCancelled = true;
                }

                bool isCancelled() const {
                    return m_isCancelled;
                }

                void reenable() {
                    m_isCancelled = false;
                }

            protected:
                bool m_isCancelled = false;
            };

            template<class ReleaseFunctionT>
            class Releaser : public ReleaseFunctionProperty<ReleaseFunctionT> {
            public:
                using ReleaseFunctionProperty<ReleaseFunctionT>::ReleaseFunctionProperty;

            public:
                ~Releaser() {
                    this->m_releaseFunction();
                }
            };

            template<class ObjectT, class ReleaseFunctionT>
            class ObjectReleaser : public ReleaseObjectMemberFunction<ObjectT, ReleaseFunctionT> {
            public:
                using ReleaseObjectMemberFunction<ObjectT, ReleaseFunctionT>::ReleaseObjectMemberFunction;

            public:
                ~ObjectReleaser() {
                    this->release();
                }
            };

            template<class ReleaseFunctionT>
            class CancellableReleaser :
                    public ReleaseFunctionProperty<ReleaseFunctionT>,
                    public CancellableProperty {
            public:
                using ReleaseFunctionProperty<ReleaseFunctionT>::ReleaseFunctionProperty;

            public:
                ~CancellableReleaser() {
                    if (this->m_isCancelled == false) {
                        this->m_releaseFunction();
                    }
                }

            };

            template<class ObjectT, class ReleaseFunctionT>
            class CancellableObjectReleaser :
                    public ReleaseObjectMemberFunction<ObjectT, ReleaseFunctionT>,
                    public CancellableProperty {
            public:
                using ReleaseObjectMemberFunction<ObjectT, ReleaseFunctionT>::ReleaseObjectMemberFunction;

            public:
                ~CancellableObjectReleaser() {
                    if (this->m_isCancelled == false) {
                        this->release();
                    }
                }
            };

        }

        template<class ReleaseFunctionT>
        inline detail::Releaser<ReleaseFunctionT> createReleaser(ReleaseFunctionT &&releaseFunction) {
            return detail::Releaser<ReleaseFunctionT>(
                    std::forward<ReleaseFunctionT &&>(releaseFunction));
        }

        template<class ObjectT, class ReleaseFunctionT>
        inline detail::ObjectReleaser<ObjectT, ReleaseFunctionT> createReleaser(
                ObjectT *object, ReleaseFunctionT &&releaseFunction) {
            return detail::ObjectReleaser<ObjectT, ReleaseFunctionT>(
                    object, std::forward<ReleaseFunctionT &&>(releaseFunction));
        }

        template<class ReleaseFunctionT>
        inline detail::CancellableReleaser<ReleaseFunctionT>
        createCancellableReleaser(ReleaseFunctionT &&releaseFunction) {
            return detail::CancellableReleaser<ReleaseFunctionT>(
                    std::forward<ReleaseFunctionT &&>(releaseFunction));
        }

        template<class ObjectT, class ReleaseFunctionT>
        inline detail::CancellableObjectReleaser<ObjectT, ReleaseFunctionT> createCancellableReleaser(
                ObjectT *object, ReleaseFunctionT &&releaseFunction) {
            return detail::CancellableObjectReleaser<ObjectT, ReleaseFunctionT>(
                    object, std::forward<ReleaseFunctionT &&>(releaseFunction));
        }
    }
}


text:
var _path = require('path');
var appPath = _path.dirname(require.main.filename);

var tcpInfo = require(_path.join(appPath, 'server', 'ProtocolBase', 'TCPPortInfo'));
var udpInfo = require(_path.join(appPath, 'server', 'ProtocolBase', 'UDPPortInfo'));

var protocolNumbers = {
  'icmp': 1,
  'igmp': 2,
  'tcp': 6,
  'udp': 17,
  'ipv4': 2048,
  'ipv6': 34525,
  'arp': 2054
};

function ProtocolExpert() {}

ProtocolExpert.getProtocolNumber = function(name) {
  return protocolNumbers[name.toLowerCase()];
};

ProtocolExpert.getProtocolName = function(number) {
  var result = undefined;

  for (var prop in protocolNumbers) {
    if (protocolNumbers.hasOwnProperty(prop)) {
      if (protocolNumbers[prop] === number) {
        result = prop;
        break;
      }
    }
  }

  return result;
};

ProtocolExpert.getPortNumber = function(serviceName, protocolNumber) {
  var result = '';

  if (protocolNumber == protocolNumbers['tcp']) {
    result = tcpInfo[serviceName.toLowerCase()];
  } else if (protocolNumber == protocolNumbers['udp']) {
    result = udpInfo[serviceName.toLowerCase()];
  }

  return result;
};

ProtocolExpert.getServiceName = function(portNumber, protocolNumber) {
  var result = 'unknown';
  var protocolInfo;

  if (protocolNumber == protocolNumbers['tcp']) {
    protocolInfo = tcpInfo;
  } else if (protocolNumber == protocolNumbers['udp']) {
    protocolInfo = udpInfo;
  }

  for (var prop in protocolInfo) {
    if (protocolInfo.hasOwnProperty(prop)) {
      if (protocolInfo[prop] === portNumber) {
        result = prop;
        break;
      }
    }
  }

  return result;
};

module.exports = ProtocolExpert;


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2013 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

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

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

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

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.plugin.illiesia;

import java.util.Iterator;
import java.util.regex.Pattern;

import org.lockss.daemon.*;
import org.lockss.extractor.ArticleMetadataExtractor;
import org.lockss.extractor.ArticleMetadataExtractorFactory;
import org.lockss.extractor.BaseArticleMetadataExtractor;
import org.lockss.extractor.MetadataTarget;
import org.lockss.plugin.*;
import org.lockss.util.Logger;

/*
 * Each article consists of a full text pdf and nothing else.  All abstracts
 * are listed in one page. ROLE_ARTICLE_METADATA can not be set.
 * BaseArticleMetadataExtractor provides default metadata from tdb file.
 *   Issue toc containing abstracts - <illiesiabase>/html/2013.html
 *   pdf - <illiesiabase>/papers/Illiesia09-01.pdf
 */
public class IlliesiaArticleIteratorFactory
  implements ArticleIteratorFactory, ArticleMetadataExtractorFactory {

  protected static Logger log =
      Logger.getLogger(IlliesiaArticleIteratorFactory.class);

  // Thib suggests to add /papers to ROOT_TEMPLATE and remove
  // from PATTERN_TEMPLATE
  protected static final String ROOT_TEMPLATE = "\"%s\", base_url";

  protected static final String PATTERN_TEMPLATE =
      "\"^%spapers/Illiesia[0-9]+-[0-9]+\\.pdf$\", base_url";

  // Thib recommends adding '/' at the beginning of of the pattern
  // as "/(.+\\.pdf)$" and replacement would be "/$1"
  private Pattern PDF_PATTERN =
      Pattern.compile("(.+\\.pdf)$", Pattern.CASE_INSENSITIVE);

  private static String PDF_REPLACEMENT = "$1";

  @Override
  public Iterator<ArticleFiles> createArticleIterator(ArchivalUnit au,
      MetadataTarget target) throws PluginException {

    SubTreeArticleIteratorBuilder builder =
                                        new SubTreeArticleIteratorBuilder(au);

    builder.setSpec(target,
        ROOT_TEMPLATE, PATTERN_TEMPLATE, Pattern.CASE_INSENSITIVE);

    // full text pdf - aspect that will trigger an ArticleFiles
    builder.addAspect(
        PDF_PATTERN, PDF_REPLACEMENT, ArticleFiles.ROLE_FULL_TEXT_PDF);

    return builder.getSubTreeArticleIterator();
  }

  @Override
  public ArticleMetadataExtractor createArticleMetadataExtractor(
      MetadataTarget target) throws PluginException {
    return new BaseArticleMetadataExtractor(null);
  }

}


text:
'use strict';
/*global CALC */

(CALC.visualizations.VectorField = function(title) {

    CALC.visualizations.Visualization.call( this, title );

}).extends(CALC.visualizations.Visualization, {

    init: function() {
        var scope = this;

        this.standardVisualizationSetup();
        var scene = this.scenes["std"];
        var camera = this.renderers["std"].camera.zoom(20, true);

        var objectBranch = new THREE.Object3D();
        var vectorBranch = new THREE.Object3D();
        objectBranch.add(vectorBranch);

        scene.add(objectBranch);

        objectBranch.rotation = new THREE.Vector3(Math.PI / 5, 0, 0);
		objectBranch.position.z = 0.5;

		var vectors = [];

		var x = CALC.parse('0-0.3*y');
		var y = CALC.parse('0.3*x');
		var maxRadius = 9;
		for (var h = -2; h < 3; ++h) {
			for (var t = 0; t < 2*Math.PI; t += Math.PI/8) {
				for (var r = 0.5; r < maxRadius; r += 1) {
					var radius = CALC.parse(r);

					var green = 0xff * (1 - r / maxRadius);
					green = Math.round(green) << 8;

					var color = 0xff0000 + green;

					var vector = new CALC.VectorArrow(x, y, 0, color);

					vector.position.set(Math.cos(t+0.5*r)*r, Math.sin(t+0.5*r)*r, h);
					vectorBranch.add(vector);
					vectors.push(vector);
				}
			}
		}

		var flow;
		flow = function() {
			CALC.animator.animate({
				milliseconds: 10000,
				interpolation: CALC.interpolations.linear,
				begin: function() {},
				step: function(t) {
					vectorBranch.rotation.z = 2* t * Math.PI;
				},
				end: function() {flow();}
			});
		};

		flow();

        this.renderers["std"].mouseStrategy = new CALC.NavigationStrategy(this.renderers["std"], objectBranch);

        // Step 0
        var $fnInfoDiv0 = $('

');
        var $infoParagraph0a = $('
Här åskådliggörs ett vektorfält <math><mi>A</mi></math> med hjälp av fältvektorerna <math><mi>A</mi><mfenced open="(" close=")"><msub><mi>P</mi><mi>i</mi></msub></mfenced></math> i en ändlig punktmängd <math><mfenced open="{" close="}"><msub><mi>P</mi><mi>i</mi></msub></mfenced>
');
        $fnInfoDiv0.append($infoParagraph0a);

        var step0 = new CALC.VisualizationStep("Funktionsytan", [
            new CALC.TextPanelAction({
                panel:          this.panels.text,
                elem:           $fnInfoDiv0
            })
        ]);

        this.setSteps([step0]);
        this.visitStep(0);

    }

});


text:
HOWTO
=====

###Question 1
Howto embed a YouTube clip with autoplay, full screen and no related videos on a webpage?
	[YouTube Gist] (https://gist.github.com/harishvc/14718d68ddd424d54c73)

###Question 2
How to flip mp4 around using command line?

    #Reference: http://stackoverflow.com/questions/3937387/rotating-videos-with-ffmpeg#
    $> ffmpeg -m   #Is ffmpeg installed?
    $> ffmpeg -i name.mp4   -vf "transpose=2,transpose=2" newname.mp4

###Resources
1. [GitHub Markdown Viewer](http://notepag.es/)
2. [Github Markdown Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)

[![Analytics](https://ga-beacon.appspot.com/UA-55381661-1/tools/howto/readme)](https://github.com/igrigorik/ga-beacon)


text:
using namespace std;
namespace po = boost::program_options;
using boost::asio::ip::tcp;

const string HOSTNAME = "api.openweathermap.org";
const string BASEPATH = "/data/2.5/weather?q=";

po::variables_map parse_args(int argc, char **argv) {
    po::options_description desc("Accepted options");
    desc.add_options()
        ("help", "produce help message")
        ("temp", "sort by temperature instead of location")
        ("location", po::value<vector<string> >(), "location(s)")
    ;

    po::positional_options_description p;
    p.add("location", -1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
    po::notify(vm);

    if (vm.count("help")) {
        cout << desc << "\n";
    }

    return vm;
}

class WeatherData {
public:
    WeatherData(string loc, string raw) {
        this->loc = loc;
        this->raw = raw;
    }

    string description() const {
        return this->loc + ": " + this->raw;
    }

    string location() const {
        return this->loc;
    }

private:
    string raw;
    string loc;
};

WeatherData *get_data(string location) {
    boost::asio::io_service io_service;
    tcp::resolver resolver(io_service);
    string path = BASEPATH + location;
    tcp::resolver::query query(HOSTNAME, "http");
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::socket socket(io_service);
    boost::asio::connect(socket, endpoint_iterator);
    boost::asio::streambuf request;
    std::ostream request_stream(&request);
    request_stream << "GET " << path << " HTTP/1.0\r\n";
    request_stream << "Host: " << HOSTNAME << "\r\n";
    request_stream << "Accept: application/json\r\n";
    request_stream << "Connection: close\r\n\r\n";
    boost::asio::write(socket, request);

    // Read the response status line. The response streambuf will automatically
    // grow to accommodate the entire line. The growth may be limited by passing
    // a maximum size to the streambuf constructor.
    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");

    // Check that response is OK.
    std::istream response_stream(&response);
    std::string http_version;
    response_stream >> http_version;
    unsigned int status_code;
    response_stream >> status_code;
    std::string status_message;
    std::getline(response_stream, status_message);
    if (!response_stream || http_version.substr(0, 5) != "HTTP/")
    {
      std::cout << "Invalid response\n";
      return nullptr;
    }
    if (status_code != 200)
    {
      std::cout << "Response returned with status code " << status_code << "\n";
      return nullptr;
    }

    // Read the response headers, which are terminated by a blank line.
    boost::asio::read_until(socket, response, "\r\n\r\n");

    // Process the response headers.
    std::string header;
    while (std::getline(response_stream, header) && header != "\r")
      ;

    stringstream content;
    // Write whatever content we already have to output.
    if (response.size() > 0)
      content << &response;

    // Read until EOF, writing data to output as we go.
    boost::system::error_code error;
    while (boost::asio::read(socket, response,
          boost::asio::transfer_at_least(1), error))
      content << &response;
    if (error != boost::asio::error::eof)
      throw boost::system::system_error(error);

    return new WeatherData(location, content.str());
}

int main(int argc, char **argv) {
    // First, parse input arguments
    po::variables_map vm = parse_args(argc, argv);

    // ... and quit if only 'help' was wanted
    if (vm.count("help")) {
        return 1;
    }

    // Ensure that we actually want to get weather for 1-or-more locations
    if (vm.count("location") < 1) {
        cerr << "No locations given" << endl;
        return 2;
    }
    auto locations = vm["location"].as<vector<string> >();

    // Check sorting order
    if (vm.count("temp")) {
        cout << "All righty, we'll sort by temperature instead of location" << endl;
    }

    // Fetch location data asynchronously
    vector<future<WeatherData*> > futures;
    for (auto location: locations)
    {
        futures.push_back(async(launch::async, get_data, location));
    }

    // Wait for the data to come back
    vector<WeatherData> data;
    for (auto &f: futures) {
        auto wd = f.get();
        if (wd) {
            data.push_back(*wd);
        }
    }

    // Set up and select sorting lambda to use (based on "--temp" input arg)
    auto location_sorter = [](const WeatherData l, const WeatherData r) -> bool {
        return l.location() < r.location();
    };
    auto temperature_sorter = [](const WeatherData l, const WeatherData r) -> bool {
        return l.location() > r.location(); // FIXME
    };
    auto selected_sorter = vm.count("temp") ? temperature_sorter : location_sorter;

    // Sort the data
    sort(data.begin(), data.end(), selected_sorter);

    // .. and finally display it
    for (auto wd: data) {
        cout << wd.description() << endl;
    }
    return 0;
}


text:
package com.blogspot.sontx.bottle.presenter;

import com.blogspot.sontx.bottle.model.bean.Category;
import com.blogspot.sontx.bottle.model.service.Callback;
import com.blogspot.sontx.bottle.model.service.FirebaseServicePool;
import com.blogspot.sontx.bottle.model.service.interfaces.BottleServerCategoryService;
import com.blogspot.sontx.bottle.presenter.interfaces.CategoryPresenter;
import com.blogspot.sontx.bottle.view.interfaces.ListCategoryView;

import java.util.List;

public class CategoryPresenterImpl extends PresenterBase implements CategoryPresenter {
    private final BottleServerCategoryService bottleServerCategoryService;
    private final ListCategoryView listCategoryView;

    public CategoryPresenterImpl(ListCategoryView listCategoryView) {
        this.listCategoryView = listCategoryView;
        this.bottleServerCategoryService = FirebaseServicePool.getInstance().getBottleServerCategoryService();
    }

    @Override
    public void getCategoriesAsync() {
        bottleServerCategoryService.getCategoriesAsync(new Callback<List<Category>>() {
            @Override
            public void onSuccess(List<Category> result) {
                listCategoryView.showCategories(result);
            }

            @Override
            public void onError(Throwable what) {
                listCategoryView.showErrorMessage(what);
            }
        });
    }
}


text:
import os
import linecache
from datetime import datetime

__all__ = ["Logger"]

class Logger(object):
    filename = ""
    log_path = ""

    def __init__(self, filename):
        self.log_path = os.getcwd()+os.sep+"log"+os.sep
        self.filename = filename

    def write(self, line):
        f = open(self.log_path+self.filename, 'a')
        f.write(line)
        f.close()

    def log(self, file, level, msg):
        self.write("%s - %s - %s - %s\n" % (
            datetime.now().isoformat(),
            level.upper(),
            file,
            msg))

    def exception(self, exc_type, exc_value, exc_traceback):
        filename = exc_traceback.tb_frame.f_code.co_filename
        lineno = exc_traceback.tb_lineno
        line = linecache.getline(filename, lineno)

        self.write("%s - ERROR - %s - Uncaught Exception at (%s:%s)\n" % (
            datetime.now().isoformat(),
            str(exc_type),
            str(filename),
            str(lineno)))


text:
@extends('admin.master')

@section('title')
@parent
- System Settings
@stop

@section('breadcrumb')
@parent

Settings

System

@stop

@section('page_title_icon')
hdd-o
@stop

@section('page_title')
System Settings
@stop

@section('page_title_right')

@stop

@section('content')

@if ($errors->has())

        @foreach ($errors->all() as $error)
            {{ $error }}

        @endforeach

@endif

		{{ Form::open(array('url'=>URL::route('systems.update', array($settings['id']->id)),'files'=>true, 'method'=>'PUT')) }}

				General

				Invoices

					<fieldset>

								logo }}" width="234" />

								Logo:

									<input type="file" id="file" name="logo" onchange="this.parentNode.nextSibling.value = this.value">Browse<input type="text" placeholder="Select Logo Image" readonly="">

								Date Format:

									{{ Form::select('date_format', $settings['date_format_list'], $settings['id']->date_format)}}

								Timezone:

									{{ Form::select('timezone', $settings['timezone_list'], $settings['id']->timezone)}}

								Paper Size:

									{{ Form::select('paper_size', $settings['paper_size_list'], $settings['id']->paper_size)}}

					</fieldset>
					<fieldset>

									<input type="text" name="company_name" placeholder="Company" value="{{ $settings['id']->company_name }}"/>

									<input type="text" name="reg_no" placeholder="Registration no." value="{{ $settings['id']->reg_no }}"/>

									<input type="text" name="office_no" placeholder="Office no." value="{{ $settings['id']->office_no }}"/>

									<input type="text" name="web_addr" placeholder="Web Address" value="{{ $settings['id']->web_addr }}"/>

								<textarea name="address" rows="3" class="custom-scroll" placeholder="Address">{{ $settings['id']->address }}</textarea>

					</fieldset>

					<fieldset>

								Invoice Prefix:

									<input type="text" name="invoice_prefix" placeholder="ICS" value="{{ $settings['id']->invoice_prefix }}"/>

								Year Prefix:

									{{ Form::select('year_prefix', array(0 => 'Yes', 1 => 'No'), $settings['id']->year_prefix)}}

								Month Prefix:

									{{ Form::select('month_prefix', array(0 => 'Yes', 1 => 'No'), $settings['id']->month_prefix)}}

								Left Pad:

									<input type="text" name="left_pad" placeholder="0" value="{{ $settings['id']->left_pad }}"/>

								Next ID:

									<input type="text" disabled="" name="invoice_next_id" placeholder="Next ID"/>

							{{ $settings['prefix_format'] }}

					</fieldset>

			{{ Form::button('Save',array('class'=>'btn btn-primary','type'=>'submit') )}}
			{{ Form::reset('Reset form', array('class'=>'btn btn-default','id'=>'reset_form')) }}

		{{Form::close()}}

@stop

@section('document_ready')
	// Single Image Preview
	$('#file').on('change', function(event) {
		var image = this.files[0];
		var reader = new FileReader();

		reader.readAsDataURL(image);
		reader.onload = function(e) {
			$('#original_image').hide();
			$('#preview_image').attr('src', e.target.result).show();
	 	}
	});

	$('#reset_form').click(function() {
		$('#original_image').show();
		$('#preview_image').attr('src', '').hide();
	});
@stop


text:
package org.deeplearning4j.spark.datavec.iterator;

import lombok.Data;
import org.datavec.api.records.SequenceRecord;
import org.datavec.api.records.metadata.RecordMetaData;
import org.datavec.api.records.reader.SequenceRecordReader;
import org.datavec.api.writable.Writable;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.List;

@Data
public class SparkSourceDummySeqReader extends SparkSourceDummyReader implements SequenceRecordReader {

    /**
     * @param readerIdx Index of the reader, in terms of the sequence RDD that it should use. For a single sequence RDD
     *                  as input, this is always 0; for 2 sequence RDDs used as input, this would be 0 or 1, depending
     *                  on whether it should pull values from the first or second sequence RDD. Note that the indexing
     *                  for sequence RDDs doesn't depend on the presence of non-sequence RDDs - they are indexed separately.
     */
    public SparkSourceDummySeqReader(int readerIdx) {
        super(readerIdx);
    }

    @Override
    public List<List<Writable>> sequenceRecord() {
        throw new UnsupportedOperationException();
    }

    @Override
    public List<List<Writable>> sequenceRecord(URI uri, DataInputStream dataInputStream) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public SequenceRecord nextSequence() {
        throw new UnsupportedOperationException();
    }

    @Override
    public SequenceRecord loadSequenceFromMetaData(RecordMetaData recordMetaData) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public List<SequenceRecord> loadSequenceFromMetaData(List<RecordMetaData> list) throws IOException {
        throw new UnsupportedOperationException();
    }
}


text:
<?php
// This file was auto-generated from sdk-root/src/data/transcribe/2017-10-26/paginators-1.json
return [ 'pagination' => [ 'ListTranscriptionJobs' => [ 'input_token' => 'NextToken', 'output_token' => 'NextToken', 'limit_key' => 'MaxResults', ], ],];


text:
package im.actor.images.loading.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.View;

import im.actor.images.cache.BitmapReference;
import im.actor.images.loading.ImageLoader;
import im.actor.images.loading.ImageLoaderProvider;
import im.actor.images.loading.ImageReceiver;
import im.actor.images.loading.ReceiverCallback;
import im.actor.images.loading.AbsTask;

/**
 * Created by ex3ndr on 06.09.14.
 */
public class ImageReceiverView extends View implements ReceiverCallback {
    private ImageReceiver receiver;

    public ImageReceiverView(Context context) {
        super(context);
        init();
    }

    public ImageReceiverView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ImageReceiverView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        if (getContext().getApplicationContext() instanceof ImageLoaderProvider) {
            ImageLoader loader = ((ImageLoaderProvider) getContext().getApplicationContext()).getImageLoader();
            receiver = loader.createReceiver(this);
        } else {
            throw new RuntimeException("Application does not implement ImageLoaderProvider");
        }
    }

    public void request(AbsTask absTask) {
        receiver.request(absTask);
    }

    public void requestSwitch(AbsTask absTask) {
        receiver.request(absTask, false);
    }

    public void clear() {
        receiver.clear();
    }

    public void close() {
        receiver.close();
    }

    protected Bitmap getBitmap() {
        BitmapReference reference = receiver.getReference();
        if (reference != null && !reference.isReleased()) {
            return reference.getBitmap();
        } else {
            return null;
        }
    }

    @Override
    public final void onImageLoaded(BitmapReference bitmap) {
        onImageLoadedImpl(bitmap.getBitmap());
        invalidate();
    }

    @Override
    public final void onImageCleared() {
        onImageClearedImpl();
        invalidate();
    }

    @Override
    public final void onImageError() {
        invalidate();
    }

    protected void onImageLoadedImpl(Bitmap bitmap) {

    }

    protected void onImageClearedImpl() {

    }
}


text:
<?php

/**
 * IShowTriggersWhereStatement interface file.
 *
 * @author Anastaszor
 */
interface IShowTriggersWhereStatement extends IShowTriggersStatement
{

	/**
	 *
	 * @return IWhereStatement
	 */
	public function getWhereStatement();

}


text:
"use strict";

var mysql = require("mysql");
var config = require('./config');

var pool = mysql.createPool({
    host: config.dbHost,
    user: config.dbUser,
    password: config.dbPassword,
    database: config.dbName
});

function getCurso(id, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("SELECT * FROM `cursos` WHERE `cursos`.`id` = ?", [id],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    if (typeof result[0] === "undefined") {
                        callback(null);
                    } else {
                        if (result[0].imagen === null || isEmpty(result[0].imagen))
                            var imagen = "";
                        else {
                            var imagen = result[0].imagen.replace(/\\/g, '\\');
                        }
                        callback(null, {
                            titulo: result[0].titulo,
                            descripcion: result[0].descripcion,
                            localidad: result[0].localidad,
                            direccion: result[0].direccion,
                            plazas: result[0].plazas,
                            fecha_inicio: result[0].fecha_inicio,
                            fecha_finalizacion: result[0].fecha_finalizacion,
                            imagen: imagen
                        });
                    }
                });
        }
    });
};

function altaCurso(curso, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("INSERT INTO `cursos` " +
                "(`titulo`, `descripcion`, `localidad`, `direccion`, `plazas`, `fecha_inicio`, `fecha_finalizacion`) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?);", [curso.titulo,
                    curso.descripcion,
                    curso.localidad,
                    curso.direccion,
                    curso.plazas,
                    curso.fecha_inicio,
                    curso.fecha_finalizacion
                ],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    callback(null, result.insertId);
                });
        }
    });
};

function updateCurso(id, curso, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("UPDATE `cursos` " +
                "SET `titulo` = ?, " +
                "`descripcion` = ?, " +
                "`localidad` = ?, " +
                "`direccion` = ?, " +
                "`plazas` = ?, " +
                "`fecha_inicio` = ?, " +
                "`fecha_finalizacion` = ? " +
                " WHERE `cursos`.`id` = ?", [curso.titulo,
                    curso.descripcion,
                    curso.localidad,
                    curso.direccion,
                    curso.plazas,
                    curso.fecha_inicio,
                    curso.fecha_finalizacion,
                    id
                ],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    callback(null, result.affectedRows);
                });
        }
    });
};

function bajaCurso(id, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("DELETE FROM `cursos` WHERE `cursos`.`id` = ?", [id],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    callback(null);
                });
        }
    });
};

function buscarPorNombre(string, num, pos, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("SELECT `id`,`titulo`,`localidad`,`fecha_inicio`,`fecha_finalizacion`,`plazas`" +
                "FROM `cursos` " +
                "WHERE `titulo` LIKE ? " +
                "ORDER BY `fecha_inicio` " +
                "LIMIT ? OFFSET ?", [string, num, pos],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    if (typeof result === "undefined") {
                        callback(null);
                    } else {
                        meterVacantesACursos(result.length, result, function(err, cursos) {
                            if (err) {
                                callback(err);
                            } else {
                                callback(null, cursos);
                            }
                        });
                    }
                });
        }
    });
};

function resultadosPorNombre(string, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("SELECT count(*) AS resultados " +
                "FROM `cursos` " +
                "WHERE `titulo` LIKE ?", [string],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    if (typeof result === "undefined") {
                        callback(null);
                    } else {
                        callback(null, result[0].resultados);
                    }
                });
        }
    });
}

function subirImagen(callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("", [],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                });
        }
    });
}

function existeCurso(id, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("SELECT `id` FROM cursos WHERE `id`=?", [id],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    callback(null, result[0]);
                });
        }
    });
}

function quedanPlazas(id, callback) {
    getCurso(id, function(err, curso) {
        if (err) {
            callback(err);
        } else if (typeof curso === "undefined") {
            callback(null, false);
        } else {
            var dao = require("./dao_inscripciones");
            dao.getNumeroInscritos(id, function(err, inscritos) {
                if (err) {
                    callback(err);
                } else {
                    callback(null, curso.plazas - inscritos > 0);
                }
            });
        }
    });
}

// usado en buscarPorNombre
function meterVacantesACursos(cursos_restantes, cursos, callback) {
    if (cursos_restantes === 0)
        callback(null, cursos);
    else {
        var dao = require("./dao_inscripciones");
        dao.getNumeroInscritos(cursos[cursos_restantes - 1].id, function(err, inscritos) {
            if (err) {
                callback(err);
            } else {
                cursos[cursos_restantes - 1].vacantes = cursos[cursos_restantes - 1].plazas - inscritos;
                cursos_restantes--;
                meterVacantesACursos(cursos_restantes, cursos, callback);
            }
        });
    }
}

function insertarImagen(id_curso, ruta, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("UPDATE `cursos` SET `imagen` = ? WHERE `cursos`.`id` = ?;", [ruta, id_curso],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    callback(null, ruta);
                });
        }
    });
}

function getImagen(id_curso, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("SELECT `imagen` FROM `cursos` WHERE `cursos`.`id` = ?", [id_curso],
                function(err, result) {
                    conexion.release();
                    if (err) {
                        callback(err);
                    } else if (result.length === 0) {
                        callback(null, undefined);
                    } else if (typeof result === "undefined") {
                        callback(null, undefined);
                    } else {
                        callback(null, result[0].imagen);
                    }
                });
        }
    });
}

function insertarHorario(id_curso, dia_semana, hora_inicio, hora_finalizacion, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("INSERT INTO `horarios` (`id`, `curso`, `dia_semana`, `hora_inicio`, `hora_finalizacion`) " + "VALUES (NULL, ?, ?, ?, ?)", [id_curso, dia_semana, hora_inicio, hora_finalizacion],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    callback(null);
                });
        }
    });
}

function borrarHorario(id_curso, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("DELETE FROM `horarios` WHERE `horarios`.`curso` = ?", [id_curso],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    callback(null);
                });
        }
    });
}

function getHorario(id_curso, callback) {
    if (callback === undefined) callback = function() {};
    pool.getConnection(function(err, conexion) {
        if (err) {
            callback(err);
        } else {
            conexion.query("SELECT * FROM `horarios` WHERE `curso` = ?", [id_curso],
                function(err, result) {
                    if (err) {
                        callback(err);
                    }
                    conexion.release();
                    if (typeof result === "undefined") {
                        callback(null, []);
                    } else
                        callback(null, result);
                });
        }
    });
}

module.exports = {
    quedanPlazas: quedanPlazas,
    existeCurso: existeCurso,
    subirImagen: subirImagen,
    resultadosPorNombre: resultadosPorNombre,
    buscarPorNombre: buscarPorNombre,
    bajaCurso: bajaCurso,
    updateCurso: updateCurso,
    altaCurso: altaCurso,
    getCurso: getCurso,
    insertarImagen: insertarImagen,
    insertarHorario: insertarHorario,
    borrarHorario: borrarHorario,
    getHorario: getHorario,
    getImagen: getImagen
};

function isEmpty(elem) {
    return elem.length === 0 || !elem.trim();
}


text:
package nats;

import nats.client.Message;
import nats.client.MessageHandler;
import nats.client.MessageIterator;
import nats.client.Nats;
import nats.client.NatsConnector;
import nats.client.Subscription;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;

/**
 * @author Mike Heath
 */
public class PerfTest {
	public static void main(String[] args) throws Exception {
		final NatsConnector builder = new NatsConnector().addHost("nats://localhost");
		final Nats sender = builder.connect();
		for (int i = 100; i <= 1000; i += 100) {
			final Collection<Nats> connections = new ArrayList<Nats>(i);
			for (int j = 0; j < i; j++) {
				connections.add(builder.connect());
			}
			// Warm up.
			System.out.println("Warming up");
			time(sender, "warmup", connections, 1000);
			Thread.sleep(1000);
			System.out.println("Warming up 2");
			time(sender, "warmup2", connections, 1000);
			Thread.sleep(1000);
			System.out.println("Running test.");
			long time = time(sender, "test.load", connections, 1);
			System.out.printf("Time for %d connections, %d\n", i, time);
			for (Nats nats : connections) {
				nats.close();
			}
		}
	}

	private static long time(Nats sender, String subject, Collection<Nats> connections, int messageCount) throws Exception {
		final CountDownLatch latch = new CountDownLatch(connections.size() * messageCount);
		final String message = createMessage(1024);
		final MessageHandler messageHandler = new MessageHandler() {
			@Override
			public void onMessage(Message message) {
				latch.countDown();
			}
		};
		for (Nats nats : connections) {
			nats.subscribe(subject).addMessageHandler(messageHandler);
		}
		Thread.sleep(1000);
		long start = System.currentTimeMillis();
		for (int i = 0; i < messageCount; i++) {
			sender.publish(subject, message);
		}
		latch.await();
		return System.currentTimeMillis() - start;
	}

	private static String createMessage(int size) {
		final String alphabet = "abcdefghijklmnopqrstuvwxyz";
		char[] message = new char[size];
		for (int i = 0; i < size; i++) {
			message[i] = alphabet.charAt(i % alphabet.length());
		}
		return new String(message);
	}

	private static void blockUntilConnected(Collection<Nats> connections) {
		for (Nats nats : connections) {
			final Subscription subscription = nats.subscribe("test");
			final MessageIterator iterator = subscription.iterator();
			nats.publish("test", "Have a nice day.");
			iterator.next();
			subscription.close();
		}
	}
}