text:
/*
 *  Reference counting implementation.
 */

#include "duk_internal.h"

#ifdef DUK_USE_REFERENCE_COUNTING

#ifndef DUK_USE_DOUBLE_LINKED_HEAP
#error internal error, reference counting requires a double linked heap
#endif

/*
 *  Misc
 */

DUK_LOCAL void duk__queue_refzero(duk_heap *heap, duk_heaphdr *hdr) {
	/* tail insert: don't disturb head in case refzero is running */

	if (heap->refzero_list != NULL) {
		duk_heaphdr *hdr_prev;

		hdr_prev = heap->refzero_list_tail;
		DUK_ASSERT(hdr_prev != NULL);
		DUK_ASSERT(DUK_HEAPHDR_GET_NEXT(heap, hdr_prev) == NULL);

		DUK_HEAPHDR_SET_NEXT(heap, hdr, NULL);
		DUK_HEAPHDR_SET_PREV(heap, hdr, hdr_prev);
		DUK_HEAPHDR_SET_NEXT(heap, hdr_prev, hdr);
		DUK_ASSERT_HEAPHDR_LINKS(heap, hdr);
		DUK_ASSERT_HEAPHDR_LINKS(heap, hdr_prev);
		heap->refzero_list_tail = hdr;
	} else {
		DUK_ASSERT(heap->refzero_list_tail == NULL);
		DUK_HEAPHDR_SET_NEXT(heap, hdr, NULL);
		DUK_HEAPHDR_SET_PREV(heap, hdr, NULL);
		DUK_ASSERT_HEAPHDR_LINKS(heap, hdr);
		heap->refzero_list = hdr;
		heap->refzero_list_tail = hdr;
	}
}

/*
 *  Heap object refcount finalization.
 *
 *  When an object is about to be freed, all other objects it refers to must
 *  be decref'd.  Refcount finalization does NOT free the object or its inner
 *  allocations (mark-and-sweep shares these helpers), it just manipulates
 *  the refcounts.
 *
 *  Note that any of the decref's may cause a refcount to drop to zero, BUT
 *  it will not be processed inline; instead, because refzero is already
 *  running, the objects will just be queued to refzero list and processed
 *  later.  This eliminates C recursion.
 */

DUK_LOCAL void duk__refcount_finalize_hobject(duk_hthread *thr, duk_hobject *h) {
	duk_uint_fast32_t i;

	DUK_ASSERT(h);
	DUK_ASSERT(DUK_HEAPHDR_GET_TYPE((duk_heaphdr *) h) == DUK_HTYPE_OBJECT);

	/* XXX: better to get base and walk forwards? */

	for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ENEXT(h); i++) {
		duk_hstring *key = DUK_HOBJECT_E_GET_KEY(thr->heap, h, i);
		if (!key) {
			continue;
		}
		duk_heaphdr_decref(thr, (duk_heaphdr *) key);
		if (DUK_HOBJECT_E_SLOT_IS_ACCESSOR(thr->heap, h, i)) {
			duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_GETTER(thr->heap, h, i));
			duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_SETTER(thr->heap, h, i));
		} else {
			duk_tval_decref(thr, DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(thr->heap, h, i));
		}
	}

	for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ASIZE(h); i++) {
		duk_tval_decref(thr, DUK_HOBJECT_A_GET_VALUE_PTR(thr->heap, h, i));
	}

	/* hash part is a 'weak reference' and does not contribute */

	duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) DUK_HOBJECT_GET_PROTOTYPE(thr->heap, h));

	if (DUK_HOBJECT_IS_COMPILEDFUNCTION(h)) {
		duk_hcompiledfunction *f = (duk_hcompiledfunction *) h;
		duk_tval *tv, *tv_end;
		duk_hobject **funcs, **funcs_end;

		if (DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, f) != NULL) {
			tv = DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE(thr->heap, f);
			tv_end = DUK_HCOMPILEDFUNCTION_GET_CONSTS_END(thr->heap, f);
			while (tv < tv_end) {
				duk_tval_decref(thr, tv);
				tv++;
			}

			funcs = DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE(thr->heap, f);
			funcs_end = DUK_HCOMPILEDFUNCTION_GET_FUNCS_END(thr->heap, f);
			while (funcs < funcs_end) {
				duk_heaphdr_decref(thr, (duk_heaphdr *) *funcs);
				funcs++;
			}
		} else {
			/* May happen in some out-of-memory corner cases. */
			DUK_D(DUK_DPRINT("duk_hcompiledfunction 'data' is NULL, skipping decref"));
		}

		duk_heaphdr_decref(thr, (duk_heaphdr *) DUK_HCOMPILEDFUNCTION_GET_DATA(thr->heap, f));
	} else if (DUK_HOBJECT_IS_NATIVEFUNCTION(h)) {
		duk_hnativefunction *f = (duk_hnativefunction *) h;
		DUK_UNREF(f);
		/* nothing to finalize */
	} else if (DUK_HOBJECT_IS_BUFFEROBJECT(h)) {
		duk_hbufferobject *b = (duk_hbufferobject *) h;
		if (b->buf) {
			duk_heaphdr_decref(thr, (duk_heaphdr *) b->buf);
		}
	} else if (DUK_HOBJECT_IS_THREAD(h)) {
		duk_hthread *t = (duk_hthread *) h;
		duk_tval *tv;

		tv = t->valstack;
		while (tv < t->valstack_top) {
			duk_tval_decref(thr, tv);
			tv++;
		}

		for (i = 0; i < (duk_uint_fast32_t) t->callstack_top; i++) {
			duk_activation *act = t->callstack + i;
			duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) DUK_ACT_GET_FUNC(act));
			duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) act->var_env);
			duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) act->lex_env);
#ifdef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY
			duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) act->prev_caller);
#endif
		}

#if 0  /* nothing now */
		for (i = 0; i < (duk_uint_fast32_t) t->catchstack_top; i++) {
			duk_catcher *cat = t->catchstack + i;
		}
#endif

		for (i = 0; i < DUK_NUM_BUILTINS; i++) {
			duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) t->builtins[i]);
		}

		duk_heaphdr_decref_allownull(thr, (duk_heaphdr *) t->resumer);
	}
}

DUK_INTERNAL void duk_heaphdr_refcount_finalize(duk_hthread *thr, duk_heaphdr *hdr) {
	DUK_ASSERT(hdr);

	switch ((int) DUK_HEAPHDR_GET_TYPE(hdr)) {
	case DUK_HTYPE_OBJECT:
		duk__refcount_finalize_hobject(thr, (duk_hobject *) hdr);
		break;
	case DUK_HTYPE_BUFFER:
		/* nothing to finalize */
		break;
	case DUK_HTYPE_STRING:
		/* cannot happen: strings are not put into refzero list (they don't even have the next/prev pointers) */
	default:
		DUK_UNREACHABLE();
	}
}

#if defined(DUK_USE_REFZERO_FINALIZER_TORTURE)
DUK_LOCAL duk_ret_t duk__refcount_fake_finalizer(duk_context *ctx) {
	DUK_UNREF(ctx);
	DUK_D(DUK_DPRINT("fake refcount torture finalizer executed"));
#if 0
	DUK_DD(DUK_DDPRINT("fake torture finalizer for: %!T", duk_get_tval(ctx, 0)));
#endif
	/* Require a lot of stack to force a value stack grow/shrink. */
	duk_require_stack(ctx, 100000);

	/* XXX: do something to force a callstack grow/shrink, perhaps
	 * just a manual forced resize?
	 */
	return 0;
}

DUK_LOCAL void duk__refcount_run_torture_finalizer(duk_hthread *thr, duk_hobject *obj) {
	duk_context *ctx;
	duk_int_t rc;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(obj != NULL);
	ctx = (duk_context *) thr;

	/* Avoid fake finalization for the duk__refcount_fake_finalizer function
	 * itself, otherwise we're in infinite recursion.
	 */
	if (DUK_HOBJECT_HAS_NATIVEFUNCTION(obj)) {
		if (((duk_hnativefunction *) obj)->func == duk__refcount_fake_finalizer) {
			DUK_DD(DUK_DDPRINT("avoid fake torture finalizer for duk__refcount_fake_finalizer itself"));
			return;
		}
	}
	/* Avoid fake finalization when callstack limit has been reached.
	 * Otherwise a callstack limit error will be created, then refzero'ed,
	 * and we're in an infinite loop.
	 */
	if (thr->heap->call_recursion_depth >= thr->heap->call_recursion_limit ||
	    thr->callstack_size + 2 * DUK_CALLSTACK_GROW_STEP >= thr->callstack_max /*approximate*/) {
		DUK_D(DUK_DPRINT("call recursion depth reached, avoid fake torture finalizer"));
		return;
	}

	/* Run fake finalizer.  Avoid creating new refzero queue entries
	 * so that we are not forced into a forever loop.
	 */
	duk_push_c_function(ctx, duk__refcount_fake_finalizer, 1 /*nargs*/);
	duk_push_hobject(ctx, obj);
	rc = duk_pcall(ctx, 1);
	DUK_UNREF(rc);  /* ignored */
	duk_pop(ctx);
}
#endif  /* DUK_USE_REFZERO_FINALIZER_TORTURE */

/*
 *  Refcount memory freeing loop.
 *
 *  Frees objects in the refzero_pending list until the list becomes
 *  empty.  When an object is freed, its references get decref'd and
 *  may cause further objects to be queued for freeing.
 *
 *  This could be expanded to allow incremental freeing: just bail out
 *  early and resume at a future alloc/decref/refzero.
 */

DUK_LOCAL void duk__refzero_free_pending(duk_hthread *thr) {
	duk_heaphdr *h1, *h2;
	duk_heap *heap;
	duk_int_t count = 0;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(thr->heap != NULL);
	heap = thr->heap;
	DUK_ASSERT(heap != NULL);

	/*
	 *  Detect recursive invocation
	 */

	if (DUK_HEAP_HAS_REFZERO_FREE_RUNNING(heap)) {
		DUK_DDD(DUK_DDDPRINT("refzero free running, skip run"));
		return;
	}

	/*
	 *  Churn refzero_list until empty
	 */

	DUK_HEAP_SET_REFZERO_FREE_RUNNING(heap);
	while (heap->refzero_list) {
		duk_hobject *obj;
		duk_bool_t rescued = 0;

		/*
		 *  Pick an object from the head (don't remove yet).
		 */

		h1 = heap->refzero_list;
		obj = (duk_hobject *) h1;
		DUK_DD(DUK_DDPRINT("refzero processing %p: %!O", (void *) h1, (duk_heaphdr *) h1));
		DUK_ASSERT(DUK_HEAPHDR_GET_PREV(heap, h1) == NULL);
		DUK_ASSERT(DUK_HEAPHDR_GET_TYPE(h1) == DUK_HTYPE_OBJECT);  /* currently, always the case */

#if defined(DUK_USE_REFZERO_FINALIZER_TORTURE)
		/* Torture option to shake out finalizer side effect issues:
		 * make a bogus function call for every finalizable object,
		 * essentially simulating the case where everything has a
		 * finalizer.
		 */
		DUK_DD(DUK_DDPRINT("refzero torture enabled, fake finalizer"));
		DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(h1) == 0);
		DUK_HEAPHDR_PREINC_REFCOUNT(h1);  /* bump refcount to prevent refzero during finalizer processing */
		duk__refcount_run_torture_finalizer(thr, obj);  /* must never longjmp */
		DUK_HEAPHDR_PREDEC_REFCOUNT(h1);  /* remove artificial bump */
		DUK_ASSERT_DISABLE(h1->h_refcount >= 0);  /* refcount is unsigned, so always true */
#endif

		/*
		 *  Finalizer check.
		 *
		 *  Note: running a finalizer may have arbitrary side effects, e.g.
		 *  queue more objects on refzero_list (tail), or even trigger a
		 *  mark-and-sweep.
		 *
		 *  Note: quick reject check should match vast majority of
		 *  objects and must be safe (not throw any errors, ever).
		 */

		/* An object may have FINALIZED here if it was finalized by mark-and-sweep
		 * on a previous run and refcount then decreased to zero.  We won't run the
		 * finalizer again here.
		 */

		/* A finalizer is looked up from the object and up its prototype chain
		 * (which allows inherited finalizers).
		 */
		if (duk_hobject_hasprop_raw(thr, obj, DUK_HTHREAD_STRING_INT_FINALIZER(thr))) {
			DUK_DDD(DUK_DDDPRINT("object has a finalizer, run it"));

			DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(h1) == 0);
			DUK_HEAPHDR_PREINC_REFCOUNT(h1);  /* bump refcount to prevent refzero during finalizer processing */

			duk_hobject_run_finalizer(thr, obj);  /* must never longjmp */
			DUK_ASSERT(DUK_HEAPHDR_HAS_FINALIZED(h1));  /* duk_hobject_run_finalizer() sets */

			DUK_HEAPHDR_PREDEC_REFCOUNT(h1);  /* remove artificial bump */
			DUK_ASSERT_DISABLE(h1->h_refcount >= 0);  /* refcount is unsigned, so always true */

			if (DUK_HEAPHDR_GET_REFCOUNT(h1) != 0) {
				DUK_DDD(DUK_DDDPRINT("-> object refcount after finalization non-zero, object will be rescued"));
				rescued = 1;
			} else {
				DUK_DDD(DUK_DDDPRINT("-> object refcount still zero after finalization, object will be freed"));
			}
		}

		/* Refzero head is still the same.  This is the case even if finalizer
		 * inserted more refzero objects; they are inserted to the tail.
		 */
		DUK_ASSERT(h1 == heap->refzero_list);

		/*
		 *  Remove the object from the refzero list.  This cannot be done
		 *  before a possible finalizer has been executed; the finalizer
		 *  may trigger a mark-and-sweep, and mark-and-sweep must be able
		 *  to traverse a complete refzero_list.
		 */

		h2 = DUK_HEAPHDR_GET_NEXT(heap, h1);
		if (h2) {
			DUK_HEAPHDR_SET_PREV(heap, h2, NULL);  /* not strictly necessary */
			heap->refzero_list = h2;
		} else {
			heap->refzero_list = NULL;
			heap->refzero_list_tail = NULL;
		}

		/*
		 *  Rescue or free.
		 */

		if (rescued) {
			/* yes -> move back to heap allocated */
			DUK_DD(DUK_DDPRINT("object rescued during refcount finalization: %p", (void *) h1));
			DUK_ASSERT(!DUK_HEAPHDR_HAS_FINALIZABLE(h1));
			DUK_ASSERT(DUK_HEAPHDR_HAS_FINALIZED(h1));
			DUK_HEAPHDR_CLEAR_FINALIZED(h1);
			h2 = heap->heap_allocated;
			DUK_HEAPHDR_SET_PREV(heap, h1, NULL);
			if (h2) {
				DUK_HEAPHDR_SET_PREV(heap, h2, h1);
			}
			DUK_HEAPHDR_SET_NEXT(heap, h1, h2);
			DUK_ASSERT_HEAPHDR_LINKS(heap, h1);
			DUK_ASSERT_HEAPHDR_LINKS(heap, h2);
			heap->heap_allocated = h1;
		} else {
			/* no -> decref members, then free */
			duk__refcount_finalize_hobject(thr, obj);
			duk_heap_free_heaphdr_raw(heap, h1);
		}

		count++;
	}
	DUK_HEAP_CLEAR_REFZERO_FREE_RUNNING(heap);

	DUK_DDD(DUK_DDDPRINT("refzero processed %ld objects", (long) count));

	/*
	 *  Once the whole refzero cascade has been freed, check for
	 *  a voluntary mark-and-sweep.
	 */

#if defined(DUK_USE_MARK_AND_SWEEP) && defined(DUK_USE_VOLUNTARY_GC)
	/* 'count' is more or less comparable to normal trigger counter update
	 * which happens in memory block (re)allocation.
	 */
	heap->mark_and_sweep_trigger_counter -= count;
	if (heap->mark_and_sweep_trigger_counter <= 0) {
		duk_bool_t rc;
		duk_small_uint_t flags = 0;  /* not emergency */
		DUK_D(DUK_DPRINT("refcount triggering mark-and-sweep"));
		rc = duk_heap_mark_and_sweep(heap, flags);
		DUK_UNREF(rc);
		DUK_D(DUK_DPRINT("refcount triggered mark-and-sweep => rc %ld", (long) rc));
	}
#endif  /* DUK_USE_MARK_AND_SWEEP && DUK_USE_VOLUNTARY_GC */
}

/*
 *  Incref and decref functions.
 *
 *  Decref may trigger immediate refzero handling, which may free and finalize
 *  an arbitrary number of objects.
 *
 */

DUK_INTERNAL void duk_heaphdr_refzero(duk_hthread *thr, duk_heaphdr *h) {
	duk_heap *heap;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(h != NULL);

	heap = thr->heap;
	DUK_DDD(DUK_DDDPRINT("refzero %p: %!O", (void *) h, (duk_heaphdr *) h));

	/*
	 *  Refzero handling is skipped entirely if (1) mark-and-sweep is
	 *  running or (2) execution is paused in the debugger.  The objects
	 *  are left in the heap, and will be freed by mark-and-sweep or
	 *  eventual heap destruction.
	 *
	 *  This is necessary during mark-and-sweep because refcounts are also
	 *  updated during the sweep phase (otherwise objects referenced by a
	 *  swept object would have incorrect refcounts) which then calls here.
	 *  This could be avoided by using separate decref macros in
	 *  mark-and-sweep; however, mark-and-sweep also calls finalizers which
	 *  would use the ordinary decref macros anyway and still call this
	 *  function.
	 *
	 *  This check must be enabled also when mark-and-sweep support has been
	 *  disabled: the flag is also used in heap destruction when running
	 *  finalizers for remaining objects, and the flag prevents objects from
	 *  being moved around in heap linked lists.
	 */

	/* XXX: ideally this would be just one flag (maybe a derived one) so
	 * that a single bit test is sufficient to check the condition.
	 */
#if defined(DUK_USE_DEBUGGER_SUPPORT)
	if (DUK_UNLIKELY(DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap) || DUK_HEAP_IS_PAUSED(heap))) {
#else
	if (DUK_UNLIKELY(DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap))) {
#endif
		DUK_DDD(DUK_DDDPRINT("refzero handling suppressed when mark-and-sweep running, object: %p", (void *) h));
		return;
	}

	switch ((duk_small_int_t) DUK_HEAPHDR_GET_TYPE(h)) {
	case DUK_HTYPE_STRING:
		/*
		 *  Strings have no internal references but do have "weak"
		 *  references in the string cache.  Also note that strings
		 *  are not on the heap_allocated list like other heap
		 *  elements.
		 */

		duk_heap_strcache_string_remove(heap, (duk_hstring *) h);
		duk_heap_string_remove(heap, (duk_hstring *) h);
		duk_heap_free_heaphdr_raw(heap, h);
		break;

	case DUK_HTYPE_OBJECT:
		/*
		 *  Objects have internal references.  Must finalize through
		 *  the "refzero" work list.
		 */

		duk_heap_remove_any_from_heap_allocated(heap, h);
		duk__queue_refzero(heap, h);
		duk__refzero_free_pending(thr);
		break;

	case DUK_HTYPE_BUFFER:
		/*
		 *  Buffers have no internal references.  However, a dynamic
		 *  buffer has a separate allocation for the buffer.  This is
		 *  freed by duk_heap_free_heaphdr_raw().
		 */

		duk_heap_remove_any_from_heap_allocated(heap, h);
		duk_heap_free_heaphdr_raw(heap, h);
		break;

	default:
		DUK_D(DUK_DPRINT("invalid heap type in decref: %ld", (long) DUK_HEAPHDR_GET_TYPE(h)));
		DUK_UNREACHABLE();
	}
}

#if !defined(DUK_USE_FAST_REFCOUNT_DEFAULT)
DUK_INTERNAL void duk_tval_incref(duk_tval *tv) {
	DUK_ASSERT(tv != NULL);

	if (DUK_TVAL_NEEDS_REFCOUNT_UPDATE(tv)) {
		duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
		DUK_ASSERT(h != NULL);
		DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
		DUK_ASSERT_DISABLE(h->h_refcount >= 0);
		DUK_HEAPHDR_PREINC_REFCOUNT(h);
	}
}
#endif

#if 0  /* unused */
DUK_INTERNAL void duk_tval_incref_allownull(duk_tval *tv) {
	if (tv == NULL) {
		return;
	}
	if (DUK_TVAL_NEEDS_REFCOUNT_UPDATE(tv)) {
		duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
		DUK_ASSERT(h != NULL);
		DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
		DUK_ASSERT_DISABLE(h->h_refcount >= 0);
		DUK_HEAPHDR_PREINC_REFCOUNT(h);
	}
}
#endif

DUK_INTERNAL void duk_tval_decref(duk_hthread *thr, duk_tval *tv) {
	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(tv != NULL);

	if (DUK_TVAL_NEEDS_REFCOUNT_UPDATE(tv)) {
		duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
		DUK_ASSERT(h != NULL);
		DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
		duk_heaphdr_decref(thr, h);
	}
}

#if 0  /* unused */
DUK_INTERNAL void duk_tval_decref_allownull(duk_hthread *thr, duk_tval *tv) {
	DUK_ASSERT(thr != NULL);

	if (tv == NULL) {
		return;
	}
	if (DUK_TVAL_NEEDS_REFCOUNT_UPDATE(tv)) {
		duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
		DUK_ASSERT(h != NULL);
		DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
		duk_heaphdr_decref(thr, h);
	}
}
#endif

#if !defined(DUK_USE_FAST_REFCOUNT_DEFAULT)
DUK_INTERNAL void duk_heaphdr_incref(duk_heaphdr *h) {
	DUK_ASSERT(h != NULL);
	DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
	DUK_ASSERT_DISABLE(DUK_HEAPHDR_GET_REFCOUNT(h) >= 0);

	DUK_HEAPHDR_PREINC_REFCOUNT(h);
}
#endif

#if 0  /* unused */
DUK_INTERNAL void duk_heaphdr_incref_allownull(duk_heaphdr *h) {
	if (h == NULL) {
		return;
	}
	DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
	DUK_ASSERT_DISABLE(DUK_HEAPHDR_GET_REFCOUNT(h) >= 0);

	DUK_HEAPHDR_PREINC_REFCOUNT(h);
}
#endif

DUK_INTERNAL void duk_heaphdr_decref(duk_hthread *thr, duk_heaphdr *h) {
	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(thr->heap != NULL);
	DUK_ASSERT(h != NULL);
	DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
	DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(h) >= 1);

#if defined(DUK_USE_ROM_OBJECTS)
	if (DUK_HEAPHDR_HAS_READONLY(h)) {
		return;
	}
#endif
	if (DUK_HEAPHDR_PREDEC_REFCOUNT(h) != 0) {
		return;
	}
	duk_heaphdr_refzero(thr, h);
}

DUK_INTERNAL void duk_heaphdr_decref_allownull(duk_hthread *thr, duk_heaphdr *h) {
	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(thr->heap != NULL);

	if (h == NULL) {
		return;
	}
	DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));

#if defined(DUK_USE_ROM_OBJECTS)
	if (DUK_HEAPHDR_HAS_READONLY(h)) {
		return;
	}
#endif
	DUK_ASSERT(DUK_HEAPHDR_GET_REFCOUNT(h) >= 1);
	if (DUK_HEAPHDR_PREDEC_REFCOUNT(h) != 0) {
		return;
	}
	duk_heaphdr_refzero(thr, h);
}

#else

/* no refcounting */

#endif  /* DUK_USE_REFERENCE_COUNTING */


text:
python3 /usr/local/lib/python3.4/dist-packages/wheresyourtrash/manage_wheresyourtrash.py migrate
#python /usr/local/lib/python2.7/dist-packages/wheresyourtrash/manage_wheresyourtrash.py collectstatic --noinput

exec gunicorn -w 2 wheresyourtrash.wsgi --bind 0.0.0.0:8000

redpajama_set_name: RedPajamaGithub


text:
#ifndef QWINTASKBARPROGRESS_H
#define QWINTASKBARPROGRESS_H

#include <QtCore/qobject.h>
#include <QtCore/qscopedpointer.h>
#include <QtWinExtras/qwinextrasglobal.h>

QT_BEGIN_NAMESPACE

class QWinTaskbarProgressPrivate;

class Q_WINEXTRAS_EXPORT QWinTaskbarProgress : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int value READ value WRITE setValue NOTIFY valueChanged)
    Q_PROPERTY(int minimum READ minimum WRITE setMinimum NOTIFY minimumChanged)
    Q_PROPERTY(int maximum READ maximum WRITE setMaximum NOTIFY maximumChanged)
    Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibilityChanged)
    Q_PROPERTY(bool paused READ isPaused WRITE setPaused NOTIFY pausedChanged)
    Q_PROPERTY(bool stopped READ isStopped NOTIFY stoppedChanged)

public:
    explicit QWinTaskbarProgress(QObject *parent = Q_NULLPTR);
    ~QWinTaskbarProgress();

    int value() const;
    int minimum() const;
    int maximum() const;
    bool isVisible() const;
    bool isPaused() const;
    bool isStopped() const;

public Q_SLOTS:
    void setValue(int value);
    void setMinimum(int minimum);
    void setMaximum(int maximum);
    void setRange(int minimum, int maximum);
    void reset();
    void show();
    void hide();
    void setVisible(bool visible);
    void pause();
    void resume();
    void setPaused(bool paused);
    void stop();

Q_SIGNALS:
    void valueChanged(int value);
    void minimumChanged(int minimum);
    void maximumChanged(int maximum);
    void visibilityChanged(bool visible);
    void pausedChanged(bool paused);
    void stoppedChanged(bool stopped);

private:
    Q_DISABLE_COPY(QWinTaskbarProgress)
    Q_DECLARE_PRIVATE(QWinTaskbarProgress)
    QScopedPointer<QWinTaskbarProgressPrivate> d_ptr;
};

QT_END_NAMESPACE

#endif // QWINTASKBARPROGRESS_H


text:
import time

def singleton(non_singleton_cls):
    """Decorator to make sure there is only one instance of a class.
    Args:
        cls: A class.

    Returns:
        A class.

    """
    instances = {}

    def getinstance(*args, **kwargs):
        if non_singleton_cls not in instances:
            instances[non_singleton_cls] = non_singleton_cls(*args, **kwargs)
        return instances[non_singleton_cls]

    # Save the class for mocking purposes.
    getinstance._cls = non_singleton_cls
    return getinstance

def retry(ExceptionToCheck, tries=4, delay=3, backoff=2):
    """Retry calling the decorated function using an exponential backoff.

    Similar to utils.decorators.retry() but customized slightly for operations tools.

    :param ExceptionToCheck: the exception to check. may be a tuple of
        excpetions to check
    :type ExceptionToCheck: Exception or tuple
    :param tries: number of times to try (not retry) before giving up
    :type tries: int
    :param delay: initial delay between retries in seconds
    :type delay: int
    :param backoff: backoff multiplier e.g. value of 2 will double the delay
        each retry
    :type backoff: int"""

    def deco_retry(f):
        def f_retry(*args, **kwargs):
            mtries, mdelay = tries, delay
            while mtries > 1:
                try:
                    return f(*args, **kwargs)
                except ExceptionToCheck:
                    time.sleep(mdelay)
                    mtries -= 1
                    mdelay *= backoff
            return f(*args, **kwargs)

        return f_retry  # true decorator

    return deco_retry


text:
package org.finra.herd.rest;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.util.Collections;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import org.finra.herd.model.api.xml.BusinessObjectDataStorageUnitCreateRequest;
import org.finra.herd.model.api.xml.BusinessObjectDataStorageUnitCreateResponse;
import org.finra.herd.model.api.xml.BusinessObjectDataStorageUnitKey;
import org.finra.herd.model.api.xml.StorageDirectory;
import org.finra.herd.model.api.xml.StorageFile;
import org.finra.herd.service.BusinessObjectDataStorageUnitService;

/**
 * This class tests various functionality within the business object data storage unit REST controller.
 */
public class BusinessObjectDataStorageUnitRestControllerTest extends AbstractRestTest
{
    @InjectMocks
    private BusinessObjectDataStorageUnitRestController businessObjectDataStorageUnitRestController;

    @Mock
    private BusinessObjectDataStorageUnitService businessObjectDataStorageUnitService;

    @Before()
    public void before()
    {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testCreateBusinessObjectDataStorageUnit()
    {
        // Create a business object data storage unit key.
        BusinessObjectDataStorageUnitKey businessObjectDataStorageUnitKey =
            new BusinessObjectDataStorageUnitKey(BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE,
                SUBPARTITION_VALUES, DATA_VERSION, STORAGE_NAME);

        // Create a storage unit directory.
        StorageDirectory storageDirectory = new StorageDirectory(STORAGE_DIRECTORY_PATH);

        // Create a list of storage files.
        List<StorageFile> storageFiles = Collections.singletonList(new StorageFile(FILE_NAME, FILE_SIZE, ROW_COUNT));

        // Create a business object data storage unit request.
        BusinessObjectDataStorageUnitCreateRequest request =
            new BusinessObjectDataStorageUnitCreateRequest(businessObjectDataStorageUnitKey, storageDirectory, storageFiles, DISCOVER_STORAGE_FILES);

        // Create a business object data storage unit response.
        BusinessObjectDataStorageUnitCreateResponse response =
            new BusinessObjectDataStorageUnitCreateResponse(businessObjectDataStorageUnitKey, storageDirectory, storageFiles);

        // Mock the external calls.
        when(businessObjectDataStorageUnitService.createBusinessObjectDataStorageUnit(request)).thenReturn(response);

        // Call the method under test.
        BusinessObjectDataStorageUnitCreateResponse result = businessObjectDataStorageUnitRestController.createBusinessObjectDataStorageUnit(request);

        // Verify the external calls.
        verify(businessObjectDataStorageUnitService).createBusinessObjectDataStorageUnit(request);
        verifyNoMoreInteractions(businessObjectDataStorageUnitService);

        // Validate the results.
        assertEquals(response, result);
    }
}


text:
#ifndef PLAYER_H
#define PLAYER_H

#include <vector>

#include <QPoint>
#include <QColor>

class Player
{
public:
    enum class Direction {
        None,
        Up,
        Down,
        Left,
        Right
    };

public:
    Player(QString name, QColor color, QPoint position, Direction direction = Direction::None);

    //! Change `position` based on `direction`.
    void step();

    //! Check if this player is colliding with `other`.
    auto collidesWith(const Player &other) const -> bool;
    //! Check if this player's trail occupies `position`.
    auto trailContains(QPoint position) const -> bool;

    //! Change `direction` of player.
    void turn(Direction direction);

    auto getName() const -> QString; //!< Get user-friendly name.
    auto getColor() const -> QColor; //!< Get displayable color.
    auto getPosition() const -> QPoint; //!< Get position.
    auto getDirection() const -> Direction; //!< Get direction.
    //! Check if player is in play.
    auto getIsPlaying() const -> bool;
    //! Set whether player is in play.
    void setIsPlaying(bool isPlaying);
    //! Get a reference to trial container.
    /*!
     * Usefull for drawing routines.
     */
    auto getTrail() const -> const std::vector<QPoint>&;

private:
    //! User-friendly (displayable) name.
    QString name;
    //! Color to be displayed for this player.
    QColor color;
    //! Where player is.
    QPoint position;
    //! Which direction the player is traveling.
    Direction direction;
    //! All locations the player has been.
    /*!
     * Does not include `position` currently at.
     */
    std::vector<QPoint> trail;
    //! Whether we are playing (can move) or not.
    bool isPlaying = true;

};

#endif // PLAYER_H


text:
/**
 * Media Module: Implementation for Speech Recognition via AT&T ASR over HTTPS/POST
 *
 * @requires AMR encoder (workers/amrEncoder.js)
 * @requires Cross-Domain access
 * @requires CSP for accessing the AT&T ASR server, e.g. "connect-src https://api.att.com" or "default-src https://api.att.com"
 *
 */
newWebAudioAsrImpl = (function ATnTWebAudioInputImpl(){

	/**  @memberOf ATnTWebAudioInputImpl# */
	var MODE = 'atnt';

	/**  @memberOf ATnTWebAudioInputImpl# */
	var _pluginName = 'atntWebAudioInput';

	/**
	 * legacy mode: use pre-v4 API of mmir-lib
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var _isLegacyMode = true;
	/**
	 * Reference to the mmir-lib core (only available in non-legacy mode)
	 * @type mmir
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var _mmir = null;

	//get mmir-lib core from global namespace:
	_mmir = window[typeof MMIR_CORE_NAME === 'string'? MMIR_CORE_NAME : 'mmir'];
	if(_mmir){
		// set legacy-mode if version is < v4
		_isLegacyMode = _mmir? _mmir.isVersion(4, '<') : true;
	}

	/**
	 * HELPER for require():
	 * 		use module IDs (and require instance) depending on legacy mode
	 *
	 * @param {String} id
	 * 			the require() module ID
	 *
	 * @returns {any} the require()'ed module
	 *
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var _req = function(id){
		var name = (_isLegacyMode? '' : 'mmirf/') + id;
		return _mmir? _mmir.require(name) : require(name);
	};

	/**
	 * @type mmir.LanguageManager
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var languageManager = _req('languageManager');
	/**
	 * @type mmir.ConfigurationManager
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var configurationManager = _req('configurationManager');

	/**
	 * @type mmir.ConfigurationManager
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var mediaManager = _req('mediaManager');

	/** @memberOf ATnTWebAudioInputImpl# */
	var result_types = {
			"FINAL": 				"FINAL",
			"INTERIM": 				"INTERIM",
			"INTERMEDIATE":			"INTERMEDIATE",
			"RECOGNITION_ERROR": 	"RECOGNITION_ERROR",
			"RECORDING_BEGIN": 		"RECORDING_BEGIN",
			"RECORDING_DONE": 		"RECORDING_DONE"
	};

	/** @memberOf ATnTWebAudioInputImpl# */
	var lastBlob = false;

	/**
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var oAuthToken = '';

	/**
	 * Supported language/country codes:
	 * since the services currently has very limited country support,
	 * this is used for mapping unsupported country codes to supported ones
	 *
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var supportedLang = {
		'en': 'en-US',
		'es': 'es-US'
	};

	/**
	 * The default language of the AT&T recognition service (i.e. used by service, if language param is omitted)
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var defaultLang = supportedLang.en;

	/**
	 * Recognition options for current recognition process.
	 *
	 * @memberOf ATnTWebAudioInputImpl#
	 * @see mmir.MediaManager#recognize
	 */
	var currentOptions;

	/**
	 * HELPER retrieve language setting and apply impl. specific corrections/adjustments
	 * (i.e. deal with AT&T specific quirks for language/country codes)
	 *
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var getFixedLang = function(options){

		var lang = options && options.language? options.language : languageManager.getLanguageConfig(_pluginName);

		//since the service supportes few languages/country codes, try to automatically "convert"
		// mismatched country-codes to supported ones
		if(/^e[ns]/i.test(lang)){

			var isSupported = false;
			for(var l in supportedLang){
				if(supportedLang.hasOwnProperty(l) && supportedLang[l] === lang){
					isSupported = true;
					break;
				}
			}

			if(! isSupported){
				var langCode = lang.substring(0, 2);
				console.warn('unsupported language/country code "'+lang+'": reverting to supported code '+supportedLang[langCode]);
				lang = supportedLang[langCode];
			}

		}

		return lang;
	};

//	var textProcessor, currentFailureCallback;

	/**
	 * @returns {Boolean} TRUE if cause was invalid authentification (-> might try to get a new oauth token).
	 * 					Otherwise FALSE
	 *
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var asrErrorWrapper = function(ajax,response,blobsize){

		var status = (ajax.status).toString(), msg;

		var text = ajax.responseText;

		var isInvalidAuth = false;
		//for stauts 400, 401, 403 AND "MessageId": "POL0001"
		// -> invalid auth token
		if(/POL0001/.test(text)){
			isInvalidAuth = true;
		}

		var isInvalid = false;
		//for stauts 400 AND "MessageId": "SVC0001"
		// -> custom error
		if(/SVC0001/.test(text)){
			isInvalid = true;
		}

		var isInvalidInput = false;
		//for stauts 400 AND "MessageId": "SVC0002"
		// -> invalid input
		if(/SVC0002/.test(text)){
			isInvalidInput = true;
		}

		var msg;
		switch (status) {
		//4xx Client Error
		case '400':
			if(isInvalidInput || isInvalid){
				msg = isInvalidInput? 'Invalid input value for message part: ' : '';
				break;
			}
		case '401':
		case '403':
			if(isInvalidAuth){
				msg = 'A policy error occurred.';
			} else {
				msg = '';
			}
			break;
			// 5xx Server Error
		case '502':
			msg = 'The API Gateway could not respond to the request.';
			break;
		default:
			msg = 'UNKNOWN ERROR';
		break;
		}

		console.error('Error response from server (status '+status+'): '+msg+' -> response: '+text);

		return isInvalidAuth;
	};

	/**
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var doSend = function(msg, successCallback, errorCallback){

//		successCallback = successCallback || textProcessor;
//		errorCallback = errorCallback || currentFailureCallback;

		if(!oAuthToken){
			//missing oauth-token 	-> try to retrieve one now, and continue with asr when token is available
			doInitSend(function(){
				//after init/retrieving the oauth token has finished: re-submit the failed request:
				doSend(msg, successCallback, errorCallback);
			});
			return; //////////////////////////////// EARLY EXIT ///////////////////////////////
		}

		var ajaxSuccess = function() {

			if(oAjaxReq.status == 200){

//				console.log("AJAXSubmit - Success!");
//				console.log("ResonseText in input");

				var respText = '', altRes;

				var jsonResp = JSON.parse(this.responseText);
				if(jsonResp && jsonResp.Recognition && !! jsonResp.Recognition.NBest){

					var results = jsonResp.Recognition.NBest;
					respText = results[0].ResultText;

					if(results.length > 1){
						altRes = [];
						for(var i=1,size=results.length; i < size; ++i){
							altRes.push({text: results[i]});
						}
					}

				} else {
					console.error('no asr results!');
				}

				if(successCallback){

					type = lastBlob? result_types.FINAL : result_types.INTERMEDIATE;

					successCallback(respText,1,type,altRes);
				}

			} else {

				if( asrErrorWrapper(oAjaxReq, this, dataSize) ){
					//error was due to invalid authentification (oauth token may have expired)
					// -> try to renew the oauth token

					doInitSend(function(){
						//after init has finished: re-submit the failed request:
						doSend(msg, successCallback, errorCallback);
					});

				}
				//else: TODO invoke error-callback for some of the error-codes (?)
			}

		};

		var data = msg.buf;
		var dataSize = data.size;
//		var sample_rate = 44100; //PB Fix nicht-hardcoden
//		console.log("Ajax-Data: ");
//		console.log(data);

		var oAjaxReq = new XMLHttpRequest();

		var apiLang = getFixedLang(currentOptions);

		//oAjaxReq.submittedData = oData;
//		oAuthToken =  "BF-ACSI~4~20150218153931~c9fdO6D2sLzftjyleO1KeWdE4aDf1kgu";
		//oAjaxReq.open("POST", "http://localhost:8080", true);
		var url = "https://api.att.com/speech/v3/speechToText";//"https://api.att.com/speech/v3/speechToTextCustom";
		oAjaxReq.open("POST", url , true);

		oAjaxReq.setRequestHeader("Authorization", "Bearer "+oAuthToken);
		oAjaxReq.setRequestHeader("Accept", "application/json");
		oAjaxReq.setRequestHeader("Content-Type", "audio/amr");
		//oAjaxReq.setRequestHeader("Transfer-Encoding", "chunked"); //chrome does not allow :/

		//valid values for speechToText API:
		// en-US (DEFAULT), es-US
		//NOTE: this is only evaluated, if X-SpeechContext is set to Generic (DEFAULT)

		//WARNING: if apiLang is other than valid values, the server responds with an error!
		if(! /en-US|es-US/.test(apiLang)){
			console.warn('Unsupported language "'+apiLang+'" requested ... ');
//			apiLang = defLang;
		}

		if(apiLang !== defaultLang){
			oAjaxReq.setRequestHeader("Content-Language", apiLang);
//			oAjaxReq.setRequestHeader("X-SpeechContext", "Generic");// <- if omitted, the default is: Generic
//			oAjaxReq.setRequestHeader("Content-Disposition", 'form-data;name="x-voice"');// <- for speechToTextCustom API
		}

		oAjaxReq.onload = ajaxSuccess;

		oAjaxReq.send(data);
	};

	/**
	 * init ASR atnt: get oAuth token
	 *
	 * @memberOf ATnTWebAudioInputImpl#
	 */
	var doInitSend = function _initSendAtnt(oninit){

		//Get from <https://matrix.bf.sl.attcompute.com/>
		var appKey = currentOptions.appKey? currentOptions.appKey : configurationManager.get([_pluginName, 'appKey']);
		var appSecret = currentOptions.appSecret? currentOptions.appSecret : configurationManager.get([_pluginName, 'appSecret']);

		var oReq = new XMLHttpRequest();
		var url = "https://api.att.com/oauth/v4/token";
		oReq.open("POST", url, true);
		oReq.setRequestHeader("Accept", "application/json");
		oReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		oReq.onload = function(oEvent) {
			if (oReq.status === 200) {
				jsonResp = JSON.parse(oReq.responseText);
				oAuthToken = jsonResp.access_token;
				console.log("Got oAuth acces-token: " + jsonResp.access_token);

				if(oninit){
					console.log("invoking on-init callback for ajax");
					oninit();
				}

			} else {
				console.error( "Error for oAuth req to "+url+ " (status" + oReq.status + "): "+oReq.responseText);

				//TODO invoke error-callback
			}
		};

		var keystring = "client_id="+appKey+"&client_secret="+appSecret+"&grant_type=client_credentials&scope=SPEECH";
		oReq.send(keystring);

		//ajax end
	};

	/** @memberOf ATnTWebAudioInputImpl# */
	var onSilenceDetected = function(evt){

		var recorder = evt.recorder;

		//encode all buffered audio now
		recorder.doEncode();
		recorder.doFinish();

		//FIXME experimental callback/listener for on-detect-sentence -> API may change!
		var onDetectSentenceListeners = mediaManager.getListeners('ondetectsentence');
		for(var i=0, size = onDetectSentenceListeners.length; i < size; ++i){
			onDetectSentenceListeners[i]();//blob, inputId);
		}

		return false;
	};

	/** @memberOf ATnTWebAudioInputImpl# */
	var onClear = function(evt){

		evt.recorder && evt.recorder.clear();
		return false;
	};

	/** @memberOf ATnTWebAudioInputImpl# */
	var doStopPropagation = function(){
		return false;
	};

	/**  @memberOf ATnTWebAudioInputImpl# */
	return {
		/** @memberOf ATnTWebAudioInputImpl.AudioProcessor# */
		_init: doInitSend,
//		initRec: function(){},
		sendData: doSend,
		oninit: doStopPropagation,
		onstarted: function(data, successCallback, errorCallback){
			successCallback && successCallback('',-1,result_types.RECORDING_BEGIN)
			return false;
		},
		onaudiostarted: doStopPropagation,
		onstopped: function(data, successCallback, errorCallback){
			successCallback && successCallback('',-1,result_types.RECORDING_DONE)
			return false;
		},
		onsendpart: doStopPropagation,
		onsilencedetected: onSilenceDetected,
		onclear: onClear,
		getPluginName: function(){
			return _pluginName;
		},
		setCallbacks: function(successCallbackFunc, failureCallbackFunc, stopUserMediaFunc, options){

			//callbacks need to be set in doSend() only
//			successCallback = successCallbackFunc;
//			errorCallback = failureCallbackFunc;
//			var func = stopUserMediaFunc;

			currentOptions = options;
		},
		setLastResult: function(){
			lastBlob = true;
		},
		resetLastResult: function(){
			lastBlob = false;
		},
		isLastResult: function(){
			return lastBlob;
		}
	};

})();


text:
<?php
namespace PhalconX\Validation\Annotations;

use PhalconX\Validation\Validation;

interface ValidatorInterface
{
    /**
     * Creates validator object
     *
     * @return Phalcon\Validation\Validator
     */
    public function getValidator(Validation $validation);
}


text:
package jat.application.EarthSatellite;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.glu.Sphere;

public class GLlib
{
    // Used when allocating native buffers for data types
    public static final int SIZE_DOUBLE = 8;
    public static final int SIZE_FLOAT = 4;
    public static final int SIZE_INT = 4;
    public static final int SIZE_BYTE = 1;

	// Display List ID for a sphere (see makeSphere() and renderSphere())
	static int sphereID = -1;

	/**
	 * Render a unit sphere at the origin, using current color, texture and material. This function calls makeSphere()
	 * to create the sphere in a display list.
	 */
	public static void renderSphere()
	{
		if (sphereID < 0)
		{
			makeSphere();
		}
		GL11.glCallList(sphereID);
	}

	public static void makeSphere()
	{
		Sphere s = new Sphere(); // an LWJGL class for drawing sphere
		sphereID = GL11.glGenLists(1); // Create a Display List
		s.setTextureFlag(true); // generate texture coords
		GL11.glNewList(sphereID, GL11.GL_COMPILE); // Start building a list
		{
			GL11.glRotatef(-90, 1, 0, 0); // rotate around X axis
			s.draw(1, 24, 24); // run GL commands to draw sphere
		}
		GL11.glEndList(); // Done building the display list
	}

	public static void drawTorus(float r, float R, int nsides, int rings)
	{
		float ringDelta = 2.0f * (float) Math.PI / rings;
		float sideDelta = 2.0f * (float) Math.PI / nsides;
		float theta = 0.0f, cosTheta = 1.0f, sinTheta = 0.0f;
		for (int i = rings - 1; i >= 0; i--)
		{
			float theta1 = theta + ringDelta;
			float cosTheta1 = (float) Math.cos(theta1);
			float sinTheta1 = (float) Math.sin(theta1);
			GL11.glBegin(GL11.GL_QUAD_STRIP);
			float phi = 0.0f;
			for (int j = nsides; j >= 0; j--)
			{
				phi += sideDelta;
				float cosPhi = (float) Math.cos(phi);
				float sinPhi = (float) Math.sin(phi);
				float dist = R + r * cosPhi;
				GL11.glNormal3f(cosTheta1 * cosPhi, -sinTheta1 * cosPhi, sinPhi);
				GL11.glVertex3f(cosTheta1 * dist, -sinTheta1 * dist, r * sinPhi);
				GL11.glNormal3f(cosTheta * cosPhi, -sinTheta * cosPhi, sinPhi);
				GL11.glVertex3f(cosTheta * dist, -sinTheta * dist, r * sinPhi);
			}
			GL11.glEnd();
			theta = theta1;
			cosTheta = cosTheta1;
			sinTheta = sinTheta1;
		}
	}

	public static void drawLine(float x0, float y0,float z0,float x1,float y1,float z1)
	{
		GL11.glBegin(GL11.GL_LINES);
		GL11.glVertex3f(x0, y0, z0);
		GL11.glVertex3f(x1, y1, z1);
		GL11.glEnd();
	}

	public static void drawTriangle()
	{
		// GL11.glBegin(GL11.GL_TRIANGLES);
		GL11.glBegin(GL11.GL_LINES);
		GL11.glVertex3f(-1.0f, -1.0f, 0.0f);
		GL11.glVertex3f(1.0f, -1.0f, 0.0f);
		GL11.glVertex3f(0.0f, 1.0f, 0.0f);
		GL11.glEnd();
		}

	public static void setSpotLight(int GLLightHandle, float[] diffuseLightColor, float[] ambientLightColor,
			float[] position, float[] direction, float cutoffAngle)
	{
		FloatBuffer ltDirection = allocFloats(direction);
		setLight(GLLightHandle, diffuseLightColor, ambientLightColor, position);
		GL11.glLightf(GLLightHandle, GL11.GL_SPOT_CUTOFF, cutoffAngle); // width of the beam
		GL11.glLight(GLLightHandle, GL11.GL_SPOT_DIRECTION, ltDirection); // which way it points
		GL11.glLightf(GLLightHandle, GL11.GL_CONSTANT_ATTENUATION, 2F); // how light beam drops off
		// GL11.glLightf(GLLightHandle, GL11.GL_LINEAR_ATTENUATION, .5F); // how light beam drops off
		// GL11.glLightf(GLLightHandle, GL11.GL_QUADRATIC_ATTENUATION, .5F); // how light beam drops off
	}

	/**
	 * Set the color of a 'positional' light (a light that has a specific position within the scene).

	 *
	 * Pass in an OpenGL light number (GL11.GL_LIGHT1), the 'Diffuse' and 'Ambient' colors (direct light and reflected
	 * light), and the position.

	 *
	 * @param GLLightHandle
	 * @param diffuseLightColor
	 * @param ambientLightColor
	 * @param position
	 */
	public static void setLight(int GLLightHandle, float[] diffuseLightColor, float[] ambientLightColor,
			float[] position)
	{
		FloatBuffer ltDiffuse = allocFloats(diffuseLightColor);
		FloatBuffer ltAmbient = allocFloats(ambientLightColor);
		FloatBuffer ltPosition = allocFloats(position);
		GL11.glLight(GLLightHandle, GL11.GL_DIFFUSE, ltDiffuse); // color of the direct illumination
		GL11.glLight(GLLightHandle, GL11.GL_SPECULAR, ltDiffuse); // color of the highlight
		GL11.glLight(GLLightHandle, GL11.GL_AMBIENT, ltAmbient); // color of the reflected light
		GL11.glLight(GLLightHandle, GL11.GL_POSITION, ltPosition);
		GL11.glEnable(GLLightHandle); // Enable the light (GL_LIGHT1 - 7)
		// GL11.glLightf(GLLightHandle, GL11.GL_QUADRATIC_ATTENUATION, .005F); // how light beam drops off
	}

    /**
	 * Load an image from the given file and return a GLImage object.
	 *
	 * @param imgFilename
	 * @return
	 */
    public static GLImage loadImage(String imgFilename) {
        GLImage img = new GLImage(imgFilename);
        if (img.isLoaded()) {
            return img;
        }
        return null;
    }

    /**
	 * Create a texture from the given image.
	 */
    public static int makeTexture(GLImage textureImg)
    {
        if ( textureImg == null ) {
            return 0;
        }
        else {
            return makeTexture(textureImg.pixelBuffer, textureImg.w, textureImg.h);
        }
    }

    /**
	 * Create a texture from the given pixels in RGBA format. Set the texture to repeat in both directions and use
	 * LINEAR for magnification.
	 *
	 * @return the texture handle
	 */
    public static int makeTexture(ByteBuffer pixels, int w, int h)
    {
        // get a new empty texture
        int textureHandle = allocateTexture();
        // 'select' the new texture by it's handle
        GL11.glBindTexture(GL11.GL_TEXTURE_2D,textureHandle);
        // set texture parameters
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); // GL11.GL_NEAREST);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); // GL11.GL_NEAREST);
        // Create the texture from pixels
        GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, w, h, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels);
        return textureHandle;
    }

    /**
	 * Allocate a texture (glGenTextures) and return the handle to it.
	 */
    public static int allocateTexture()
    {
        IntBuffer textureHandle = allocInts(1);
        GL11.glGenTextures(textureHandle);
        return textureHandle.get(0);
    }

    // ========================================================================
    // Buffer allocation functions
    //
    // These functions create and populate the native buffers used by LWJGL.
    // ========================================================================

    public static ByteBuffer allocBytes(int howmany) {
        return ByteBuffer.allocateDirect(howmany * SIZE_BYTE).order(ByteOrder.nativeOrder());
    }

    public static IntBuffer allocInts(int howmany) {
        return ByteBuffer.allocateDirect(howmany * SIZE_INT).order(ByteOrder.nativeOrder()).asIntBuffer();
    }

    public static FloatBuffer allocFloats(int howmany) {
        return ByteBuffer.allocateDirect(howmany * SIZE_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
    }

    public static DoubleBuffer allocDoubles(int howmany) {
        return ByteBuffer.allocateDirect(howmany * SIZE_DOUBLE).order(ByteOrder.nativeOrder()).asDoubleBuffer();
    }

    public static ByteBuffer allocBytes(byte[] bytearray) {
        ByteBuffer bb = ByteBuffer.allocateDirect(bytearray.length * SIZE_BYTE).order(ByteOrder.nativeOrder());
        bb.put(bytearray).flip();
        return bb;
    }

    public static IntBuffer allocInts(int[] intarray) {
        IntBuffer ib = ByteBuffer.allocateDirect(intarray.length * SIZE_FLOAT).order(ByteOrder.nativeOrder()).asIntBuffer();
        ib.put(intarray).flip();
        return ib;
    }

    public static FloatBuffer allocFloats(float[] floatarray) {
        FloatBuffer fb = ByteBuffer.allocateDirect(floatarray.length * SIZE_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
        fb.put(floatarray).flip();
        return fb;
    }

}


text:
using namespace std;

class CIntelliTxDB : public CDBWrapper {
    string sType;

public:
    ~CIntelliTxDB();

    CIntelliTxDB(size_t nCacheSize, bool fMemory, bool fWipe, std::string& t) : CDBWrapper(GetDataDir() / t, nCacheSize, fMemory, fWipe)
    {
        sType = t;
    }
    bool ReconstructIntelliTxIndex(CBlockIndex *pindexRescan);
};


text:
package com.lht.paintview.pojo;

import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.Parcelable;

/**
 * Created by lht on 16/10/17.
 */

public abstract class DrawShape implements Parcelable {
    SerializablePaint paint;

    public abstract void draw(Canvas canvas, Matrix matrix);

    public abstract DrawShape clone(float scale);
}


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

<TITLE>
Uses of Class realtimeweb.weatherservice.domain.Location (weather service: version 2.0)
</TITLE>

<META NAME="date" CONTENT="2014-04-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
realtimeweb.weatherservice.domain.Location

Packages that use Location

realtimeweb.weatherservice

realtimeweb.weatherservice.domain

Uses of Location in realtimeweb.weatherservice

Methods in realtimeweb.weatherservice that return Location

 Location
WeatherService.geocode(String address)

Uses of Location in realtimeweb.weatherservice.domain

Methods in realtimeweb.weatherservice.domain that return Location

static Location
Location.fromGeocode(Map<String,Object> raw)

 Location
Report.getLocation()

Methods in realtimeweb.weatherservice.domain with parameters of type Location

 void
Report.setLocation(Location location)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
class Namespace(object):
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __getattr__(self, key):
        return self.__dict__[key] if key in self.__dict__ else None

    def __setattr__(self, key, value):
        self.__dict__[key] = value

    def __repr__(self):
        return 'Namespace' + str(self.__dict__)

    def __str__(self):
        return repr(self)


text:
var multimeter = require('pm2-multimeter');
var os         = require('os');
var CliUx      = require('./CliUx');
var bars       = {};
var path       = require('path');
var p          = path;
require('colors');

// Cst for light programs
const RATIO_T1   = Math.floor(os.totalmem() / 500);
// Cst for medium programs
const RATIO_T2   = Math.floor(os.totalmem() / 50);
// Cst for heavy programs
const RATIO_T3   = Math.floor(os.totalmem() / 5);
// Cst for heavy programs
const RATIO_T4   = Math.floor(os.totalmem());

var Monit        = module.exports = {};

Monit.init = function(processes, debug) {
  if (processes === undefined || processes[0] == null)
    throw new Error('No processes passed to init');

  if (!processes[0].monit)
    throw new Error('No monit assigned to processes');

  if (processes[0].monit.error)
    throw new Error(JSON.stringify(processes[0].monit.error));

  Monit.multi = multimeter(process);

  Monit.multi.on('^C', process.exit);
  Monit.multi.charm.reset();

  Monit.multi.write('\x1B[32m⌬ PM2 \x1B[39mmonitoring :\n\n');

  processes.forEach(function(proc, i) {
    if (proc.status == 'stopped' || proc.status == 'stopped - too fast exit')
      return ;

    var process_name = proc.pm2_env.name || p.basename(proc.pm2_env.pm_exec_path);
    var status = proc.pm2_env.status == 'online' ? '●'.green.bold : '●'.red.bold;

    Monit.multi.write(' ' + status + ' ' + process_name.green.bold);
    Monit.multi.write('\n');
    Monit.multi.write('[' + proc.pm2_env.pm_id + '] [' + proc.pm2_env.exec_mode + ']\n');

    var bar_cpu = Monit.multi(40, (i * 2) + 3 + i, {
      width: 30,
      solid: {
        text: '|',
        foreground: 'white',
        background: 'blue'
      },
      empty: {
        text: ' '
      }
    });

    var bar_memory = Monit.multi(40, (i * 2) + 4 + i, {
      width: 30,
      solid: {
        text: '|',
        foreground: 'white',
        background: 'red'
      },
      empty: {
        text: ' '
      }
    });

    bar_cpu.percent(proc.monit.cpu);
    Monit.drawRatio(bar_memory, proc.monit.memory);

    bars[proc.pid] = {};
    bars[proc.pid].memory = bar_memory;
    bars[proc.pid].cpu = bar_cpu;
    Monit.multi.write('\n');
  });
};

Monit.stop = function() {
  Monit.multi.charm.destroy();
};

// Draw memory bars
Monit.drawRatio = function(bar_memory, memory) {
  var scale = 0;

  if (memory < RATIO_T1) scale = RATIO_T1;
  else if (memory < RATIO_T2) scale = RATIO_T2;
  else if (memory < RATIO_T3) scale = RATIO_T3;
  else scale = RATIO_T4;

  bar_memory.ratio(memory,
		   scale,
		   CliUx.bytesToSize(memory, 3));
};

Monit.refresh = function(dt) {
  dt.forEach(function(proc, i) {
    if (proc && proc.monit && bars[proc.pid]) {

      bars[proc.pid].cpu.percent(proc.monit.cpu);
      Monit.drawRatio(bars[proc.pid].memory, proc.monit.memory);

    }
  });
};


text:
"""
Created on Thu Mar 24 08:18:04 2016

@author: npop
ProcessorSingleSite
Inherits from Processor
And implements single site processing
"""
import os
import random
import numpy as np
import scipy.signal as signal
import scipy.interpolate as interp
# utils
from utilsFreq import *
from utilsIO import *
from utilsRobust import *
from utilsProcess import *

class ProcessorSingleSite(object):

	###################
	### CONSTRUCTOR
	##################
	def __init__(self, project, winSelector):
		# data reader
		self.proj = project
		self.winSelector = winSelector
		self.decParams = winSelector.getDecParams()
		self.winParams = winSelector.getWinParams()
		self.setDefaults()

	def setDefaults(self):
		# inputs
		self.inSite = ""
		self.inChannels = ["Hx", "Hy"]
		self.outSite = ""
		self.outChannels = ["Ex", "Ey"]
		self.allChannels = self.inChannels + self.outChannels
		# set cross channels - these are the actual channels to use in the solution
		self.crossChannels = self.allChannels
		# evaluation frequency data
		self.evalFreq = []
		self.evalFreqEqns = []
		# whether to include an intercept term
		self.intercept = False
		# smoothing options
		self.win = "hanning"
		self.winSmooth = -1
		# output filename
		self.prepend = ""

	###################
	### GET GENERAL INFO
	##################
	def getWinSelector(self):
		return self.winSelector

	def getDecParams(self):
		return self.decParams

	def getWinParams(self):
		return self.winParams

	def getInChannels(self):
		return self.inChannels

	def getInSite(self):
		return self.inSite

	def getInSize(self):
		return self.inSize

	def getOutChannels(self):
		return self.outChannels

	def getOutSite(self):
		return self.outSite

	def getOutSize(self):
		return self.outSize

	def getAllChannels(self):
		return self.allChannels

	def getCrossChannels(self):
		return self.crossChannels

	def getPrepend(self):
		return self.prepend

	def getIntercept(self):
		return self.intercept

	def getWindow(self):
		return self.win

	def getWindowSmooth(self, **kwargs):
		# first check if window size specified by user
		if self.winSmooth != -1 and self.winSmooth > 1:
			return self.winSmooth
		# if not, then calculate based on datasize
		if "datasize" in kwargs:
			winSmooth = kwargs["datasize"]*1.0/16.0
			if winSmooth < 3:
				return 3 # minimum smoothing
			# otherwise round to nearest odd number
			winSmooth = np.ceil(winSmooth) // 2 # this is floor division
			return int(winSmooth*2 + 1)
		# otherwise, return a default value
		return 15

	def getWinSelector(self):
		return self.winSelector

	###################
	### SET INPUTS AND OUTPUTS
	##################
	def setInput(self, inSite, inChannels):
		self.inSite = inSite
		self.inChannels = inChannels
		self.inSize = len(inChannels)
		# set all and cross channels
		self.allChannels = self.inChannels + self.outChannels
		self.crossChannels = self.allChannels

	def setOutput(self, outSite, outChannels):
		self.outSite = outSite
		self.outChannels = outChannels
		self.outSize = len(outChannels)
		# set all and cross channels
		self.allChannels = self.inChannels + self.outChannels
		self.crossChannels = self.allChannels

	def setCrossChannels(self, crossChannels):
		# this is for the case where we want to limit the cross channels used
		self.crossChannels = crossChannels

	def setPrepend(self, prepend):
		self.prepend = prepend

	def setSmooth(self, window, windowSize):
		self.win = window
		self.winSmooth = windowSize

	def setIntercept(self, intercept):
		self.intercept = intercept

	###################
	### PROCESS
	###################
	def process(self):
		# checks
		# for testing
		evalFreqEqnsTest = []
		evalFreqEqnsTest2 = []
		evalFreqEqnsTest3 = []
		evalFreqEqnsTest4 = []
		evalFreqVarsTest4 = []
		evalFreqEqnsTest5 = []
		evalFreqEqnsTest6 = []
		self.crossChannels = ["Ex", "Ey"]
		# for each decimation level
		# read in the shared windows from all sites
		# for each evaluation frequency, store the data from each window
		# and then at the end, perform robust processing
		numLevels = self.getDecParams().getNumLevels()
		inChans = self.getInChannels()
		outChans = self.getOutChannels()
		# get set of shared windows for all decimation levels
		sharedWindows = self.getWinSelector().getSharedWindows()

		for iDec in xrange(0, numLevels):
			# print out some info
			self.printText("Processing decimation level {}".format(iDec))

			fs = self.getDecParams().getSampleFreqLevel(iDec)
			# get the number of all shared windows and the number of unmasked windows
			# unmasked windows are ones that will actually be used in the calculation
			numWindows = self.getWinSelector().getNumSharedWindows(iDec)
			unmaskedWindows = self.getWinSelector().getUnmaskedWindowsLevel(iDec)
			numUnmasked = len(unmaskedWindows)
			self.printText("Total shared windows for decimation level = {}".format(numWindows))
			self.printText("Total unmasked windows for decimation level = {}".format(numUnmasked))
			if numUnmasked == 0:
				self.printText("No unmasked windows found at this decimation level, continuing to next level".format(iDec))
				continue # continue to next decimation level
			self.printText("{} windows will be processed".format(numUnmasked))

			# get the evaluation frequencies
			evalFreq = self.getDecParams().getEvalFrequenciesForLevel(iDec)
			# set some variables
			totalSize = self.getInSize() + self.getOutSize()
			numEvalFreq = len(evalFreq)
			dataSize = self.getWinSelector().getDataSize(iDec)
			freq = np.linspace(0, fs/2, dataSize)
			# get the window smoothing params
			smoothLen = self.getWindowSmooth(datasize=dataSize)

			# create the data array
			# for each evaluation frequency
			# keep the spectral power information for all windows
			evalFreqData = np.empty(shape=(numEvalFreq, numWindows, totalSize, totalSize), dtype="complex")

			# an array for the window data
			winSpectraMatrix = np.empty(shape=(totalSize, totalSize, dataSize), dtype="complex")
			winDataArray = np.empty(shape=(totalSize, dataSize), dtype="complex")

			# loop over shared windows
			localWin = 0
			global2local = {}
			# randomise the windows
			# sharedWin = random.shuffle(sharedWindows[iDec])
			for iWin in unmaskedWindows:
				# do the local to global map
				global2local[iWin] = localWin

				# get the window for the input site
				inSF, inReader = self.getWinSelector().getSpecReaderForWindow(self.getInSite(), iDec, iWin)
				inData = inReader.readBinaryWindowGlobal(iWin)
				# get the window and channels for the output site
				if self.getOutSite() != self.getInSite():
					outSF, outReader = self.getWinSelector().getSpecReaderForWindow(self.getOutSite(), iDec, iWin)
					outData = outReader.readBinaryWindowGlobal(iWin)
				else:
					outData = inData

				# get data into the right part of the arrays
				for i in xrange(0, self.getInSize()):
					winDataArray[i] = inData[inChans[i]]
				for i in xrange(0, self.getOutSize()):
					winDataArray[self.getInSize() + i] = outData[outChans[i]]

				# and now can fill the parts of the matrix
				# recall, smooth the power spectra
				for i in xrange(0, totalSize):
					for j in xrange(i, totalSize):
						# winSpectraMatrix[i,j] = winDataArray[i] * np.conjugate(winDataArray[j])
						winSpectraMatrix[i,j] = smooth1d(winDataArray[i] * np.conjugate(winDataArray[j]), smoothLen, self.getWindow())
						if i != j:
							winSpectraMatrix[j,i] = np.conjugate(winSpectraMatrix[i,j]) # due to complex symmetry

				# after running through all windows, calculate evaluation frequencies
				# calculate frequency array
				evalFreqData[:, localWin] = self.calcEvalFrequencyData(freq, evalFreq, winSpectraMatrix)

				# increment local window
				localWin = localWin + 1

			# now all the data has been collected
			# for each evaluation frequency, do the robust processing
			# and get the evaluation frequency data
			for eIdx in xrange(0, numEvalFreq):
				self.printText("Processing evaluation frequency = {:.6f} [Hz], period = {:.6f} [s]".format(evalFreq[eIdx], 1/evalFreq[eIdx]))
				# get the constrained windows for the evaluation frequency
				evalFreqWindows = self.getWinSelector().getWindowsForFreq(iDec, eIdx)
				if len(evalFreqWindows) == 0: # no windows meet constraints
					self.printText("No windows found - possibly due to masking")
					continue
				localWinIndices = []
				for iW in evalFreqWindows:
					localWinIndices.append(global2local[iW])
				self.printText("{:d} windows will be solved for".format(len(localWinIndices)))
				# restrict processing to data that meets constraints for this evaluation frequency
				# add to class vars
				self.evalFreq.append(evalFreq[eIdx])
				# try a random smoothing of the spectral density estimates across windows
				# spectralEstimates = self.smoothSpectralEstimates(evalFreqData[eIdx, localWinIndices])
				# self.evalFreqEqns.append(self.robustProcess(spectralEstimates))
				# solution using all components
				numSolveWindows, obs, reg = self.prepareLinearEqn2(evalFreqData[eIdx, localWinIndices])
				self.evalFreqEqns.append(self.robustProcess(numSolveWindows, obs, reg))
				# evalFreqEqnsTest.append(self.stackedProcess(evalFreqData[eIdx, localWinIndices]))
				# evalFreqEqnsTest2.append(self.robustProcessReduced(evalFreqData[eIdx, localWinIndices]))
				# evalFreqEqnsTest3.append(self.robustProcessOLS(numSolveWindows, obs, reg))
				tmp1, tmp2 = self.robustProcessCM(numSolveWindows, obs, reg)
				evalFreqEqnsTest4.append(tmp1)
				evalFreqVarsTest4.append(tmp2)
				# evalFreqEqnsTest4.append(self.robustProcessCM(numSolveWindows, obs, reg))
				# evalFreqEqnsTest5.append(self.robustProcessCMMod(numSolveWindows, obs, reg))
				# evalFreqEqnsTest6.append(self.robustProcessStack(numSolveWindows, obs, reg))

		# write out all the data
		self.writeTF(self.getPrepend() + "_mmest", self.evalFreq, self.evalFreqEqns)
		# self.writeTF(self.getPrepend() + "_stacked", self.evalFreq, evalFreqEqnsTest)
		# self.writeTF(self.getPrepend() + "_reduced", self.evalFreq, evalFreqEqnsTest2)
		# self.writeTF(self.getPrepend() + "_ols", self.evalFreq, evalFreqEqnsTest3)
		self.writeTF(self.getPrepend() + "_cm", self.evalFreq, evalFreqEqnsTest4, variances=evalFreqVarsTest4)
		# self.writeTF(self.getPrepend() + "_cmMod", self.evalFreq, evalFreqEqnsTest5)
		# self.writeTF(self.getPrepend() + "_mmestStacked", self.evalFreq, evalFreqEqnsTest6)

	###################
	### SOLVER ROUTINES
	###################
	def calcEvalFrequencyData(self, freq, evalFreq, winDataMatrix):
		# interpolate data to the evaluation frequencies
		inShape = winDataMatrix.shape
		data = np.empty(shape=(evalFreq.size, inShape[0], inShape[1]), dtype="complex")
		# get data from winDataMatrix
		for i in xrange(0, inShape[0]):
			for j in xrange(0, inShape[1]):
				interpFunc = interp.interp1d(freq, winDataMatrix[i,j])
				interpVals = interpFunc(evalFreq)
				for eIdx, eFreq in enumerate(evalFreq):
					data[eIdx,i,j] = interpVals[eIdx]
		return data

	def smoothSpectralEstimates(self, data):
		# takes the evaluation frequency data, which is indexed
		# windows, matrix of spectral components
		winSmooth = 9
		totalChans = self.getInSize() + self.getOutSize()
		for i in xrange(0, totalChans):
			for j in xrange(0, totalChans):
				data[:,i,j] = smooth1d(data[:,i,j], winSmooth, self.getWindow())
		return data

	def checkForBadValues(self, numWindows, data):
		finiteArray = np.ones(shape=(numWindows))
		for iW in xrange(0, numWindows):
			if not np.isfinite(data[iW]).all():
				finiteArray[iW] = 0
		numGoodWindows = sum(finiteArray)
		if numGoodWindows == numWindows:
			return numWindows, data
		self.printWarning("Bad data found...number of windows reduced from {} to {}".format(numWindows, numGoodWindows))
		goodWindowIndices = np.where(finiteArray == 1)
		return numGoodWindows, data[goodWindowIndices]

	def prepareLinearEqn(self, data):
		# prepare observations and regressors for linear processing
		numWindows = data.shape[0]
		numWindows, data = self.checkForBadValues(numWindows, data)
		totalSize = self.getOutSize() + self.getInSize()
		# for each output variable, have ninput regressor variables
		# let's construct our arrays
		obs = np.empty(shape=(self.getOutSize(), totalSize*numWindows), dtype="complex")
		reg = np.empty(shape=(self.getOutSize(), totalSize*numWindows, self.getInSize()), dtype="complex")
		for iW in xrange(0, numWindows):
			iOffset = iW*totalSize
			for i in xrange(0, self.getOutSize()):
				for j in xrange(0, totalSize):
					# this is the observation row where,i is the observed output
					obs[i, iOffset + j] = data[iW, self.getInSize() + i, j]
					for k in xrange(0, self.getInSize()):
						reg[i, iOffset + j, k] = data[iW, k, j]
		return numWindows, obs, reg

	def prepareLinearEqn2(self, data):
		# prepare observations and regressors for linear processing
		numWindows = data.shape[0]
		numWindows, data = self.checkForBadValues(numWindows, data)
		totalSize = self.getOutSize() + self.getInSize()
		crossSize = len(self.getCrossChannels())
		# for each output variable, have ninput regressor variables
		# let's construct our arrays
		obs = np.empty(shape=(self.getOutSize(), crossSize*numWindows), dtype="complex")
		reg = np.empty(shape=(self.getOutSize(), crossSize*numWindows, self.getInSize()), dtype="complex")
		for iW in xrange(0, numWindows):
			iOffset = iW*crossSize
			for i in xrange(0, self.getOutSize()):
				for j, crossChan in enumerate(self.crossChannels):
					# this is the observation row where,i is the observed output
					crossIndex = self.allChannels.index(crossChan)
					obs[i, iOffset + j] = data[iW, self.getInSize() + i, crossIndex]
					for k in xrange(0, self.getInSize()):
						reg[i, iOffset + j, k] = data[iW, k, crossIndex]
		return numWindows, obs, reg

	# def calcConfidenceIntervals(self, obs, reg, out):

	def robustProcess(self, numWindows, obs, reg):
		# do mmestimate robust processing for a single evaluation frequency
		crossSize = len(self.getCrossChannels())
		# create array for output
		output = np.empty(shape=(self.getOutSize(), self.getInSize()), dtype="complex")
		# solve
		for i in xrange(0, self.getOutSize()):
			observation = obs[i,:]
			predictors = reg[i,:,:]
			# save the output
			out, resids, scale, weights = mmestimateModel(predictors, observation, intercept=self.getIntercept())

			# now take the weights, apply to the observations and predictors, stack the appropriate rows and test
			observation2 = np.zeros(shape=(crossSize), dtype="complex")
			predictors2 = np.zeros(shape=(crossSize, self.getInSize()), dtype="complex")
			for iChan in xrange(0, crossSize):
				# now need to have my indexing array
				indexArray = np.arange(iChan, numWindows*crossSize, crossSize)
				weightsLim = weights[indexArray]
				# weightsLim = weightsLim/np.sum(weightsLim) # normalise weights to 1
				observation2[iChan] = np.sum(obs[i, indexArray]*weightsLim)/numWindows
				# now for the regressors
				for j in xrange(0, self.getInSize()):
					predictors2[iChan, j] = np.sum(reg[i, indexArray, j]*weightsLim)/numWindows
			out, resids, scale, weights = mmestimateModel(predictors2, observation2, intercept=self.getIntercept())

			if self.getIntercept():
				output[i] = out[1:]
			else:
				output[i] = out
		return output

	def robustProcessStack(self, numWindows, obs, reg):
		# loop over the outputs
		output = np.zeros(shape=(self.getOutSize(), self.getInSize()), dtype="complex")
		totalSize = self.getOutSize() + self.getInSize()
		for i in xrange(0, self.getOutSize()):
			# lets out some easier lettering
			y = obs[i]
			A = reg[i]
			# get some sizes
			n = A.shape[0]
			p = A.shape[1]
			# first calculate the leverage weights
			# this is based on the hat matrix
			q, r = linalg.qr(A)
			Pdiag = np.empty(shape=(n), dtype="float")
			for iRow in xrange(0, n):
				Pdiag[iRow] = np.absolute(np.sum(q[iRow,:]*np.conjugate(q[iRow,:]))).real
			del q, r
			Pdiag = Pdiag/np.max(Pdiag)
			leverageScale = sampleMAD0(Pdiag)
			leverageWeights = getRobustLocationWeights(Pdiag/leverageScale, "huber")

			# Begin with stacking the data and solving
			observation = np.zeros(shape=(totalSize), dtype="complex")
			predictors = np.zeros(shape=(totalSize, self.getInSize()), dtype="complex")
			for iChan in xrange(0, totalSize):
				# now need to have my indexing array
				indexArray = np.arange(iChan, numWindows*totalSize, totalSize)
				observation[iChan] = np.sum(y[indexArray])/numWindows
				# now for the regressors
				for j in xrange(0, self.getInSize()):
					predictors[iChan, j] = np.sum(A[indexArray, j])/numWindows
			initParams, residsStacked, scaleStacked, weightsStacked = mmestimateModel(predictors, observation, intercept=False)
			# calculate out scale and weights
			resids = y - np.dot(A, initParams)
			scale = sampleMAD0(resids)
			weights = getRobustLocationWeights(resids/scale, "huber")*leverageWeights

			# now get m-estimates and do the process again
			maxiter = 50
			iteration = 0
			while iteration < maxiter:

				# now stack with the weights and solve again
				observation = np.zeros(shape=(totalSize), dtype="complex")
				predictors = np.zeros(shape=(totalSize, self.getInSize()), dtype="complex")
				for iChan in xrange(0, totalSize):
					# now need to have my indexing array
					indexArray = np.arange(iChan, numWindows*totalSize, totalSize)
					weightsLim = weights[indexArray]
					# weightsLim = weightsLim/np.sum(weightsLim) # normalise weights to 1
					observation[iChan] = np.sum(y[indexArray]*weightsLim)/numWindows
					# now for the regressors
					for j in xrange(0, self.getInSize()):
						predictors[iChan, j] = np.sum(A[indexArray, j]*weightsLim)/numWindows
				paramsNew, residsStacked, scaleStacked, weightsStacked = mmestimateModel(predictors, observation)

				# now calculate residsNew etc
				residsNew = y - np.dot(A, paramsNew)

				if np.sum(np.absolute(residsNew)) < eps():
					# then return everything here
					params = paramsNew
					resids = residsNew
					break

				scale = sampleMAD0(residsNew)
				# standardise and calculate weights
				weightsNew = getRobustLocationWeights(residsNew/scale, "huber")*leverageWeights
				# increment iteration and save weightsNew
				iteration = iteration + 1
				weights = weightsNew
				params = paramsNew
				# check to see whether the change is smaller than the tolerance
				# use the R method of checking change in residuals (can check change in params)
				changeResids = linalg.norm(residsNew-resids)/linalg.norm(residsNew)
				if changeResids < eps():
					# update residuals
					resids = residsNew
					break
				# update residuals
				resids = residsNew

			# another go with tukey weights
			# return to original solution
			resids = y - np.dot(A, initParams)
			weights = getRobustLocationWeights(resids/scale, "bisquare")*leverageWeights

			while iteration < maxiter:
				# now stack with the weights and solve again
				observation = np.zeros(shape=(totalSize), dtype="complex")
				predictors = np.zeros(shape=(totalSize, self.getInSize()), dtype="complex")
				for iChan in xrange(0, totalSize):
					# now need to have my indexing array
					indexArray = np.arange(iChan, numWindows*totalSize, totalSize)
					weightsLim = weights[indexArray]
					# weightsLim = weightsLim/np.sum(weightsLim) # normalise weights to 1
					observation[iChan] = np.sum(y[indexArray]*weightsLim)/numWindows
					# now for the regressors
					for j in xrange(0, self.getInSize()):
						predictors[iChan, j] = np.sum(A[indexArray, j]*weightsLim)/numWindows
				paramsNew, residsStacked, scaleStacked, weightsStacked = mmestimateModel(predictors, observation)

				# now calculate residsNew etc
				residsNew = y - np.dot(A, paramsNew)

				if np.sum(np.absolute(residsNew)) < eps():
					# then return everything here
					params = paramsNew
					resids = residsNew
					break

				scale = sampleMAD0(residsNew)
				# standardise and calculate weights
				weightsNew = getRobustLocationWeights(residsNew/scale, "bisquare")*leverageWeights
				# increment iteration and save weightsNew
				iteration = iteration + 1
				weights = weightsNew
				params = paramsNew
				# check to see whether the change is smaller than the tolerance
				# use the R method of checking change in residuals (can check change in params)
				changeResids = linalg.norm(residsNew-resids)/linalg.norm(residsNew)
				if changeResids < eps():
					# update residuals
					resids = residsNew
					break
				# update residuals
				resids = residsNew

			output[i] = params

		return output

	def robustProcessOLS(self, numWindows, obs, reg):
		# ordinary least squares solution
		# create array for output
		output = np.empty(shape=(self.getOutSize(), self.getInSize()), dtype="complex")
		# solve
		for i in xrange(0, self.getOutSize()):
			observation = obs[i,:]
			predictors = reg[i,:,:]
			# save the output
			out, resids, squareResid, rank, s = olsModel(predictors, observation, intercept=self.getIntercept())
			if self.getIntercept():
				output[i] = out[1:]
			else:
				output[i] = out
		return output

	def robustProcessCM(self, numWindows, obs, reg):
		# do the robust processing for a single evaluation frequency
		crossSize = len(self.getCrossChannels())
		# create array for output
		output = np.empty(shape=(self.getOutSize(), self.getInSize()), dtype="complex")
		varOutput = np.empty(shape=(self.getOutSize(), self.getInSize()), dtype="float")
		# solve
		for i in xrange(0, self.getOutSize()):
			observation = obs[i,:]
			predictors = reg[i,:,:]
			# save the output
			out, resids, weights = chatterjeeMachler(predictors, observation, intercept=self.getIntercept())

			# now take the weights, apply to the observations and predictors, stack the appropriate rows and test
			observation2 = np.zeros(shape=(crossSize), dtype="complex")
			predictors2 = np.zeros(shape=(crossSize, self.getInSize()), dtype="complex")
			for iChan in xrange(0, crossSize):
				# now need to have my indexing array
				indexArray = np.arange(iChan, numWindows*crossSize, crossSize)
				weightsLim = weights[indexArray]
				# weightsLim = weightsLim/np.sum(weightsLim) # normalise weights to 1
				observation2[iChan] = np.sum(obs[i, indexArray]*weightsLim)/numWindows
				# now for the regressors
				for j in xrange(0, self.getInSize()):
					predictors2[iChan, j] = np.sum(reg[i, indexArray, j]*weightsLim)/numWindows
			out, resids, weights = chatterjeeMachler(predictors2, observation2, intercept=self.getIntercept())

			# now calculate out the varainces - have the solution out, have the weights
			# recalculate out the residuals with the final solution
			# calculate standard deviation of residuals
			# and then use chatterjee machler formula to estimate variances
			# this needs work - better to use an empirical bootstrap method, but this will do for now
			resids = np.absolute(observation - np.dot(predictors, out))
			scale = sampleMAD0(resids) # some measure of standard deviation, rather than using the standard deviation
			residsVar = scale*scale
			varPred = np.dot(hermitianTranspose(predictors), weights*predictors)
			varPred = np.linalg.inv(varPred) # this is a pxp matrix
			varOut = 1.91472*residsVar*varPred
			print varOut
			varOut = np.diag(varOut).real # this should be a real number
			print varOut

			if self.getIntercept():
				output[i] = out[1:]
				varOutput[i] = varOut[1:]
			else:
				output[i] = out
				varOutput[i] = varOut

		return output, varOutput

	def robustProcessCMMod(self, numWindows, obs, reg):
		# do the robust processing for a single evaluation frequency
		crossSize = len(self.getCrossChannels())
		# create array for output
		output = np.empty(shape=(self.getOutSize(), self.getInSize()), dtype="complex")
		# solve
		for i in xrange(0, self.getOutSize()):
			observation = obs[i,:]
			predictors = reg[i,:,:]
			# save the output
			out, resids, weights = chatterjeeMachlerMod(predictors, observation, intercept=self.getIntercept())

			# now take the weights, apply to the observations and predictors, stack the appropriate rows and test
			observation2 = np.zeros(shape=(crossSize), dtype="complex")
			predictors2 = np.zeros(shape=(crossSize, self.getInSize()), dtype="complex")
			for iChan in xrange(0, crossSize):
				# now need to have my indexing array
				indexArray = np.arange(iChan, numWindows*crossSize, crossSize)
				weightsLim = weights[indexArray]
				# weightsLim = weightsLim/np.sum(weightsLim) # normalise weights to 1
				observation2[iChan] = np.sum(obs[i, indexArray]*weightsLim)/numWindows
				# now for the regressors
				for j in xrange(0, self.getInSize()):
					predictors2[iChan, j] = np.sum(reg[i, indexArray, j]*weightsLim)/numWindows
			out, resids, weights = chatterjeeMachlerMod(predictors2, observation2, intercept=self.getIntercept())

			if self.getIntercept():
				output[i] = out[1:]
			else:
				output[i] = out
		return output

	def robustProcessCMHadi(self, numWindows, obs, reg):
		# chatterjee machler robust processing wth Hadi weights
		crossSize = len(self.getCrossChannels())
		# create array for output
		output = np.empty(shape=(self.getOutSize(), self.getInSize()), dtype="complex")
		# solve
		for i in xrange(0, self.getOutSize()):
			observation = obs[i,:]
			predictors = reg[i,:,:]
			# save the output
			out, resids, weights = chatterjeeMachlerHadi(predictors, observation, intercept=self.getIntercept())

			# now take the weights, apply to the observations and predictors, stack the appropriate rows and test
			observation2 = np.zeros(shape=(crossSize), dtype="complex")
			predictors2 = np.zeros(shape=(crossSize, self.getInSize()), dtype="complex")
			for iChan in xrange(0, crossSize):
				# now need to have my indexing array
				indexArray = np.arange(iChan, numWindows*crossSize, crossSize)
				weightsLim = weights[indexArray]
				# weightsLim = weightsLim/np.sum(weightsLim) # normalise weights to 1
				observation2[iChan] = np.sum(obs[i, indexArray]*weightsLim)/numWindows
				# now for the regressors
				for j in xrange(0, self.getInSize()):
					predictors2[iChan, j] = np.sum(reg[i, indexArray, j]*weightsLim)/numWindows
			out, resids, weights = chatterjeeMachler(predictors2, observation2, intercept=self.getIntercept())

			if self.getIntercept():
				output[i] = out[1:]
			else:
				output[i] = out
		return output

	def robustProcessReduced(self, data):
		# do the robust processing for a single evaluation frequency
		# this is an array with size numWindows, numIn
		# here only the input channels are used as the multiplying channels
		numWindows = data.shape[0]
		totalChans = self.getOutSize() + self.getInSize()
		# check for bad values
		numWindows, data = self.checkForBadValues(numWindows, data)
		# for each output variable, have ninput regressor variables
		# let's construct our arrays
		obs = np.empty(shape=(self.getOutSize(), self.getInSize()*numWindows), dtype="complex")
		reg = np.empty(shape=(self.getOutSize(), self.getInSize()*numWindows, self.getInSize()), dtype="complex")
		for iW in xrange(0, numWindows):
			iOffset = iW*self.getOutSize()
			for i in xrange(0, self.getOutSize()):
				for j in xrange(0, self.getInSize()):
					# this is the observation row where,i is the observed output
					obs[i, iOffset + j] = data[iW, self.getInSize() + i, j]
					for k in xrange(0, self.getInSize()):
						reg[i, iOffset + j, k] = data[iW, k, j]

		# create array for output
		output = np.empty(shape=(self.getOutSize(), self.getInSize()), dtype="complex")

		for i in xrange(0, self.getOutSize()):
			observation = obs[i,:]
			predictors = reg[i,:,:]
			# save the output
			out, resids, weights = chatterjeeMachlerMod(predictors, observation, intercept=self.getIntercept())
			if self.getIntercept():
				output[i] = out[1:]
			else:
				output[i] = out
		return output

	def stackedProcess(self, data):
		# then do various sums
		numWindows = data.shape[0]
		crossSize = len(self.getCrossChannels())
		# unweighted sum (i.e. normal solution)
		unWeightedSum = np.sum(data, axis=0)
		unWeightedSum = unWeightedSum/numWindows

		# for each output variable, have ninput regressor variables
		# let's construct our arrays
		obs = np.empty(shape=(self.getOutSize(), crossSize), dtype="complex")
		reg = np.empty(shape=(self.getOutSize(), crossSize, self.getInSize()), dtype="complex")
		for i in xrange(0, self.getOutSize()):
			for j, crossChan in enumerate(self.crossChannels):
				crossIndex = self.allChannels.index(crossChan)
				obs[i, j] = unWeightedSum[self.getInSize() + i, crossIndex]
				for k in xrange(0, self.getInSize()):
					reg[i, j, k] = unWeightedSum[k, crossIndex]

		# create array for output
		output = np.empty(shape=(self.getOutSize(), self.getInSize()), dtype="complex")

		for i in xrange(0, self.getOutSize()):
			observation = obs[i,:]
			predictors = reg[i,:,:]
			# save the output
			out, resids, scale, weights = mmestimateModel(predictors, observation, intercept=self.getIntercept())
			if self.getIntercept():
				output[i] = out[1:]
			else:
				output[i] = out
		return output

	###################
	### UTIL FUNCTIONS
	###################
	def writeTF(self, prepend, freq, data, **kwargs):
		inChans = self.getInChannels()
		outChans = self.getOutChannels()
		rootpath = self.proj.getTransDataPathSite(self.getOutSite())
		filename = "{}_fs{:d}_{}".format(self.getOutSite(), int(self.decParams.getSampleFreq()), prepend)
		datapath = os.path.join(rootpath, "{}".format(int(self.getWinSelector().getSampleFreq())))
		checkAndMakeDir(datapath)
		outfile = os.path.join(datapath, filename)
		outF = open(outfile, "w")
		# first write evalfreq
		outF.write("Evaluation frequencies\n")
		outF.write("{}\n".format(arrayToString(freq)))
		# now need to write out the other data
		for i in xrange(0, self.getOutSize()):
			for j in xrange(0, self.getInSize()):
				outF.write("IJ = {},{} = {}{}\n".format(i, j, outChans[i], inChans[j]))
				dataArray = np.empty(shape=(len(freq)), dtype="complex")
				for ifreq in xrange(0, len(freq)):
					dataArray[ifreq] = data[ifreq][i,j]
				outF.write("{}\n".format(arrayToString(dataArray)))

		# check for variances
		if "variances" in kwargs:
			# write out variances
			variances = kwargs["variances"]
			for i in xrange(0, self.getOutSize()):
				for j in xrange(0, self.getInSize()):
					outF.write("Var IJ = {},{} = {}{}\n".format(i, j, outChans[i], inChans[j]))
					varArray = np.empty(shape=(len(freq)), dtype="float")
					for ifreq in xrange(0, len(freq)):
						varArray[ifreq] = variances[ifreq][i,j]
					outF.write("{}\n".format(arrayToString(varArray)))
		outF.close()

	###################
	### DEBUG
	##################
	def printInfo(self):
		self.printText("####################")
		self.printText("SINGLE SITE PROCESSOR INFO BEGIN")
		self.printText("####################")
		self.printText("In Site = {}".format(self.inSite))
		self.printText("In Channels = {}".format(self.getInChannels()))
		self.printText("Out Site = {}".format(self.outSite))
		self.printText("Out Channels = {}".format(self.getOutChannels()))
		self.printText("####################")
		self.printText("SINGLE SITE PROCESSOR INFO END")
		self.printText("####################")

	def printText(self, infoStr):
		generalPrint("Single Site Processor Info", infoStr)

	def printWarning(self, warnStr):
		warningPrint("Single Site Processor Warning", warnStr)


text:
#ifndef RENDERINTERFACESFML_H
#define RENDERINTERFACESFML_H

#include <Rocket/Core/RenderInterface.h>
#include <SFML/Graphics.hpp>

class RocketSFMLRenderer : public Rocket::Core::RenderInterface
{
public:
	RocketSFMLRenderer();

	/// Sets the window
	void SetWindow(sf::RenderWindow *Window);

	/// Returns the currently assigned window
	sf::RenderWindow *GetWindow();

	/// Resizes the viewport automatically
	void Resize();

	/// Called by Rocket when it wants to render geometry that it does not wish to optimise.
	virtual void RenderGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture, const Rocket::Core::Vector2f& translation);

	/// Called by Rocket when it wants to compile geometry it believes will be static for the forseeable future.
	virtual Rocket::Core::CompiledGeometryHandle CompileGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture);

	/// Called by Rocket when it wants to render application-compiled geometry.
	virtual void RenderCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry, const Rocket::Core::Vector2f& translation);
	/// Called by Rocket when it wants to release application-compiled geometry.
	virtual void ReleaseCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry);

	/// Called by Rocket when it wants to enable or disable scissoring to clip content.
	virtual void EnableScissorRegion(bool enable);
	/// Called by Rocket when it wants to change the scissor region.
	virtual void SetScissorRegion(int x, int y, int width, int height);

	/// Called by Rocket when a texture is required by the library.
	virtual bool LoadTexture(Rocket::Core::TextureHandle& texture_handle, Rocket::Core::Vector2i& texture_dimensions, const Rocket::Core::String& source);
	/// Called by Rocket when a texture is required to be built from an internally-generated sequence of pixels.
	virtual bool GenerateTexture(Rocket::Core::TextureHandle& texture_handle, const Rocket::Core::byte* source, const Rocket::Core::Vector2i& source_dimensions);
	/// Called by Rocket when a loaded texture is no longer required.
	virtual void ReleaseTexture(Rocket::Core::TextureHandle texture_handle);

private:
	sf::RenderWindow *MyWindow;
};

#endif


text:
<!DOCTYPE html>

		<title>Finding content type conflict reasons with Episerver Developer tools</title>
		<meta http-equiv="REFRESH" content="0; url=/2018/07/16/finding-content-type-conflict-reasons-with-dev-tools/">
		<link rel="canonical" href="/2018/07/16/finding-content-type-conflict-reasons-with-dev-tools/" />

		This page has moved. You will be automatically redirected to its new location. If you aren't forwarded to the new page, click here.


text:
@interface PlaceholderTableViewController () <UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) UITableView       *tableView;
@property (strong, nonatomic) NSArray           *textsArray;
@property (strong, nonatomic) LGPlaceholderView *placeholderView;

@end

@implementation PlaceholderTableViewController

- (id)initWithTitle:(NSString *)title
{
    self = [super init];
    if (self)
    {
        self.title = title;

        // -----

        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.alwaysBounceVertical = YES;
        _tableView.allowsSelection = NO;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        [self.view addSubview:_tableView];

        _textsArray = @[@"UITableViewCell 1",
                        @"UITableViewCell 2",
                        @"UITableViewCell 3",
                        @"UITableViewCell 4",
                        @"UITableViewCell 5"];

        _placeholderView = [[LGPlaceholderView alloc] initWithView:_tableView];
        [_placeholderView showActivityIndicatorAnimated:NO completionHandler:nil];
    }
    return self;
}

#pragma mark - Dealloc

- (void)dealloc
{
    NSLog(@"%s [Line %d]", __PRETTY_FUNCTION__, __LINE__);
}

#pragma mark - Appearing

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    _tableView.frame = CGRectMake(0.f, 0.f, self.view.frame.size.width, self.view.frame.size.height);
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void)
                   {
                       [_placeholderView dismissAnimated:YES completionHandler:nil];
                   });
}

#pragma mark - UITableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _textsArray.count;
}

#pragma mark - UITableView Delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    cell.textLabel.font = [UIFont systemFontOfSize:16.f];
    cell.textLabel.text = _textsArray[indexPath.row];

    return cell;
}

@end


text:
from __future__ import absolute_import, unicode_literals, division

IMAGEMAGICK_IDENTIFY = "identify"
IMAGEMAGICK_CONVERT = "convert"

IMAGE_RESOLUTION = "800x600"
THUMB_RESOLUTION = "150x150"


text:
package newjb.core.predictable;

import newjb.core.Monitor;
import newjb.core.Step;
import newjb.core.StepFactory;

public class AssertingStep extends Step {

    private final String id;

    public AssertingStep(String id) {
        this.id = id;
    }

    public boolean perform(StepFactory stepFactory, Monitor monitor) {
        monitor.failed(id, new AssertionError("aErr"));
        return false;
    }

    @Override
    public void dontPerform(StepFactory stepFactory, Monitor monitor) {
        monitor.notPerformed(id);
    }

    public static Step assertingStep(String id) {
        return new AssertingStep(id);
    }
}


text:
package io.shrtr.server;

import java.util.Map;

import com.google.common.base.Optional;
import com.google.common.collect.Maps;

public class InMemoryPersister implements Persister {

	private Map<String, String> store = Maps.newLinkedHashMap();

	@Override
	public void storeMapping(String fullLength, String shortened) {
		// on collision we throw, for now
		if (sameHashAlreadyPresent(fullLength, shortened)) {
			if (differentUrlSameHash(fullLength, shortened)) {
				handleCollision(fullLength, shortened);
			}
			return;
		}
		store.put(shortened, fullLength);
	}

	@Override
	public Optional<String> getMapping(String shortened) {
		return Optional.fromNullable(store.get(shortened));
	}

	private boolean sameHashAlreadyPresent(String fullLength, String shortened) {
		return store.containsKey(shortened);
	}

	private boolean differentUrlSameHash(String fullLength, String shortened) {
		return !store.get(shortened).equals(fullLength);
	}

	@Override
	public void handleCollision(String fullLength, String shortened) {
		throw new RuntimeException("Error shortening URL: " + fullLength);
	}
}


text:
export interface ParseConfig {
    query?: string,
    xpath?: string,
    property?: string | Array<String> | { [name: string]: string },
    attr?: string | Array<String> | { [name: string]: string },
    name?: string,
    index?: number,
    value?: any,
    group?: Array<ParseConfig>
}


text:
package hudson.tasks.test;

import hudson.model.AbstractBuild;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;

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

/**
 * {@link AbstractTestResultAction} that aggregates all the test results
 * from the corresponding {@link AbstractBuild}s.
 *
 * <p>
 * (This has nothing to do with {@link AggregatedTestResultPublisher}, unfortunately)
 *
 * @author Kohsuke Kawaguchi
 */
@ExportedBean
public abstract class AggregatedTestResultAction extends AbstractTestResultAction {
    private int failCount,skipCount,totalCount;

    public static final class Child {
        /**
         * Name of the module. Could be relative to something.
         * The interpretation of this is done by
         * {@link AggregatedTestResultAction#getChildName(AbstractTestResultAction)} and
         * {@link AggregatedTestResultAction#resolveChild(Child)} and
         */
        public final String name;
        public final int build;

        public Child(String name, int build) {
            this.name = name;
            this.build = build;
        }
    }

    /**
     * child builds whose test results are used for aggregation.
     */
    public final List<Child> children = new ArrayList<Child>();

    @Deprecated
    public AggregatedTestResultAction(AbstractBuild owner) {
        super(owner);
    }

    /** @since 1.545 */
    public AggregatedTestResultAction() {}

    protected void update(List<? extends AbstractTestResultAction> children) {
        failCount = skipCount = totalCount = 0;
        this.children.clear();
        for (AbstractTestResultAction tr : children)
            add(tr);
    }

    protected void add(AbstractTestResultAction child) {
        failCount += child.getFailCount();
        skipCount += child.getSkipCount();
        totalCount += child.getTotalCount();
        this.children.add(new Child(getChildName(child),child.owner.number));
    }

    public int getFailCount() {
        return failCount;
    }

    @Override
    public int getSkipCount() {
        return skipCount;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public List<ChildReport> getResult() {
        // I think this is a reasonable default.
        return getChildReports();
    }

    @Override
    public List<? extends TestResult> getFailedTests() {
        List<TestResult> failedTests = new ArrayList<TestResult>(failCount);
        for (ChildReport childReport : getChildReports()) {
            if (childReport.result instanceof TestResult) {
                failedTests.addAll(((TestResult) childReport.result).getFailedTests());
            }
        }
        return failedTests;
    }

    /**
     * Data-binding bean for the remote API.
     */
    @ExportedBean(defaultVisibility=2)
    public static final class ChildReport {
        @Exported
        public final AbstractBuild<?,?> child;
        @Exported
        public final Object result;

        public ChildReport(AbstractBuild<?, ?> child, AbstractTestResultAction result) {
            this.child = child;
            this.result = result!=null ? result.getResult() : null;
        }
    }

    /**
     * Mainly for the remote API. Expose results from children.
     */
    @Exported(inline=true)
    public List<ChildReport> getChildReports() {
        return new AbstractList<ChildReport>() {
            public ChildReport get(int index) {
                return new ChildReport(
                        resolveChild(children.get(index)),
                        getChildReport(children.get(index)));
            }

            public int size() {
                return children.size();
            }
        };
    }

    protected abstract String getChildName(AbstractTestResultAction tr);
    public abstract AbstractBuild<?,?> resolveChild(Child child);

    /**
     * Uses {@link #resolveChild(Child)} and obtain the
     * {@link AbstractTestResultAction} object for the given child.
     */
    protected AbstractTestResultAction getChildReport(Child child) {
        AbstractBuild<?,?> b = resolveChild(child);
        if(b==null) return null;
        return b.getAction(AbstractTestResultAction.class);
    }

    /**
     * Since there's no TestObject that points this action as the owner
     * (aggregated {@link TestObject}s point to their respective real owners, not 'this'),
     * so this method should be never invoked.
     *
     * @deprecated
     *      so that IDE warns you if you accidentally try to call it.
     */
    @Override
    protected final String getDescription(TestObject object) {
        throw new AssertionError();
    }

    /**
     * See {@link #getDescription(TestObject)}
     *
     * @deprecated
     *      so that IDE warns you if you accidentally try to call it.
     */
    @Override
    protected final void setDescription(TestObject object, String description) {
        throw new AssertionError();
    }
}


text: from histograph.histograph import Histograph


text:
module Shouter
  class Action < ActiveRecord::Base
    TABLE_NAME = 'shouter_actions'

    class <<self
      def table_name
        TABLE_NAME
      end
    end

    belongs_to :subject, :polymorphic => true
  end
end