text:
/**
 * @file
 * implementation: common GA functions and macros
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#ifndef WIN32
#ifndef ANDROID
#include <execinfo.h>
#endif /* !ANDROID */
#include <unistd.h>
#include <sys/time.h>
#include <sys/syscall.h>
#endif /* !WIN32 */
#ifdef ANDROID
#include <android/log.h>
#endif /* ANDROID */

#if !defined(WIN32) && !defined(__APPLE__) && !defined(ANDROID)
#include <X11/Xlib.h>
#endif

#include "ga-common.h"
#include "ga-conf.h"
#ifndef ANDROID_NO_FFMPEG
#include "ga-avcodec.h"
#endif
#include "rtspconf.h"

#include <map>
#include <list>
using namespace std;

#ifndef NIPQUAD
/** For printing IPv4 addresses: convert an unsigned int to 4 unsigned char. */
#define NIPQUAD(x)	((unsigned char*)&(x))[0],	\
			((unsigned char*)&(x))[1],	\
			((unsigned char*)&(x))[2],	\
			((unsigned char*)&(x))[3]
#endif

/** The gloabl log file name */
static char *ga_logfile = NULL;

/**
 * Compute the time difference for two \a timeval data structure, i.e.,
 * \a tv1 - \a tv2.
 *
 * @param tv1 [in] Pointer to the first \a timeval data structure.
 * @param tv2 [in] Pointer to the second \a timeval data structure.
 * @return The difference in micro seconds.
 */
long long
tvdiff_us(struct timeval *tv1, struct timeval *tv2) {
	struct timeval delta;
	delta.tv_sec = tv1->tv_sec - tv2->tv_sec;
	delta.tv_usec = tv1->tv_usec - tv2->tv_usec;
	if(delta.tv_usec < 0) {
		delta.tv_sec--;
		delta.tv_usec += 1000000;
	}
	return 1000000LL*delta.tv_sec + delta.tv_usec;
}

/**
 * Sleep and wake up at \a ptv + \a interval (micro seconds).
 *
 * @param interval [in] The expected sleeping time (in micro seconds).
 * @param ptv [in] Pointer to the baseline time.
 * @return Currently always return 0.
 *
 * This function is useful for controlling precise sleeps.
 * We usually have to process each video frame in a fixed interval.
 * Each time interval includes the processing time and the sleeping time.
 * However, the processing time could be different in each iteration, so
 * the sleeping time has to be adapted as well.
 * To achieve the goal, we have to obtain the baseline time \a ptv
 * (using \a gettimeofday function)
 * \em before the processing task and call this function \em after
 * the processing task. In this case, the \a interval is set to the total
 * length of the interval, e.g., 41667 for 24fps video.
 *
 * This function sleeps for \a interval micro seconds if the baseline
 * time is not specified.
 */
long long
ga_usleep(long long interval, struct timeval *ptv) {
	long long delta;
	struct timeval tv;
	if(ptv != NULL) {
		gettimeofday(&tv, NULL);
		delta = tvdiff_us(&tv, ptv);
		if(delta >= interval) {
			usleep(1);
			return -1;
		}
		interval -= delta;
	}
	usleep(interval);
	return 0LL;
}

/**
 * Write message \a s into the log file.
 * This in an internal function only called by \em ga_log function.
 *
 * @param tv [in] The timestamp of logging.
 * @param s [in] The message to be written.
 *
 * This function is SLOW, but it attempts to make all writes successfull.
 * It appends the message into the file each time when it is called.
 */
static void
ga_writelog(struct timeval tv, const char *s) {
	FILE *fp;
	if(ga_logfile == NULL)
		return;
	if((fp = fopen(ga_logfile, "at")) != NULL) {
		fprintf(fp, "[%d] %ld.%06ld %s", getpid(), tv.tv_sec, tv.tv_usec, s);
		fclose(fp);
	}
	return;
}

/**
 * Write log messages and print on Android console.
 *
 * @param fmt [in] The format string for the message.
 * @param ... [in] The arguments for replacing specifiers in the format string.
 *
 * This function has the same syntax as the \em printf function.
 * It outputs a timestamp before the message, and optionally writing
 * the message into a log file if log feature is turned on.
 */
int
ga_log(const char *fmt, ...) {
	char msg[4096];
	struct timeval tv;
	va_list ap;
	//
	gettimeofday(&tv, NULL);
	va_start(ap, fmt);
#ifdef ANDROID
	__android_log_vprint(ANDROID_LOG_INFO, "ga_log.native", fmt, ap);
#endif
	vsnprintf(msg, sizeof(msg), fmt, ap);
	va_end(ap);
	//
	ga_writelog(tv, msg);
	//
	return 0;
}

/**
 * Print out log messages (on \em stderr or log console (on Android)).
 *
 * @param fmt [in] The format string for the message.
 * @param ... [in] The arguments for replacing specifiers in the format string.
 *
 * This function has the same syntax as the \em printf function.
 * It outputs a timestamp before the message.
 */
int
ga_error(const char *fmt, ...) {
	char msg[4096];
	struct timeval tv;
	va_list ap;
	gettimeofday(&tv, NULL);
	va_start(ap, fmt);
#ifdef ANDROID
	__android_log_vprint(ANDROID_LOG_INFO, "ga_log.native", fmt, ap);
#endif
	vsnprintf(msg, sizeof(msg), fmt, ap);
	va_end(ap);
	fprintf(stderr, "# [%d] %ld.%06ld %s", getpid(), tv.tv_sec, tv.tv_usec, msg);
	//
	ga_writelog(tv, msg);
	//
	return -1;
}

/**
 * malloc() and return the offset to align pointer at 16-byte boundary.
 *
 * @param size [in] Requested memory space.
 * @param ptr [out] Pointer to the memory pointer.
 * @param alignment [out] Pointer to the alignment value.
 * @return 0 on success, or -1 on failure.
 *
 * Note: The actually allocated memory space is \a size + 16.
 * Data should be stored starting from \a *ptr + \a *alignment.
 */
int
ga_malloc(int size, void **ptr, int *alignment) {
	if((*ptr = malloc(size+16)) == NULL)
		return -1;
#ifdef __x86_64__
	*alignment = 16 - (((unsigned long long) *ptr) & 0x0f);
#else
	*alignment = 16 - (((unsigned) *ptr) & 0x0f);
#endif
	return 0;
}

/**
 * Compute the alignment offset for a given pointer and the align-to value.
 *
 * @param ptr [in] The pointer address used to compute alignment offset.
 * @param alignto [in] The align-to value, must be 2^n, e.g., 1, 2, 4, 8, 16.
 * @return The alignment offset has to be added to the pointer address.
 *
 * Note that this function does not check the alignto value.
 * The caller must ensure that the \a alignto value must be 2^n, n >= 0.
 */
int
ga_alignment(void *ptr, int alignto) {
	int mask = alignto - 1;
#ifdef __x86_64__
	return alignto - (((unsigned long long) ptr) & mask);
#else
	return alignto - (((unsigned) ptr) & mask);
#endif
}

/**
 * Get the thread ID in long format.
 */
long
ga_gettid() {
#ifdef WIN32
	return GetCurrentThreadId();
#elif defined __APPLE__
	return pthread_mach_thread_np(pthread_self());
#elif defined ANDROID
	return gettid();
#else
	return (pid_t) syscall(SYS_gettid);
#endif
}

/**
 * Initialize windows socket sub-system.
 *
 * @return 0 on success and -1 on error.
 */
static int
winsock_init() {
#ifdef WIN32
	WSADATA wd;
	if(WSAStartup(MAKEWORD(2,2), &wd) != 0)
		return -1;
#endif
	return 0;
}

/**
 * List registered ffmpeg codecs.
 * This function is for debug purpose, and could be removed in the future.
 */
void
ga_dump_codecs() {
	int n, count;
	char buf[8192], *ptr;
	AVCodec *c = NULL;
	n = snprintf(buf, sizeof(buf), "Registered codecs: ");
	ptr = &buf[n];
	count = 0;
	for(c = av_codec_next(NULL); c != NULL; c = av_codec_next(c)) {
		n = snprintf(ptr, sizeof(buf)-(ptr-buf), "%s ",
				c->name);
		ptr += n;
		count++;
	}
	snprintf(ptr, sizeof(buf)-(ptr-buf), "(%d)\n", count);
	ga_error(buf);
	return;
}

/**
 * Initialize GamingAnywhere
 *
 * @param config [in] Pathname to the configuration file
 * @param url [in] URL to the server URL address, in the form of rtsp://serveraddress:port/path
 * @return 0 on success or -1 on error
 */
int
ga_init(const char *config, const char *url) {
	srand(time(0));
	winsock_init();
#ifndef ANDROID_NO_FFMPEG
	av_register_all();
	avcodec_register_all();
	avformat_network_init();
	//ga_dump_codecs();
#endif
	if(config != NULL) {
		if(ga_conf_load(config) < 0) {
			ga_error("GA: cannot load configuration file '%s'\n", config);
			return -1;
		}
	}
	if(url != NULL) {
		if(ga_url_parse(url) < 0) {
			ga_error("GA: invalid URL '%s'\n", url);
			return -1;
		}
	}
	return 0;
}

/**
 * Deinitialize GamingAnywhere: currently do nothing
 */
void
ga_deinit() {
	return;
}

/**
 * Enable log feature
 *
 * This function must be called if you plan to write logs into a file.
 * It reads the \em logfile option specified in the configuration file.
 */
void
ga_openlog() {
	char fn[1024];
	FILE *fp;
	//
	if(ga_conf_readv("logfile", fn, sizeof(fn)) == NULL)
		return;
	if((fp = fopen(fn, "at")) != NULL) {
		fclose(fp);
		ga_logfile = strdup(fn);
	}
	//
	return;
}

/**
 * Disable log feature
 */
void
ga_closelog() {
	if(ga_logfile != NULL) {
		free(ga_logfile);
		ga_logfile = NULL;
	}
	return;
}

// save file feature

/**
 * Internal function for \em ga_save_init and \em ga_save_init_txt.
 * Returns the FILE pointer.
 *
 * @param filename [in] Pathname to store the image data.
 * @param mode [in] File access mode pass to \em fopen function.
 * @return FILE pointer to the opened file.
 */
static FILE *
ga_save_init_internal(const char *filename, const char *mode) {
	FILE *fp = NULL;
	if(filename != NULL) {
		fp = fopen(filename, mode);
		if(fp == NULL) {
			ga_error("save file: open %s failed.\n", filename);
		}
	}
	return fp;
}

/**
 * Return the FILE pointer used to store saved raw image frame data.
 *
 * @param filename [in] Pathname to store the image data.
 * @return FILE pointer to the opened file.
 *
 * This function must be called if you plan to use the
 * save raw video image feature.
 * All captured images will be stored in this single file.
 */
FILE *
ga_save_init(const char *filename) {
	return ga_save_init_internal(filename, "wb");
}

/**
 * Return the FILE pointer used to stora text-based meta-data for saved image frame.
 *
 * @param filename [in] Pathname to store the text-based meta-data.
 * @return the FILE pointer to the opened file.
 *
 * This function can be called optionally when you need to store
 * text-based meta data for saved raw video image.
 * All stored meta-data will be stored in this single file.
 */
FILE *
ga_save_init_txt(const char *filename) {
	return ga_save_init_internal(filename, "wt");
}

/**
 * Save arbitrary binary data.
 *
 * @param fp [in] FILE pointer to the opened file (by \em ga_save_init).
 * @param buffer [in] Pointer to the data memory.
 * @param size [in] Size of the data, in bytes.
 */
int
ga_save_data(FILE *fp, unsigned char *buffer, int size) {
	if(fp == NULL || buffer == NULL || size < 0)
		return -1;
	if(size == 0)
		return 0;
	return fwrite(buffer, sizeof(char), size, fp);
}

/**
 * Save text data.
 *
 * @param fp [in] FILE pointer to the opened file (by \em ga_save_init_txt).
 * @param fmt [in] Pointer the for format string.
 * @param ... [in] Arguments for specifiers in the format string.
 */
int
ga_save_printf(FILE *fp, const char *fmt, ...) {
	int wlen;
	va_list ap;
	if(fp == NULL)
		return -1;
	va_start(ap, fmt);
	wlen = vfprintf(fp, fmt, ap);
	va_end(ap);
	fflush(fp);
	return wlen;
}

/**
 * Save YUV420 image frame data
 *
 * @param fp [in] FILE pointer to the opened file (by \em ga_save_init).
 * @param w [in] Width of the frame.
 * @param h [in] Height of the frame.
 * @param planes [in] Pointers to address of (3) planes [Y, U, and V].
 * @param linesize [in] Pointers to linesize.
 */
int
ga_save_yuv420p(FILE *fp, int w, int h, unsigned char *planes[], int linesize[]) {
	int i, j, wlen, written = 0;
	int w2 = w/2;
	int h2 = h/2;
	int expected = w * h * 3 / 2;
	unsigned char *src;
	if(fp == NULL || w <= 0 || h <= 0 || planes == NULL || linesize == NULL)
		return -1;
	// write Y
	src = planes[0];
	for(i = 0; i < h; i++) {
		if((wlen = fwrite(src, sizeof(char), w, fp)) < 0)
			goto err_save_yuv;
		written += wlen;
		src += linesize[0];
	}
	// write U/V
	for(j = 1; j < 3; j++) {
		src = planes[j];
		for(i = 0; i < h2; i++) {
			if((wlen = fwrite(src, sizeof(char), w2, fp)) < 0)
				goto err_save_yuv;
			written += wlen;
			src += linesize[j];
		}
	}
	//
	if(written != expected) {
		ga_error("save YUV (%dx%d): expected %d, save %d (frame may be corrupted)\n",
			w, h, expected, written);
	}
	//
	fflush(fp);
	return written;
err_save_yuv:
	return -1;
}

/**
 * Save RGB4 image frame data
 *
 * @param fp [in] FILE pointer to the opened file (by \em ga_save_init).
 * @param w [in] Width of the frame.
 * @param h [in] Height of the frame.
 * @param planes [in] Pointers to the image data memory.
 * @param linesize [in] linesize, usually \a h * pixel size plus (optional) alignments.
 */
int
ga_save_rgb4(FILE *fp, int w, int h, unsigned char *planes, int linesize) {
	int i, wlen, written = 0;
	int w4 = w*4;
	int expected = w * h * 4;
	if(fp == NULL || w <= 0 || h <= 0 || planes == NULL || linesize < w4)
		return -1;
	// write
	for(i = 0; i < h; i++) {
		if((wlen = fwrite(planes, sizeof(char), w4, fp)) < 0)
			goto err_save_rgb4;
		written += wlen;
		planes += linesize;
	}
	//
	if(written != expected) {
		ga_error("save RGB4 (%dx%d): expected %d, save %d (frame may be corrupted)\n",
			w, h, expected, written);
	}
	//
	fflush(fp);
	return written;
err_save_rgb4:
	return -1;
}

/**
 * Close a file opened by \em ga_save_init or \em ga_save_init_txt
 *
 * @param fp [in] The opened file pointer.
 * @return This function currently always returns 0.
 */
int
ga_save_close(FILE *fp) {
	if(fp != NULL) {
		fclose(fp);
	}
	return 0;
}

//

static map<int,list<int> > aggmap;

/**
 * Clear everything in the aggregated output buffer.
 */
void
ga_aggregated_reset() {
	aggmap.clear();
	return;
}

/**
 * Output aggregated statistic numbers periodically
 *
 * @param key [in] The key used to uniquely identify an record series.
 * @param limit [in] Output buffered records when the number of records
 *		reaches the \a limit
 * @param value [in] The value to be output
 *
 * This function is used to reduce the output frequency of statistics.
 * If you need to output integer statistics but does not want the output
 * affect the performance too much.
 * You can consider use the aggregated output function.
 * Call this function to output an integer value as usual but the output
 * is only output when the number of records reaches the limit.
 * The \a key value must be different for different statistic series.
 * The \a limit value would be better to be a distinct prime number:
 * To prevent output from different series collides at the same time.
 */
void
ga_aggregated_print(int key, int limit, int value) {
	map<int,list<int> >::iterator mi;
	// push data
	if((mi = aggmap.find(key)) == aggmap.end()) {
		aggmap[key].push_back(value);
		return;
	} else {
		mi->second.push_back(value);
	}
	// output?
	if(mi->second.size() >= limit) {
		int pos, left, wlen;
		char *ptr, buf[16384] = "AGGREGATED-VALUES:";
		list<int>::iterator li;
		struct timeval tv;
		//
		pos = snprintf(buf, sizeof(buf), "AGGREGATED-OUTPUT[%04x]:", key);
		left = sizeof(buf) - pos;
		ptr = buf + pos;
		for(li = mi->second.begin(); li != mi->second.end() && left>16; li++) {
			wlen = snprintf(ptr, left, " %d", *li);
			ptr += wlen;
			left -= wlen;
		}
		if(li != mi->second.end()) {
			ga_error("insufficeient space for aggregated messages.\n");
		}
		mi->second.clear();
		//
		gettimeofday(&tv, NULL);
#ifdef ANDROID
		__android_log_write(ANDROID_LOG_INFO, "ga_log.native", buf);
#else
		fprintf(stderr, "# [%d] %ld.%06ld %s\n",
			getpid(), tv.tv_sec, tv.tv_usec, buf);
#endif
		ga_writelog(tv, buf);
	}
	//
	return;
}

/**
 * Convert a number represented in a string to a long integer.
 *
 * @param str [in] The number string.
 * @return The converted number in long format.
 */
long
ga_atoi(const char *str) {
	// XXX: not sure why sometimes windows strtol failed on
	// handling read-only constant strings ...
	char buf[64];
	long val;
	strncpy(buf, str, sizeof(buf));
	val = strtol(buf, NULL, 0);
	return val;
}

struct gaRect *
ga_fillrect(struct gaRect *rect, int left, int top, int right, int bottom) {
	if(rect == NULL)
		return NULL;
#define SWAP(a,b)	do { int tmp = a; a = b; b = tmp; } while(0);
	if(left > right)
		SWAP(left, right);
	if(top > bottom)
		SWAP(top, bottom);
#undef	SWAP
	rect->left = left;
	rect->top = top;
	rect->right = right;
	rect->bottom = bottom;
	//
	rect->width = rect->right - rect->left + 1;
	rect->height = rect->bottom - rect->top + 1;
	rect->linesize = rect->width * RGBA_SIZE;
	rect->size = rect->width * rect->height * RGBA_SIZE;
	//
	if(rect->width <= 0 || rect->height <= 0) {
		ga_error("# invalid rect size (%dx%d)\n", rect->width, rect->height);
		return NULL;
	}
	//
	return rect;
}

#ifdef WIN32
int
ga_crop_window(struct gaRect *rect, struct gaRect **prect) {
	char wndname[1024], wndclass[1024];
	char *pname;
	char *pclass;
	int dw, dh, find_wnd_arg = 0;
	HWND hWnd;
	RECT client;
	POINT lt, rb;
	//
	if(rect == NULL || prect == NULL)
		return -1;
	//
	pname = ga_conf_readv("find-window-name", wndname, sizeof(wndname));
	pclass = ga_conf_readv("find-window-class", wndclass, sizeof(wndclass));
	//
	if(pname != NULL && *pname != '\0')
		find_wnd_arg++;
	if(pclass != NULL && *pclass != '\0')
		find_wnd_arg++;
	if(find_wnd_arg <= 0) {
		*prect = NULL;
		return 0;
	}
	//
	if((hWnd = FindWindow(pclass, pname)) == NULL) {
		ga_error("FindWindow failed for '%s/%s'\n",
			pclass ? pclass : "",
			pname ? pname : "");
		return -1;
	}
	//
	GetWindowText(hWnd, wndname, sizeof(wndname));
	dw = GetSystemMetrics(SM_CXSCREEN);
	dh = GetSystemMetrics(SM_CYSCREEN);
	//
	ga_error("Found window (0x%08x) :%s%s%s%s\n", hWnd,
		pclass ? " class=" : "",
		pclass ? pclass : "",
		pname ? " name=" : "",
		pname ? pname : "");
	//
	if(SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE|SWP_SHOWWINDOW) == 0) {
		ga_error("SetWindowPos failed.\n");
		return -1;
	}
	if(GetClientRect(hWnd, &client) == 0) {
		ga_error("GetClientRect failed.\n");
		return -1;
	}
	if(SetForegroundWindow(hWnd) == 0) {
		ga_error("SetForegroundWindow failed.\n");
	}
	//
	lt.x = client.left;
	lt.y = client.top;
	rb.x = client.right-1;
	rb.y = client.bottom-1;
	//
	if(ClientToScreen(hWnd, &lt) == 0
	|| ClientToScreen(hWnd, &rb) == 0) {
		ga_error("Map from client coordinate to screen coordinate failed.\n");
		return -1;
	}
	//
	rect->left = lt.x;
	rect->top = lt.y;
	rect->right = rb.x;
	rect->bottom = rb.y;
	// size check: multiples of 2?
	if((rect->right - rect->left + 1) % 2 != 0)
		rect->left--;
	if((rect->bottom - rect->top + 1) % 2 != 0)
		rect->top--;
	//
	if(rect->left < 0 || rect->top < 0 || rect->right >= dw || rect->bottom >= dh) {
		ga_error("Invalid window: (%d,%d)-(%d,%d) w=%d h=%d (screen dimension = %dx%d).\n",
			rect->left, rect->top, rect->right, rect->bottom,
			rect->right - rect->left + 1,
			rect->bottom - rect->top + 1);
		return -1;
	}
	//
	*prect = rect;
	return 1;
}
#elif defined(__APPLE__) || defined(ANDROID)
int
ga_crop_window(struct gaRect *rect, struct gaRect **prect) {
	// XXX: implement find window for Apple
	*prect = NULL;
	return 0;
}
#else /* X11 */
Window
FindWindowX(Display *dpy, Window top, const char *name) {
	Window *children, dummy;
	unsigned int i, nchildren;
	Window w = 0;
	char *window_name;

	if(XFetchName(dpy, top, &window_name) && !strcmp(window_name, name)) {
		return(top);
	}

	if(!XQueryTree(dpy, top, &dummy, &dummy, &children, &nchildren))
		return(0);

	for(i = 0; i < nchildren; i++) {
		w = FindWindowX(dpy, children[i], name);
		if (w) {
			break;
		}
	}

	if (children)
		XFree ((char *)children);

	return(w);
}

int
GetClientRectX(Display *dpy, int screen, Window window, struct gaRect *rect) {
	XWindowAttributes win_attributes;
	int rx, ry;
	Window tmpwin;
	//
	if(rect == NULL)
		return -1;
	if(!XGetWindowAttributes(dpy, window, &win_attributes))
		return -1;
	XTranslateCoordinates(dpy, window, win_attributes.root,
		-win_attributes.border_width,
		-win_attributes.border_width,
		&rx, &ry, &tmpwin);
	rect->left = rx;
	rect->top = ry;
	rect->right = rx + win_attributes.width - 1;
	rect->bottom = ry + win_attributes.height - 1;
	return 0;
}

int
ga_crop_window(struct gaRect *rect, struct gaRect **prect) {
	char display[16], wndname[1024];
	char *pdisplay, *pname;
	Display *d = NULL;
	int dw, dh, screen = 0;
	Window w = 0;
	//
	if(rect == NULL || prect == NULL)
		return -1;
	//
	if((pdisplay = ga_conf_readv("display", display, sizeof(display))) == NULL) {
		*prect = NULL;
		return 0;
	}
	if((pname = ga_conf_readv("find-window-name", wndname, sizeof(wndname))) == NULL) {
		*prect = NULL;
		return 0;
	}
	//
	if((d = XOpenDisplay(pdisplay)) == NULL) {
		ga_error("ga_crop_window: cannot open display %s\n", display);
		return -1;
	}
	screen = XDefaultScreen(d);
	dw = DisplayWidth(d, screen);
	dh = DisplayHeight(d, screen);
	if((w = FindWindowX(d, RootWindow(d, screen), pname)) == 0) {
		ga_error("FindWindowX failed for %s/%s\n", pdisplay, pname);
		XCloseDisplay(d);
		return -1;
	}
	if(GetClientRectX(d, screen, w, rect) < 0) {
		ga_error("GetClientRectX failed for %s/%s\n", pdisplay, pname);
		XCloseDisplay(d);
		return -1;
	}
	XRaiseWindow(d, w);
	XSetInputFocus(d, w, RevertToNone, CurrentTime);
	XCloseDisplay(d);
	// size check: multiples of 2?
	if((rect->right - rect->left + 1) % 2 != 0)
		rect->left--;
	if((rect->bottom - rect->top + 1) % 2 != 0)
		rect->top--;
	// window is all visible?
	if(rect->left < 0 || rect->top < 0 || rect->right >= dw || rect->bottom >= dh) {
		ga_error("Invalid window: (%d,%d)-(%d,%d) w=%d h=%d (screen dimension = %dx%d).\n",
			rect->left, rect->top, rect->right, rect->bottom,
			rect->right - rect->left + 1,
			rect->bottom - rect->top + 1,
			dw, dh);
		return -1;
	}
	//
	*prect = rect;
	return 1;
}
#endif

/**
 * Show the backtrace of current process
 * This function is only for debug purpose.
 */
void
ga_backtrace() {
#if defined(WIN32) || defined(ANDROID)
	return;
#else
	int j, nptrs;
#define SIZE 100
	void *buffer[SIZE];
	char **strings;

	nptrs = backtrace(buffer, SIZE);
	printf("-- backtrace() returned %d addresses -----------\n", nptrs);

	strings = backtrace_symbols(buffer, nptrs);
	if (strings == NULL) {
		perror("backtrace_symbols");
		exit(-1);
	}

	for (j = 0; j < nptrs; j++)
		printf("%s\n", strings[j]);

	free(strings);
	printf("------------------------------------------------\n");
#endif	/* WIN32 */
}

/**
 * This function is not used.
 * It is sometimes that a function is optimized out because it is not
 * called by the function.
 * Put those function here to prevent them from being optimized out.
 */
void
ga_dummyfunc() {
#ifndef ANDROID_NO_FFMPEG
	// place some required functions - for link purpose
	swr_alloc_set_opts(NULL, 0, (AVSampleFormat) 0, 0, 0, (AVSampleFormat) 0, 0, 0, NULL);
#endif
	return;
}

/**
 * Data struture to describe codecs supported by GA.
 * The last data must have a key of NULL.
 */
struct ga_codec_entry {
	const char *key;	/**< Key to identify the codec, must be unique */
	enum AVCodecID id;	/**< codec Id: defined in (ffmpeg) AVCodecID */
	const char *mime;	/**< MIME-type name */
	const char *ffmpeg_decoders[4]; /**< The ffmpeg decoder name */
};

/**
 * The codec table.
 */
struct ga_codec_entry ga_codec_table[] = {
	{ "H264", AV_CODEC_ID_H264, "video/avc", { "h264", NULL } },
	{ "H265", AV_CODEC_ID_H265, "video/hevc", { "hevc", NULL } },
	{ "VP8", AV_CODEC_ID_VP8, "video/x-vnd.on2.vp8", { "libvpx", NULL } },
	{ "MPA", AV_CODEC_ID_MP3, "audio/mpeg", { "mp3", NULL } },
	{ "OPUS", AV_CODEC_ID_OPUS, "audio/opus", { "libopus", NULL } },
	{ NULL, AV_CODEC_ID_NONE, NULL, { NULL } } /* END */
};

/**
 * Get the codec entry from the codec table by key.
 */
static ga_codec_entry *
ga_lookup_core(const char *key) {
	int i = 0;
	while(i >= 0 && ga_codec_table[i].key != NULL) {
		if(strcasecmp(ga_codec_table[i].key, key) == 0)
			return &ga_codec_table[i];
		i++;
	}
	return NULL;
}

/**
 * Get the codec MIME-type from the codec table by key.
 */
const char *
ga_lookup_mime(const char *key) {
	struct ga_codec_entry * e = ga_lookup_core(key);
	if(e==NULL || e->mime==NULL) {
		ga_error("ga_lookup[%s]: mime not found\n", key);
		return NULL;
	}
	return e->mime;
}

/**
 * Get the codec ffmpeg decoders from the codec table by key.
 */
const char **
ga_lookup_ffmpeg_decoders(const char *key) {
	struct ga_codec_entry * e = ga_lookup_core(key);
	if(e==NULL || e->ffmpeg_decoders==NULL) {
		ga_error("ga_lookup[%s]: ffmpeg decoders not found\n", key);
		return NULL;
	}
	return e->ffmpeg_decoders;
}

/**
 * Get the codec Id from the codec table by key.
 */
enum AVCodecID
ga_lookup_codec_id(const char *key) {
	struct ga_codec_entry * e = ga_lookup_core(key);
	if(e==NULL) {
		ga_error("ga_lookup[%s]: codec id not found\n", key);
		return AV_CODEC_ID_NONE;
	}
	return e->id;
}


text:
"""
background_systems.py contains BackgroundSystem, which contains different arrays relating to
the evolution of fuel blends, sulfur content in fuels, and electricity mixes in different
countries over time.
"""

from typing import Dict

import numpy as np
import pandas as pd
import xarray as xr

from . import DATA_DIR

def data_to_dict(csv_list: list) -> dict:
    """
    Returns a dictionary from a sequence of items.
    :param csv_list: list
    :return: dict
    """

    (_, *header), *data = csv_list
    csv_dict = {}
    for row in data:
        key, *values = row
        csv_dict[key] = dict(zip(header, values))

    return csv_dict

def get_electricity_losses() -> Dict[str, float]:
    """
    Retrieve cumulative electricity losses from high to medium and low voltage.
    Source: `ecoinvent v.3.6 <https://www.ecoinvent.org/>`_.

    :returns: dictionary
    :rtype: dict

    """
    filename = "cumulative_electricity_losses.csv"
    filepath = DATA_DIR / filename
    if not filepath.is_file():
        raise FileNotFoundError(
            "The CSV file that contains electricity mixes could not be found."
        )
    with open(filepath, encoding="utf-8") as file:
        csv_list = [[val.strip() for val in r.split(";")] for r in file.readlines()]

    return data_to_dict(csv_list)

def get_region_mapping() -> Dict[str, str]:
    """
    Retrieve mapping between ISO country codes and REMIND regions.

    :returns: dictionary
    :rtype: dict

    """
    filename = "region_mapping.csv"
    filepath = DATA_DIR / filename
    if not filepath.is_file():
        raise FileNotFoundError(
            "The CSV file that contains correspondences between REMIND region "
            "names and ISO country codes could not be found."
        )
    with open(filepath, encoding="utf-8") as file:
        csv_list = [[val.strip() for val in r.split(";")] for r in file.readlines()]

    return data_to_dict(csv_list)

def get_electricity_mix() -> xr.DataArray:
    """
    Retrieve electricity mixes and shape them into a xarray.
    Source:
        * for European countries (`ENTSOE TYNDP 2020 scenarios <https://2020.entsos-tyndp-scenarios.eu/>`_),
        * for African countries (`TEMBA <http://www.osemosys.org/temba.html>`_ model)
        * and for other countries (`IEA World Energy outlook 2017 <https://www.iea.org/reports/world-energy-outlook-2017>`_)

    :returns: An axarray with 'country' and 'year' as dimensions
    :rtype: xarray.core.dataarray.DataArray

    """
    filename = "electricity_mixes.csv"
    filepath = DATA_DIR / filename
    if not filepath.is_file():
        raise FileNotFoundError(
            "The CSV file that contains electricity mixes could not be found."
        )

    dataframe = pd.read_csv(filepath, sep=";", index_col=["country", "year"])
    dataframe = dataframe.reset_index()

    array = (
        dataframe.melt(id_vars=["country", "year"], value_name="value")
        .groupby(["country", "year", "variable"])["value"]
        .mean()
        .to_xarray()
    )
    array = array.interpolate_na(
        dim="year", method="linear", fill_value="extrapolate"
    ).clip(0, 1)
    array /= array.sum(axis=2)

    return array

def get_biofuel_share() -> xr.DataArray:
    """
    Retrieve shares of biofuel consumption from REMIND and shape them into an xarray.

    :return: An axarray with 'country' and 'year' as dimensions
    :rtype: xarray.core.dataarray.DataArray
    """
    filename = "biofuel_share.csv"
    filepath = DATA_DIR / filename

    if not filepath.is_file():
        raise FileNotFoundError(
            "The CSV file that contains biofuel shares could not be found."
        )
    dataframe = pd.read_csv(filepath, sep=";")

    country_codes = dataframe["Region"].unique()
    scenarios = dataframe["Scenario"].unique()
    year = dataframe["Year"].unique()
    tech = dataframe.columns[3:]
    array = xr.DataArray(
        np.zeros((len(country_codes), len(year), len(scenarios), len(tech), 1)),
        coords=[country_codes, year, scenarios, tech, np.arange(1)],
        dims=["region", "year", "scenario", "fuel_type", "value"],
    )
    for country_code in country_codes:
        for scenario in scenarios:
            val = dataframe.loc[
                (dataframe["Region"] == country_code)
                & (dataframe["Scenario"] == scenario),
                "Biomass fuel":,
            ]
            array.loc[dict(region=country_code, scenario=scenario, value=0)] = val
    return array

def get_biomethane_share() -> xr.DataArray:
    """

    :return: Returns an xarray with share of biomethane in the fuel blend, per country, per year.
    """
    filename = "share_bio_cng.csv"
    filepath = DATA_DIR / filename

    if not filepath.is_file():
        raise FileNotFoundError(
            "The CSV file that contains biomethane shares could not be found."
        )
    dataframe = pd.read_csv(filepath, sep=";")

    return dataframe.groupby(["country", "year"]).sum().to_xarray().to_array()

def get_biogasoline_share() -> xr.DataArray:
    """

    :return: Returns an xarray with share of bioethanol in the fuel blend, per country, per year.
    """
    filename = "share_bio_gasoline.csv"
    filepath = DATA_DIR / filename

    if not filepath.is_file():
        raise FileNotFoundError(
            "The CSV file that contains biogasoline shares could not be found."
        )
    dataframe = pd.read_csv(filepath, sep=";")

    return dataframe.groupby(["country", "year"]).sum().to_xarray().to_array()

def get_biodiesel_share() -> xr.DataArray:
    """

    :return: Returns an xarray with share of biodiesel in the fuel blend, per country, per year.
    """
    filename = "share_bio_diesel.csv"
    filepath = DATA_DIR / filename

    if not filepath.is_file():
        raise FileNotFoundError(
            "The CSV file that contains biodiesel shares could not be found."
        )
    dataframe = pd.read_csv(filepath, sep=";")

    return dataframe.groupby(["country", "year"]).sum().to_xarray().to_array()

def get_sulfur_content_in_fuel() -> xr.DataArray:
    """
    Retrieve sulfur content per kg of petrol and diesel.
    For CH, DE, FR, AU and SE, the concentration values come from HBEFA 4.1, from 1909 to 2020 (extrapolated to 2050).

    For the other countries, values come from
    Miller, J. D., & Jin, L. (2019). Global progress toward soot-free diesel vehicles in 2019.
    International Council on Clean Transportation.
    https://www.theicct.org/publications/global-progress-toward-soot-free-diesel-vehicles-2019

    There is an assumption made: countries that have high-sulfur content fuels (above 50 ppm in 2019) are assumed to
    improve over time to reach 50 ppm by 2050.

    :return: An axarray with 'country' and 'year' as dimensions
    :rtype: xarray.core.dataarray.DataArray
    """
    filename = "S_concentration_fuel.csv"
    filepath = DATA_DIR / filename

    if not filepath.is_file():
        raise FileNotFoundError(
            "The CSV file that contains sulfur concentration values could not be found."
        )
    dataframe = pd.read_csv(filepath, sep=";")
    dataframe = dataframe.groupby(["country", "year"]).sum().unstack()
    dataframe.loc[:, ("diesel", 1990)] = dataframe["diesel"].max(1)
    dataframe.loc[:, ("petrol", 1990)] = dataframe["petrol"].max(1)

    dataframe.loc[dataframe[("diesel", 2019)] > 50 / 1e6, ("diesel", 2050)] = 50 / 1e6
    dataframe.loc[dataframe[("petrol", 2019)] > 50 / 1e6, ("petrol", 2050)] = 50 / 1e6
    dataframe.loc[:, ("diesel", 2050)] = dataframe["diesel"].min(1)
    dataframe.loc[:, ("petrol", 2050)] = dataframe["petrol"].min(1)

    dataframe = dataframe.interpolate(axis=1)
    dataframe = dataframe.unstack().reset_index()
    dataframe = dataframe.rename(columns={"level_0": "fuel"})
    arr = dataframe.groupby(["country", "year", "fuel"]).sum()[0].to_xarray()
    return arr

class BackgroundSystemModel:
    """
    Retrieve and build dictionaries that contain important information to model in the background system:

        * gross electricity production mixes from nearly all countries in the world, from 2015 to 2050.
        * cumulative electricity transformation/transmission/distribution losses from high voltage to medium and low voltage.
        * share of biomass-derived fuel in the total consumption of liquid fuel in the transport sector. Source: REMIND.
        * share of bioethanol, biodiesel and biomethane, for each country, for different years.
        * share of sulfur in gasoline and diesel, for different countries and years.
    """

    def __init__(self) -> None:
        self.electricity_mix = get_electricity_mix()
        self.losses = get_electricity_losses()
        self.region_map = get_region_mapping()
        self.biofuel = get_biofuel_share()
        self.sulfur = get_sulfur_content_in_fuel()
        self.biomethane = get_biomethane_share()
        self.biogasoline = get_biogasoline_share()
        self.biodiesel = get_biodiesel_share()

    def __str__(self):
        return self.__class__.__name__

redpajama_set_name: RedPajamaGithub


text:
namespace hyrise {

class SecondTestPlugin : public AbstractPlugin {
 public:
  SecondTestPlugin() : storage_manager(Hyrise::get().storage_manager) {}

  std::string description() const final;

  void start() final;

  void stop() final;

  std::vector<std::pair<PluginFunctionName, PluginFunctionPointer>> provided_user_executable_functions() final;

  void a_user_executable_function() const;

  StorageManager& storage_manager;
};

}  // namespace hyrise


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.thinkaurelius.titan.diskstorage.log.util (Titan 1.0.0 API)</title>
<meta name="date" content="2015-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.thinkaurelius.titan.diskstorage.log.util

Class Summary

Class
Description

AbstractMessage

Abstract implementation of Message which exposes the timestamp, sender, and payload
 of a message.

FutureMessage<M extends Message>

Implementation of a Future for Messages that
 are being added to the Log via Log.add(com.thinkaurelius.titan.diskstorage.StaticBuffer).

ProcessMessageJob

Helper class for processing read messages with the registered message readers.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2012–2015. All rights reserved.


text:
using MiX.Integrate.API.Client.Base;
using MiX.Integrate.Shared.Constants;
using MiX.Integrate.Shared.Entities.Assets;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace MiX.Integrate.API.Client
{
	/// <inheritdoc cref="IAssetsClient"/>
	public class AssetsClient : BaseClient, IAssetsClient
	{
		public AssetsClient(string url, bool setTestRequestHeader = false) : base(url, setTestRequestHeader) { }
		public AssetsClient(string url, IdServerResourceOwnerClientSettings settings, bool setTestRequestHeader = false) : base(url, settings, setTestRequestHeader) { }

		public List<Asset> GetAll(long groupId)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETALL, HttpMethod.Get);
			request.AddUrlSegment("groupId", groupId.ToString());
			IHttpRestResponse<List<Asset>> response = Execute<List<Asset>>(request);
			return response.Data;
		}

		public async Task<List<Asset>> GetAllAsync(long groupId)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETALL, HttpMethod.Get);
			request.AddUrlSegment("groupId", groupId.ToString());
			IHttpRestResponse<List<Asset>> response = await ExecuteAsync<List<Asset>>(request).ConfigureAwait(false);
			return response.Data;
		}

		public List<AdditionalDetails> GetAdditionalDetailsByGroup(long groupId)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETADDITIONALDETAILSBYGROUP, HttpMethod.Get);
			request.AddUrlSegment("groupId", groupId.ToString());
			IHttpRestResponse<List<AdditionalDetails>> response = Execute<List<AdditionalDetails>>(request);
			return response.Data;
		}

		public async Task<List<AdditionalDetails>> GetAdditionalDetailsByGroupAsync(long groupId)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETADDITIONALDETAILSBYGROUP, HttpMethod.Get);
			request.AddUrlSegment("groupId", groupId.ToString());
			IHttpRestResponse<List<AdditionalDetails>> response = await ExecuteAsync<List<AdditionalDetails>>(request).ConfigureAwait(false);
			return response.Data;
		}

		public List<AssetDiagnostics> GetAssetDiagnostics(long organisationId, IList<long> assetIds)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETASSETDIAG, HttpMethod.Post);
			request.AddUrlSegment("groupId", organisationId.ToString());
			request.AddJsonBody(assetIds);
			IHttpRestResponse<List<AssetDiagnostics>> response = Execute<List<AssetDiagnostics>>(request);
			return response.Data;
		}

		public async Task<List<AssetDiagnostics>> GetAssetDiagnosticsAsync(long organisationId, IList<long> assetIds)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETASSETDIAG, HttpMethod.Post);
			request.AddUrlSegment("groupId", organisationId.ToString());
			request.AddJsonBody(assetIds);
			IHttpRestResponse<List<AssetDiagnostics>> response = await ExecuteAsync<List<AssetDiagnostics>>(request).ConfigureAwait(false);
			return response.Data;
		}

		public List<Asset> GetAll(long groupId, string filterType, string wildCard)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETALL, HttpMethod.Get);
			request.AddUrlSegment("groupId", groupId.ToString());
			request.AddQueryParameter("filterType", filterType);
			request.AddQueryParameter("wildCard", wildCard);
			IHttpRestResponse<List<Asset>> response = Execute<List<Asset>>(request);
			return response.Data;
		}

		public async Task<List<Asset>> GetAllAsync(long groupId, string filterType, string wildCard)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETALL, HttpMethod.Get);
			request.AddUrlSegment("groupId", groupId.ToString());
			request.AddQueryParameter("filterType", filterType);
			request.AddQueryParameter("wildCard", wildCard);
			IHttpRestResponse<List<Asset>> response = await ExecuteAsync<List<Asset>>(request).ConfigureAwait(false);
			return response.Data;
		}

		public Asset Get(long assetId)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GET, HttpMethod.Get);
			request.AddUrlSegment("assetId", assetId.ToString());
			IHttpRestResponse<Asset> response = Execute<Asset>(request);
			return response.Data;
		}

		public async Task<Asset> GetAsync(long assetId)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GET, HttpMethod.Get);
			request.AddUrlSegment("assetId", assetId.ToString());
			IHttpRestResponse<Asset> response = await ExecuteAsync<Asset>(request).ConfigureAwait(false);
			return response.Data;
		}

		public Asset GetByGroup(long groupId, long assetId)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETBYGROUP, HttpMethod.Get);
			request.AddUrlSegment("groupId", groupId.ToString());
			request.AddUrlSegment("assetId", assetId.ToString());
			IHttpRestResponse<Asset> response = Execute<Asset>(request);
			return response.Data;
		}

		public async Task<Asset> GetByGroupAsync(long groupId, long assetId)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETBYGROUP, HttpMethod.Get);
			request.AddUrlSegment("groupId", groupId.ToString());
			request.AddUrlSegment("assetId", assetId.ToString());
			IHttpRestResponse<Asset> response = await ExecuteAsync<Asset>(request).ConfigureAwait(false);
			return response.Data;
		}

		public void Update(Asset asset)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.UPDATE, HttpMethod.Put);
			request.AddJsonBody(asset);
			Execute(request);
		}

		public async Task UpdateAsync(Asset asset)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.UPDATE, HttpMethod.Put);
			request.AddJsonBody(asset);
			await ExecuteAsync(request).ConfigureAwait(false);
		}

		public bool AddAssetState(long groupId, AssetState assetState)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.ADDASSETSTATE, HttpMethod.Post);
			request.AddUrlSegment("groupId", groupId.ToString());
			request.AddJsonBody(assetState);
			IHttpRestResponse response = Execute(request);
			if (response.StatusCode == System.Net.HttpStatusCode.OK)
				return true;
			else
				return false;
		}

		public async Task<bool> AddAssetStateAsync(long groupId, AssetState assetState)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.ADDASSETSTATE, HttpMethod.Post);
			request.AddUrlSegment("groupId", groupId.ToString());
			request.AddJsonBody(assetState);
			IHttpRestResponse response = await ExecuteAsync(request).ConfigureAwait(false);
			if (response.StatusCode == System.Net.HttpStatusCode.OK)
				return true;
			else
				return false;
		}

		public long Add(Asset asset)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.ADD, HttpMethod.Post);
			request.AddJsonBody(asset);
			IHttpRestResponse response = Execute(request);
			string idHeaderVal = GetResponseHeader(response.Headers, "assetId");
			long assetId;
			if (!long.TryParse(idHeaderVal, out assetId) || assetId == 0)
				throw new Exception("Could not determine the id of the newly-created asset");
			return assetId;
		}

		public async Task<long> AddAsync(Asset asset)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.ADD, HttpMethod.Post);
			request.AddJsonBody(asset);
			IHttpRestResponse response = await ExecuteAsync(request).ConfigureAwait(false);
			string idHeaderVal = GetResponseHeader(response.Headers, "assetId");
			long assetId;
			if (!long.TryParse(idHeaderVal, out assetId) || assetId == 0)
				throw new Exception("Could not determine the id of the newly-created asset");
			return assetId;
		}

		public List<string> GetManufacturerNames()
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETMANUFACTURERS, HttpMethod.Get);
			IHttpRestResponse<List<string>> response = Execute<List<string>>(request);
			return response.Data;
		}

		public async Task<List<string>> GetManufacturerNamesAsync()
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETMANUFACTURERS, HttpMethod.Get);
			IHttpRestResponse<List<string>> response = await ExecuteAsync<List<string>>(request);
			return response.Data;
		}

		/// Gets a list of the <see cref="Trailer"/> assets for the specified organisation
		public List<Trailer> GetTrailers(long organisationId)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETTRAILERSFORORGANISATION, HttpMethod.Get);
			request.AddUrlSegment("organisationId", organisationId.ToString());
			IHttpRestResponse<List<Trailer>> response = Execute<List<Trailer>>(request);
			return response.Data;
		}

		/// Gets a list of the <see cref="Trailer"/> assets for the specified organisation
		public async Task<List<Trailer>> GetTrailersAsync(long organisationId)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETTRAILERSFORORGANISATION, HttpMethod.Get);
			request.AddUrlSegment("organisationId", organisationId.ToString());
			IHttpRestResponse<List<Trailer>> response = await ExecuteAsync<List<Trailer>>(request).ConfigureAwait(false);
			return response.Data;
		}

		public List<AssetService> GetServiceHistory(List<long> assetIds, DateTime @from, DateTime to)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETSERVICEHISTORY, HttpMethod.Post);
			request.AddUrlSegment("from", @from.ToString("yyyyMMdd"));
			request.AddUrlSegment("to", to.ToString("yyyyMMdd"));
			request.AddJsonBody(assetIds);
			IHttpRestResponse<List<AssetService>> response = Execute<List<AssetService>>(request);
			return response.Data;
		}

		public async Task<List<AssetService>> GetServiceHistoryAsync(List<long> assetIds, DateTime @from, DateTime to)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETSERVICEHISTORY, HttpMethod.Post);
			request.AddUrlSegment("from", @from.ToString("yyyyMMdd"));
			request.AddUrlSegment("to", to.ToString("yyyyMMdd"));
			request.AddJsonBody(assetIds);
			IHttpRestResponse<List<AssetService>> response = await ExecuteAsync<List<AssetService>>(request).ConfigureAwait(false);
			return response.Data;
		}

		public List<AssetService> GetServiceHistoryByGroup(long groupId, DateTime @from, DateTime to)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETSERVICEHISTORYBYGROUP, HttpMethod.Get);
			request.AddUrlSegment("groupId", groupId.ToString());
			request.AddUrlSegment("from", @from.ToString("yyyyMMdd"));
			request.AddUrlSegment("to", to.ToString("yyyyMMdd"));
			IHttpRestResponse<List<AssetService>> response = Execute<List<AssetService>>(request);
			return response.Data;
		}

		public async Task<List<AssetService>> GetServiceHistoryByGroupAsync(long groupId, DateTime @from, DateTime to)
		{
			IHttpRestRequest request = GetRequest(APIControllerRoutes.AssetsController.GETSERVICEHISTORYBYGROUP, HttpMethod.Get);
			request.AddUrlSegment("groupId", groupId.ToString());
			request.AddUrlSegment("from", @from.ToString("yyyyMMdd"));
			request.AddUrlSegment("to", to.ToString("yyyyMMdd"));
			IHttpRestResponse<List<AssetService>> response = await ExecuteAsync<List<AssetService>>(request).ConfigureAwait(false);
			return response.Data;
		}
	}
}


text:
package com.nvapp.mupdf;

public class LinkInfoInternal extends LinkInfo {
	final public int pageNumber;

	public LinkInfoInternal(float l, float t, float r, float b, int p) {
		super(l, t, r, b);
		pageNumber = p;
	}

	public void acceptVisitor(LinkInfoVisitor visitor) {
		visitor.visitInternal(this);
	}
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Foobar</title>
<link href="/static/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="/static/css/bootstrap-responsive.min.css" rel="stylesheet">

Foo, bar!

这是一个简单页面.

    了解更多...


text:
"use strict";

let express = require('express'),
	cookieParser = require('cookie-parser'),
    http = require('http'),
	resolver = require('./steam_user_resolver.js');

resolver.runTests();

const defaultUserSettings = {'methodSet':'default', 'methods':[], 'autocopy':null};

let app = express();
app.use(cookieParser());

app.get('/api/arbitraryStringToSteamId', function(req, res, next) {
    let ret = function(error, data) {
        if (error) {
            res.status(500).send({'error' : error.stack})
        } else if (!data) {
            res.status(404).send({'error' : 'not found'});
        } else {
			console.log(data.type);
			data = data.value;
		let theID = data.steamID;
            res.send({
                'name' : data.name,
                'steamId64' : theID.toString(),
		'steam32AccountId' : theID.accountid,
		'steamId32' : theID.getSteam3RenderedID(),
		'steam2Old' : theID.getSteam2RenderedID(),
		'steam2New' : theID.getSteam2RenderedID(true),
                'customURL' : data.customURL,
		'profileURL' : 'http://steamcommunity.com/profiles/' + theID.toString(),
		'isGroupchat' : theID.isGroupChat(),
		'isSteamLobby' : theID.isLobby(),
                'memberSince' : data.memberSince,
                'isOnline' : data.onlineState
            }); //TODO: more fields here
        }
    };
	let settings = cookieParser.JSONCookie(req.cookies.settings) || defaultUserSettings,
		methodsToTry = [],
		query = decodeURIComponent(req.query.string.trim());

	if (settings.methods && settings.methods.length) {
		//TODO: support custom methods ordering
	} else {
		methodsToTry = resolver.methodSets[settings.methodSet] || resolver.methodSets.default;
	}
	resolver.resolveSteamUser(query, methodsToTry, ret);
});

app.get('/', function(req, res, next) {
    res.sendFile( '/static/' + 'index.html');
});

http.createServer(app).listen(process.env.PORT || 8080, function() {
    console.log('Listening on port ' + (process.env.PORT || 8080));
});


text:
#region License

#endregion
using NAnt.Core;
using NAnt.Core.Attributes;
using System;
using System.IO;
using System.Linq;
using System.Patterns.ReleaseManagement;
namespace Digital.Nant.Hosting.Tasks
{
	[TaskName("manageIis"), Serializable]
	public partial class ManageIisTask : Task
	{
        [TaskAttribute("deploymentEnvironment", Required = true), StringValidator(AllowEmpty = false)]
        public DeploymentEnvironment DeploymentEnvironment { get; set; }

		[TaskAttribute("applicationId", Required = true), StringValidator(AllowEmpty = false)]
		public string ApplicationId { get; set; }

		[TaskAttribute("remove")]
		public bool Remove { get; set; }

		[BuildElementArray("binding")]
		public Binding[] Bindings { get; set; }

		private string ApplicationPath { get; set; }

		private decimal IisVersion { get; set; }

		private decimal LayoutVersion { get; set; }

		protected override void ExecuteTask()
		{
			LayoutVersion = 2M;
			IisVersion = 7M;
			var iis = (IisVersion != 6M ? (IIis)new Iis7 { Project = Project } : (IIis)new Iis6 { Project = Project });
			ApplicationPath = (!Project.Properties.Contains("applicationPath") ? @"C:\_APPLICATION2" : Project.Properties["applicationPath"]);
			// site
			var bindings = (Bindings != null ? Bindings.Select(c => new IisContext.Binding { Information = c.Information, Protocol = c.Protocol }).ToArray() : null);
			var iisContext = new IisContext
			{
				LayoutVersion = LayoutVersion,
				ApplicationPoolId = ApplicationId,
				ApplicationPoolUserId = DeploymentEnvironment.CreateAccountUserId(ApplicationId, "IUSR"),
				ApplicationPoolPassword = DeploymentEnvironment.CreateAccountPassword(ApplicationId, "IUSR"),
				Bindings = bindings,
				SiteId = ApplicationId,
				Domain = ApplicationId + "." + DeploymentEnvironment.ToShortName() + (DeploymentEnvironment.GetExternalDeployment() ? ".x.com" : ".x.com"),
				RootPath = ApplicationPath + @"\" + ApplicationId,
			};
			if (!Remove)
				iis.CreateSite(iisContext);
			else
				iis.RemoveSite(iisContext);
		}
	}
}


text:
'use strict';
var UglifyJS = require("uglify-js");
var glob = require("glob");
var fs = require("fs");
var path = require("path");
var cwd = process.cwd() + "/";
module.exports = function (grunt) {

    grunt.registerMultiTask('react_seajs', 'a plugin to translate react components to seajs modules', function () {
        var config = grunt.file.readJSON(cwd + this.data.config_file);
        config.merge = config.merge || [];
        for (var mergeIndex = 0; mergeIndex < config.merge.length; mergeIndex++) {
            var configS = config.merge[mergeIndex];
            if (typeof (configS.file) == "undefined" || typeof (configS.target) == "undefined") {
                grunt.log.error("can't know what file want to be merged at " + mergeIndex + " config");
                continue;
            }
            var filesMerge = [];
            configS.file.forEach(function (item) {
                item = cwd + item;
                var mg = glob(item, {mark: true, sync: true});
                filesMerge = filesMerge.concat(mg);
            });
            var result = UglifyJS.minify(filesMerge);
            result.code = "define(function(require,exports,modules){" + result.code + "});";
            fs.writeFileSync(cwd + configS.target, result.code, {encoding: 'utf8'});
        }

        config.single = config.single || [];
        for (var singleIndex = 0; singleIndex < config.single.length; singleIndex++) {
            var configS = config.single[singleIndex];
            if (typeof (configS.file) == "undefined" || typeof (configS.target) == "undefined") {
                grunt.log.error("can't know what file want to be moved at " + mergeIndex + " config");
                continue;
            }
            var filesSingle = [];
            configS.file.forEach(function (item) {
                item = cwd + item;
                var mg = glob(item, {mark: true, sync: true});
                filesSingle = filesSingle.concat(mg);
            });
            filesSingle.forEach(function (item) {
                var result = UglifyJS.minify(item);
                result.code = "define(function(require,exports,module){" + result.code + "});";
                fs.writeFileSync(cwd + configS.target + path.basename(item), result.code, {encoding: 'utf8'});
            });
        }
    });

};


text:
/**
 * @file lars_main.cpp
 * @author Nishant Mehta
 *
 * Executable for LARS.
 */
#include <mlpack/core.hpp>

#include "lars.hpp"

PROGRAM_INFO("LARS", "An implementation of LARS: Least Angle Regression "
    "(Stagewise/laSso).  This is a stage-wise homotopy-based algorithm for "
    "L1-regularized linear regression (LASSO) and L1+L2-regularized linear "
    "regression (Elastic Net).\n"
    "\n"
    "This program is able to train a LARS/LASSO/Elastic Net model or load a "
    "model from file, output regression predictions for a test set, and save "
    "the trained model to a file.  The LARS algorithm is described in more "
    "detail below:\n"
    "\n"
    "Let X be a matrix where each row is a point and each column is a "
    "dimension, and let y be a vector of targets.\n"
    "\n"
    "The Elastic Net problem is to solve\n\n"
    "  min_beta 0.5 || X * beta - y ||_2^2 + lambda_1 ||beta||_1 +\n"
    "      0.5 lambda_2 ||beta||_2^2\n\n"
    "If --lambda1 > 0 and --lambda2 = 0, the problem is the LASSO.\n"
    "If --lambda1 > 0 and --lambda2 > 0, the problem is the Elastic Net.\n"
    "If --lambda1 = 0 and --lambda2 > 0, the problem is ridge regression.\n"
    "If --lambda1 = 0 and --lambda2 = 0, the problem is unregularized linear "
    "regression.\n"
    "\n"
    "For efficiency reasons, it is not recommended to use this algorithm with "
    "--lambda_1 = 0.  In that case, use the 'linear_regression' program, which "
    "implements both unregularized linear regression and ridge regression.\n"
    "\n"
    "To train a LARS/LASSO/Elastic Net model, the --input_file and "
    "--responses_file parameters must be given.  The --lambda1 --lambda2, and "
    "--use_cholesky arguments control the training parameters.  A trained model"
    " can be saved with the --output_model_file, or, if training is not desired"
    " at all, a model can be loaded with --input_model_file.  Any output "
    "predictions from a test file can be saved into the file specified by the "
    "--output_predictions option.");

PARAM_STRING("input_file", "File containing covariates (X).", "i", "");
PARAM_STRING("responses_file", "File containing y (responses/observations).",
    "r", "");

PARAM_STRING("input_model_file", "File to load model from.", "m", "");
PARAM_STRING("output_model_file", "File to save model to.", "M", "");

PARAM_STRING("test_file", "File containing points to regress on (test points).",
    "t", "");
PARAM_STRING("output_predictions", "If --test_file is specified, this file is "
    "where the predicted responses will be saved.", "o", "predictions.csv");

PARAM_DOUBLE("lambda1", "Regularization parameter for l1-norm penalty.", "l",
    0);
PARAM_DOUBLE("lambda2", "Regularization parameter for l2-norm penalty.", "L",
    0);
PARAM_FLAG("use_cholesky", "Use Cholesky decomposition during computation "
    "rather than explicitly computing the full Gram matrix.", "c");

using namespace arma;
using namespace std;
using namespace mlpack;
using namespace mlpack::regression;

int main(int argc, char* argv[])
{
  // Handle parameters,
  CLI::ParseCommandLine(argc, argv);

  double lambda1 = CLI::GetParam<double>("lambda1");
  double lambda2 = CLI::GetParam<double>("lambda2");
  bool useCholesky = CLI::HasParam("use_cholesky");

  // Check parameters -- make sure everything given makes sense.
  if (CLI::HasParam("input_file") && !CLI::HasParam("responses_file"))
    Log::Fatal << "--input_file (-i) is specified, but --responses_file (-r) is"
        << " not!" << endl;

  if (CLI::HasParam("responses_file") && !CLI::HasParam("input_file"))
    Log::Fatal << "--responses_file (-r) is specified, but --input_file (-i) is"
        << " not!" << endl;

  if (!CLI::HasParam("input_file") && !CLI::HasParam("input_model_file"))
    Log::Fatal << "No input data specified (with --input_file (-i) and "
        << "--responses_file (-r)), and no input model specified (with "
        << "--input_model_file (-m))!" << endl;

  if (CLI::HasParam("input_file") && CLI::HasParam("input_model_file"))
    Log::Fatal << "Both --input_file (-i) and --input_model_file (-m) are "
        << "specified, but only one may be specified!" << endl;

  if (!CLI::HasParam("output_predictions") &&
      !CLI::HasParam("output_model_file"))
    Log::Warn << "--output_predictions (-o) and --output_model_file (-M) are "
        << "not specified; no results will be saved!" << endl;

  if (CLI::HasParam("output_predictions") && !CLI::HasParam("test_file"))
    Log::Warn << "--output_predictions (-o) specified, but --test_file (-t) is "
        << "not; no results will be saved." << endl;

  // Initialize the object.
  LARS lars(useCholesky, lambda1, lambda2);

  if (CLI::HasParam("input_file"))
  {
    // Load covariates.  We can avoid LARS transposing our data by choosing to
    // not transpose this data.
    const string matXFilename = CLI::GetParam<string>("input_file");
    mat matX;
    data::Load(matXFilename, matX, true, false);

    // Load responses.  The responses should be a one-dimensional vector, and it
    // seems more likely that these will be stored with one response per line
    // (one per row).  So we should not transpose upon loading.
    const string yFilename = CLI::GetParam<string>("responses_file");
    mat matY; // Will be a vector.
    data::Load(yFilename, matY, true, false);

    // Make sure y is oriented the right way.
    if (matY.n_rows == 1)
      matY = trans(matY);
    if (matY.n_cols > 1)
      Log::Fatal << "Only one column or row allowed in responses file!" << endl;

    if (matY.n_elem != matX.n_rows)
      Log::Fatal << "Number of responses must be equal to number of rows of X!"
          << endl;

    vec beta;
    lars.Train(matX, matY.unsafe_col(0), beta, false /* do not transpose */);
  }
  else // We must have --input_model_file.
  {
    const string modelFile = CLI::GetParam<string>("input_model_file");
    data::Load(modelFile, "lars_model", lars, true);
  }

  if (CLI::HasParam("test_file"))
  {
    Log::Info << "Regressing on test points." << endl;
    const string testFile = CLI::GetParam<string>("test_file");
    const string outputPredictionsFile =
        CLI::GetParam<string>("output_predictions");

    // Load test points.
    mat testPoints;
    data::Load(testFile, testPoints, true, false);

    // Make sure the dimensionality is right.  We haven't transposed, so, we
    // check n_cols not n_rows.
    if (testPoints.n_cols != lars.BetaPath().back().n_elem)
      Log::Fatal << "Dimensionality of test set (" << testPoints.n_cols << ") "
          << "is not equal to the dimensionality of the model ("
          << lars.BetaPath().back().n_elem << ")!" << endl;

    arma::vec predictions;
    lars.Predict(testPoints.t(), predictions, false);

    // Save test predictions.  One per line, so, don't transpose on save.
    data::Save(outputPredictionsFile, predictions, true, false);
  }

  if (CLI::HasParam("output_model_file"))
  {
    const string outputModelFile = CLI::GetParam<string>("output_model_file");
    data::Save(outputModelFile, "lars_model", lars, true);
  }
}


text:
Hi!

This is our dinner at [@CodeDay](https://twitter.com/CodeDay) Boulder.

codeday-boulder-food is a repository created for the sole purpose of making a
food list. Food ordering is outdated and needs to be updated. We really enjoy
presenting to you, codeday-boulder-food but remember no dolphin meat! We all
enjoy dolphin meat! However, dolphins are becoming endangered. We really enjoy
that you're reading our readme. We need food and really enjoy recieving it.
We're going to a place that sounds illegal but isn't. We'd really appreciate it
if you'd donate for food at this dogecoin address:
DNHuKD4gvczTEs2ajT5MKCrSXX7RLbsrPZ food is quite delicious and if you can't use
github you don't get food. We'll make sure you die if you can't use github, and
you don't get dinner. Dinner was created in 1846. It was discovered by Louis
Armstrong. Louis Armstrong was different than Lance Armstrong, though the both
probably enjoyed music. Lance Armstrong admitted to drug usage. He inspired us
and made us sad. El endo.

## Usage

Prerequisites:

* Python
* Go
* Haskell
* GCC
* G++
* Node
* [LOLCODE](https://github.com/justinmeza/lci)
* [Brainfuck](https://github.com/shurizzle/brainfuck)

Once you have all of those:

    $ ./dinner.bash

## Contributing Guidlines

Add your orders in the same format that all previous orders are in.

**Bon appetite.**
**Made with ♥ by CodeDay Boulder hackers.**


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</sem:predicate>
    <sem:object datatype="sem:iri">http://www.w3.org/2004/02/skos/core#Concept</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">Murmur</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.lds.org/core#partOfSpeech</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">verb</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/gs/murmur</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#definition</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">To grumble and complain against God's purposes, plans, or servants.</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/triple-index/murmur?lang=eng</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/rebellion</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/contention</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/guide-to-the-scriptures</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/murmur</sem:subject>
    <sem:predicate>http://www.lds.org/core#relCount</sem:predicate>
    <sem:object datatype="xsd:integer">2</sem:object>
  </sem:triple>
</sem:triples>


text:
/*global define */
/*
 | Copyright 2014 Esri
 |
 | Licensed under the Apache License, Version 2.0 (the "License");
 | you may not use this file except in compliance with the License.
 | You may obtain a copy of the License at
 |
 |    http://www.apache.org/licenses/LICENSE-2.0
 |
 | Unless required by applicable law or agreed to in writing, software
 | distributed under the License is distributed on an "AS IS" BASIS,
 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | See the License for the specific language governing permissions and
 | limitations under the License.
 */
define({
  "map": {
    "error": "Nelze vytvořit mapu"
  },
  "tools": {
    "info": {
      "label": "Informace",
      "tooltip": "Přepnout informace o mapě"
    },
    "sync": {
      "label": "Synchronizovat rozsah mapy",
      "tooltip": "Synchronizovat zobrazení na rozsah této mapy"
    }
  }
});


text:
package com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.OutDegree;

import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.ICriterium;
import com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.ICriteriumCreator;

/**
 * Factory class for Outdegree creators.
 */
public final class COutdegreeCriteriumCreator implements ICriteriumCreator {
  @Override
  public ICriterium createCriterium() {
    return new COutdegreeCriterium();
  }

  @Override
  public String getCriteriumDescription() {
    return "Select Nodes by Outdegree";
  }
}


text:
DomCrawler Component
====================

The DomCrawler component eases DOM navigation for HTML and XML documents.

Resources
---------

  * [Documentation](https://symfony.com/doc/current/components/dom_crawler.html)
  * [Contributing](https://symfony.com/doc/current/contributing/index.html)
  * [Report issues](https://github.com/symfony/symfony/issues) and
    [send Pull Requests](https://github.com/symfony/symfony/pulls)
    in the [main Symfony repository](https://github.com/symfony/symfony)


text:
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#ifndef ATOM_VERSION_H
#define ATOM_VERSION_H

#define ATOM_MAJOR_VERSION 0
#define ATOM_MINOR_VERSION 32
#define ATOM_PATCH_VERSION 3

#define ATOM_VERSION_IS_RELEASE 1

#ifndef ATOM_TAG
# define ATOM_TAG ""
#endif

#ifndef ATOM_STRINGIFY
#define ATOM_STRINGIFY(n) ATOM_STRINGIFY_HELPER(n)
#define ATOM_STRINGIFY_HELPER(n) #n
#endif

#if ATOM_VERSION_IS_RELEASE
# define ATOM_VERSION_STRING  ATOM_STRINGIFY(ATOM_MAJOR_VERSION) "." \
                              ATOM_STRINGIFY(ATOM_MINOR_VERSION) "." \
                              ATOM_STRINGIFY(ATOM_PATCH_VERSION)     \
                              ATOM_TAG
#else
# define ATOM_VERSION_STRING  ATOM_STRINGIFY(ATOM_MAJOR_VERSION) "." \
                              ATOM_STRINGIFY(ATOM_MINOR_VERSION) "." \
                              ATOM_STRINGIFY(ATOM_PATCH_VERSION)     \
                              ATOM_TAG "-pre"
#endif

#define ATOM_VERSION "v" ATOM_VERSION_STRING

#define ATOM_VERSION_AT_LEAST(major, minor, patch) \
  (( (major) < ATOM_MAJOR_VERSION) \
  || ((major) == ATOM_MAJOR_VERSION && (minor) < ATOM_MINOR_VERSION) \
  || ((major) == ATOM_MAJOR_VERSION && (minor) == ATOM_MINOR_VERSION && (patch) <= ATOM_PATCH_VERSION))

#endif /* ATOM_VERSION_H */


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Philipp. J. Sci. , C, Bot. 8: (1913)

#### Original name
Calopeziza mirabilis Syd. & P. Syd., 1913

### Remarks
null


text:
$pkg_name = "test-probe"
$pkg_origin = "habitat-testing"
$pkg_version = "0.1.0"
$pkg_maintainer = "The Habitat Maintainers <humans@habitat.sh>"
$pkg_license = @("Apache-2.0")
$pkg_bin_dirs = @("bin")
$pkg_deps=@(
    "core/visual-cpp-redist-2015"
)
$pkg_build_deps = @(
    "core/rust",
    "core/visual-cpp-build-tools-2015"
)

$pkg_binds_optional = @{
    thing_with_a_port = "port"
}

function Invoke-Prepare {
    $env:CARGO_TARGET_DIR = Join-Path -Path "$HAB_CACHE_SRC_PATH" -ChildPath "$pkg_dirname"
    Write-BuildLine "Setting env:CARGO_TARGET_DIR=$env:CARGO_TARGET_DIR"
}

function Invoke-Build {
    Push-Location "$PLAN_CONTEXT"
    try {
        cargo build --verbose
        if($LASTEXITCODE -ne 0) {
            Write-Error "Cargo build failed!"
        }
    } finally { Pop-Location }
}

function Invoke-Install {
    Copy-Item "$env:CARGO_TARGET_DIR/debug/test-probe.exe" "$pkg_prefix/bin/test-probe.exe"
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<atlassian-plugin key="${project.groupId}.${project.artifactId}" name="${project.name}" plugins-version="2">
  <plugin-info>
    <description>${project.description}</description>
    <version>${project.version}</version>
    <vendor name="${project.organization.name}" url="${project.organization.url}"/>
    <param name="plugin-icon">images/pluginIcon.png</param>
    <param name="plugin-logo">images/pluginLogo.png</param>
  </plugin-info>
  <!-- add our i18n resource -->
  <resource type="i18n" name="i18n" location="togglplugin"/>
  <!-- add our web resources -->
  <web-resource key="togglplugin-resources" name="togglplugin Web Resources">
    <dependency>com.atlassian.auiplugin:ajs</dependency>
    <resource type="download" name="togglplugin.css" location="/css/togglplugin.css"/>
    <resource type="download" name="togglplugin.js" location="/js/togglplugin.js"/>
    <resource type="download" name="images/" location="/images"/>
    <context>togglplugin</context>
  </web-resource>
  <!-- import from the product container -->
  <component-import key="applicationProperties" interface="com.atlassian.sal.api.ApplicationProperties"/>
  <web-panel name="Toggl" i18n-name-key="toggl.name" key="toggl" location="atl.jira.view.issue.right.context" weight="1000">
    <label>Toggl</label>
    <description key="toggl.description">The Toggl Plugin</description>
    <context-provider class="org.stone.jira.plugin.TogglPlugin"/>
    <resource name="view" type="velocity" location="togglPlugin.vm"/>
  </web-panel>
  <rest name="Toggl API Wrapper" i18n-name-key="toggl-api-wrapper.name" key="toggl-api-wrapper" path="/toggl" version="1.0">
    <description key="toggl-api-wrapper.description">The Toggl API Wrapper Plugin</description>
  </rest>
</atlassian-plugin>


text:
package com.google.cloud.pubsub.v1;

import com.google.api.core.ApiClock;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.api.core.InternalApi;
import com.google.api.core.SettableApiFuture;
import com.google.api.gax.batching.FlowController;
import com.google.api.gax.batching.FlowController.FlowControlException;
import com.google.api.gax.core.Distribution;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.ReceivedMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.threeten.bp.Duration;
import org.threeten.bp.Instant;
import org.threeten.bp.temporal.ChronoUnit;

/**
 * Dispatches messages to a message receiver while handling the messages acking and lease
 * extensions.
 */
class MessageDispatcher {
  private static final Logger logger = Logger.getLogger(MessageDispatcher.class.getName());

  @InternalApi static final double PERCENTILE_FOR_ACK_DEADLINE_UPDATES = 99.9;
  @InternalApi static final Duration PENDING_ACKS_SEND_DELAY = Duration.ofMillis(100);

  private final Executor executor;
  private final SequentialExecutorService.AutoExecutor sequentialExecutor;
  private final ScheduledExecutorService systemExecutor;
  private final ApiClock clock;

  private final Duration ackExpirationPadding;
  private final Duration maxAckExtensionPeriod;
  private int minDurationPerAckExtensionSeconds;
  private final boolean minDurationPerAckExtensionDefaultUsed;
  private final int maxDurationPerAckExtensionSeconds;
  private final boolean maxDurationPerAckExtensionDefaultUsed;

  // Only one of receiver or receiverWithAckResponse will be set
  private MessageReceiver receiver;
  private MessageReceiverWithAckResponse receiverWithAckResponse;

  private final AckProcessor ackProcessor;

  private final FlowController flowController;

  private AtomicBoolean exactlyOnceDeliveryEnabled = new AtomicBoolean(false);

  private final Waiter messagesWaiter;

  // Maps ID to "total expiration time". If it takes longer than this, stop extending.
  private final ConcurrentMap<String, AckHandler> pendingMessages = new ConcurrentHashMap<>();

  private final LinkedBlockingQueue<AckRequestData> pendingAcks = new LinkedBlockingQueue<>();
  private final LinkedBlockingQueue<AckRequestData> pendingNacks = new LinkedBlockingQueue<>();
  private final LinkedBlockingQueue<AckRequestData> pendingReceipts = new LinkedBlockingQueue<>();

  private final AtomicInteger messageDeadlineSeconds = new AtomicInteger();
  private final AtomicBoolean extendDeadline = new AtomicBoolean(true);
  private final Lock jobLock;
  private ScheduledFuture<?> backgroundJob;
  private ScheduledFuture<?> setExtendedDeadlineFuture;

  // To keep track of number of seconds the receiver takes to process messages.
  private final Distribution ackLatencyDistribution;

  /** Internal representation of a reply to a Pubsub message, to be sent back to the service. */
  public enum AckReply {
    ACK,
    NACK
  }

  /** Handles callbacks for acking/nacking messages from the {@link MessageReceiver}. */
  private class AckHandler implements ApiFutureCallback<AckReply> {
    private final AckRequestData ackRequestData;
    private final int outstandingBytes;
    private final long receivedTimeMillis;
    private final Instant totalExpiration;

    private AckHandler(
        AckRequestData ackRequestData, int outstandingBytes, Instant totalExpiration) {
      this.ackRequestData = ackRequestData;
      this.outstandingBytes = outstandingBytes;
      this.receivedTimeMillis = clock.millisTime();
      this.totalExpiration = totalExpiration;
    }

    public AckRequestData getAckRequestData() {
      return ackRequestData;
    }

    public SettableApiFuture<AckResponse> getMessageFutureIfExists() {
      return this.ackRequestData.getMessageFutureIfExists();
    }

    /** Stop extending deadlines for this message and free flow control. */
    private void forget() {
      if (pendingMessages.remove(this.ackRequestData.getAckId()) == null) {
        /*
         * We're forgetting the message for the second time. Probably because we ran out of total
         * expiration, forget the message, then the user finishes working on the message, and forget
         * again. Turn the second forget into a no-op so we don't free twice.
         */
        return;
      }
      flowController.release(1, outstandingBytes);
      messagesWaiter.incrementPendingCount(-1);
    }

    @Override
    public void onFailure(Throwable t) {
      logger.log(
          Level.WARNING,
          "MessageReceiver failed to process ack ID: "
              + this.ackRequestData.getAckId()
              + ", the message will be nacked.",
          t);
      this.ackRequestData.setResponse(AckResponse.OTHER, false);
      pendingNacks.add(this.ackRequestData);
      forget();
    }

    @Override
    public void onSuccess(AckReply reply) {
      switch (reply) {
        case ACK:
          pendingAcks.add(this.ackRequestData);
          // Record the latency rounded to the next closest integer.
          ackLatencyDistribution.record(
              Ints.saturatedCast(
                  (long) Math.ceil((clock.millisTime() - receivedTimeMillis) / 1000D)));
          break;
        case NACK:
          pendingNacks.add(this.ackRequestData);
          break;
        default:
          throw new IllegalArgumentException(String.format("AckReply: %s not supported", reply));
      }
      forget();
    }
  }

  interface AckProcessor {
    public void sendAckOperations(List<AckRequestData> ackRequestDataList);

    public void sendModackOperations(List<ModackRequestData> modackRequestDataList);
  }

  private MessageDispatcher(Builder builder) {
    executor = builder.executor;
    systemExecutor = builder.systemExecutor;
    ackExpirationPadding = builder.ackExpirationPadding;
    maxAckExtensionPeriod = builder.maxAckExtensionPeriod;

    minDurationPerAckExtensionSeconds =
        Math.toIntExact(builder.minDurationPerAckExtension.getSeconds());
    minDurationPerAckExtensionDefaultUsed = builder.minDurationPerAckExtensionDefaultUsed;
    maxDurationPerAckExtensionSeconds =
        Math.toIntExact(builder.maxDurationPerAckExtension.getSeconds());
    maxDurationPerAckExtensionDefaultUsed = builder.maxDurationPerAckExtensionDefaultUsed;

    // Start the deadline at the minimum ack deadline so messages which arrive before this is
    // updated will not have a long ack deadline.
    if (minDurationPerAckExtensionDefaultUsed) {
      messageDeadlineSeconds.set(Math.toIntExact(Subscriber.MIN_STREAM_ACK_DEADLINE.getSeconds()));
    } else {
      messageDeadlineSeconds.set(minDurationPerAckExtensionSeconds);
    }

    receiver = builder.receiver;
    receiverWithAckResponse = builder.receiverWithAckResponse;

    ackProcessor = builder.ackProcessor;
    flowController = builder.flowController;
    ackLatencyDistribution = builder.ackLatencyDistribution;
    clock = builder.clock;
    jobLock = new ReentrantLock();
    messagesWaiter = new Waiter();
    sequentialExecutor = new SequentialExecutorService.AutoExecutor(builder.executor);
  }

  private boolean shouldSetMessageFuture() {
    return receiverWithAckResponse != null;
  }

  void start() {
    final Runnable setExtendDeadline =
        new Runnable() {
          @Override
          public void run() {
            extendDeadline.set(true);
          }
        };

    jobLock.lock();
    try {
      // Do not adjust deadline concurrently with extendDeadline or processOutstandingAckOperations.
      // The following sequence can happen:
      //  0. Initially, deadline = 1 min
      //  1. Thread A (TA) wants to send receipts, reads deadline = 1m, but stalls before actually
      // sending request
      //  2. Thread B (TB) adjusts deadline to 2m
      //  3. TB calls extendDeadline, modack all messages to 2m, schedules next extension in 2m
      //  4. TA sends request, modacking messages to 1m.
      // Then messages will expire too early.
      // This can be resolved by adding locks in the right places, but at that point,
      // we might as well do things sequentially.
      backgroundJob =
          systemExecutor.scheduleWithFixedDelay(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    if (extendDeadline.getAndSet(false)) {
                      int newDeadlineSec = computeDeadlineSeconds();
                      messageDeadlineSeconds.set(newDeadlineSec);
                      extendDeadlines();
                      if (setExtendedDeadlineFuture != null && !backgroundJob.isDone()) {
                        setExtendedDeadlineFuture.cancel(true);
                      }

                      setExtendedDeadlineFuture =
                          systemExecutor.schedule(
                              setExtendDeadline,
                              newDeadlineSec - ackExpirationPadding.getSeconds(),
                              TimeUnit.SECONDS);
                    }
                    processOutstandingOperations();
                  } catch (Throwable t) {
                    // Catch everything so that one run failing doesn't prevent subsequent runs.
                    logger.log(Level.WARNING, "failed to run periodic job", t);
                  }
                }
              },
              PENDING_ACKS_SEND_DELAY.toMillis(),
              PENDING_ACKS_SEND_DELAY.toMillis(),
              TimeUnit.MILLISECONDS);
    } finally {
      jobLock.unlock();
    }
  }

  void stop() {
    messagesWaiter.waitComplete();
    jobLock.lock();
    try {
      if (backgroundJob != null) {
        backgroundJob.cancel(false);
      }
      if (setExtendedDeadlineFuture != null) {
        setExtendedDeadlineFuture.cancel(true);
      }
      backgroundJob = null;
      setExtendedDeadlineFuture = null;
    } finally {
      jobLock.unlock();
    }
    processOutstandingOperations();
  }

  @InternalApi
  void setMessageDeadlineSeconds(int sec) {
    messageDeadlineSeconds.set(sec);
  }

  @InternalApi
  int getMessageDeadlineSeconds() {
    return messageDeadlineSeconds.get();
  }

  @InternalApi
  void setExactlyOnceDeliveryEnabled(boolean exactlyOnceDeliveryEnabled) {
    // Sanity check that we are changing the exactlyOnceDeliveryEnabled state
    if (exactlyOnceDeliveryEnabled == this.exactlyOnceDeliveryEnabled.get()) {
      return;
    }

    this.exactlyOnceDeliveryEnabled.set(exactlyOnceDeliveryEnabled);

    // If a custom value for minDurationPerAckExtension, we should respect that
    if (!minDurationPerAckExtensionDefaultUsed) {
      return;
    }

    // We just need to update the minDurationPerAckExtensionSeconds as the
    // maxDurationPerAckExtensionSeconds does not change
    int possibleNewMinAckDeadlineExtensionSeconds;

    if (exactlyOnceDeliveryEnabled) {
      possibleNewMinAckDeadlineExtensionSeconds =
          Math.toIntExact(
              Subscriber.DEFAULT_MIN_ACK_DEADLINE_EXTENSION_EXACTLY_ONCE_DELIVERY.getSeconds());
    } else {
      possibleNewMinAckDeadlineExtensionSeconds =
          Math.toIntExact(Subscriber.DEFAULT_MIN_ACK_DEADLINE_EXTENSION.getSeconds());
    }

    // If we are not using the default maxDurationAckExtension, check if the
    // minAckDeadlineExtensionExactlyOnceDelivery needs to be bounded by the set max
    if (!maxDurationPerAckExtensionDefaultUsed
        && (possibleNewMinAckDeadlineExtensionSeconds > maxDurationPerAckExtensionSeconds)) {
      minDurationPerAckExtensionSeconds = maxDurationPerAckExtensionSeconds;
    } else {
      minDurationPerAckExtensionSeconds = possibleNewMinAckDeadlineExtensionSeconds;
    }
  }

  private static class OutstandingMessage {
    private final ReceivedMessage receivedMessage;
    private final AckHandler ackHandler;

    private OutstandingMessage(ReceivedMessage receivedMessage, AckHandler ackHandler) {
      this.receivedMessage = receivedMessage;
      this.ackHandler = ackHandler;
    }
  }

  void processReceivedMessages(List<ReceivedMessage> messages) {
    Instant totalExpiration = now().plus(maxAckExtensionPeriod);
    List<OutstandingMessage> outstandingBatch = new ArrayList<>(messages.size());
    for (ReceivedMessage message : messages) {
      AckRequestData.Builder builder = AckRequestData.newBuilder(message.getAckId());
      if (shouldSetMessageFuture()) {
        builder.setMessageFuture(SettableApiFuture.create());
      }
      AckRequestData ackRequestData = builder.build();
      AckHandler ackHandler =
          new AckHandler(ackRequestData, message.getMessage().getSerializedSize(), totalExpiration);
      if (pendingMessages.putIfAbsent(message.getAckId(), ackHandler) != null) {
        // putIfAbsent puts ackHandler if ackID isn't previously mapped, then return the
        // previously-mapped element.
        // If the previous element is not null, we already have the message and the new one is
        // definitely a duplicate.
        // Don't nack this, because that'd also nack the one we already have in queue.
        // Don't update the existing one's total expiration either. If the user "loses" the message,
        // we want to eventually
        // totally expire so that pubsub service sends us the message again.
        continue;
      }
      outstandingBatch.add(new OutstandingMessage(message, ackHandler));
      pendingReceipts.add(ackRequestData);
    }

    processBatch(outstandingBatch);
  }

  private void processBatch(List<OutstandingMessage> batch) {
    messagesWaiter.incrementPendingCount(batch.size());
    for (OutstandingMessage message : batch) {
      // This is a blocking flow controller.  We have already incremented messagesWaiter, so
      // shutdown will block on processing of all these messages anyway.
      try {
        flowController.reserve(1, message.receivedMessage.getMessage().getSerializedSize());
      } catch (FlowControlException unexpectedException) {
        // This should be a blocking flow controller and never throw an exception.
        throw new IllegalStateException("Flow control unexpected exception", unexpectedException);
      }
      processOutstandingMessage(addDeliveryInfoCount(message.receivedMessage), message.ackHandler);
    }
  }

  private PubsubMessage addDeliveryInfoCount(ReceivedMessage receivedMessage) {
    PubsubMessage originalMessage = receivedMessage.getMessage();
    int deliveryAttempt = receivedMessage.getDeliveryAttempt();
    // Delivery Attempt will be set to 0 if DeadLetterPolicy is not set on the subscription. In
    // this case, do not populate the PubsubMessage with the delivery attempt attribute.
    if (deliveryAttempt > 0) {
      return PubsubMessage.newBuilder(originalMessage)
          .putAttributes("googclient_deliveryattempt", Integer.toString(deliveryAttempt))
          .build();
    }
    return originalMessage;
  }

  private void processOutstandingMessage(final PubsubMessage message, final AckHandler ackHandler) {
    // This future is for internal bookkeeping to be sent to the StreamingSubscriberConnection
    // use below in the consumers
    SettableApiFuture<AckReply> ackReplySettableApiFuture = SettableApiFuture.create();
    ApiFutures.addCallback(ackReplySettableApiFuture, ackHandler, MoreExecutors.directExecutor());

    Runnable deliverMessageTask =
        new Runnable() {
          @Override
          public void run() {
            try {
              if (ackHandler
                  .totalExpiration
                  .plusSeconds(messageDeadlineSeconds.get())
                  .isBefore(now())) {
                // Message expired while waiting. We don't extend these messages anymore,
                // so it was probably sent to someone else. Don't work on it.
                // Don't nack it either, because we'd be nacking someone else's message.
                ackHandler.forget();
                return;
              }
              if (shouldSetMessageFuture()) {
                // This is the message future that is propagated to the user
                SettableApiFuture<AckResponse> messageFuture =
                    ackHandler.getMessageFutureIfExists();
                final AckReplyConsumerWithResponse ackReplyConsumerWithResponse =
                    new AckReplyConsumerWithResponseImpl(ackReplySettableApiFuture, messageFuture);
                receiverWithAckResponse.receiveMessage(message, ackReplyConsumerWithResponse);
              } else {
                final AckReplyConsumer ackReplyConsumer =
                    new AckReplyConsumerImpl(ackReplySettableApiFuture);
                receiver.receiveMessage(message, ackReplyConsumer);
              }
            } catch (Exception e) {
              ackReplySettableApiFuture.setException(e);
            }
          }
        };
    if (message.getOrderingKey().isEmpty()) {
      executor.execute(deliverMessageTask);
    } else {
      sequentialExecutor.submit(message.getOrderingKey(), deliverMessageTask);
    }
  }

  /** Compute the ideal deadline, set subsequent modacks to this deadline, and return it. */
  @InternalApi
  int computeDeadlineSeconds() {
    int deadlineSeconds = ackLatencyDistribution.getPercentile(PERCENTILE_FOR_ACK_DEADLINE_UPDATES);

    // Bound deadlineSeconds by extensions
    if (!maxDurationPerAckExtensionDefaultUsed
        && (deadlineSeconds > maxDurationPerAckExtensionSeconds)) {
      deadlineSeconds = maxDurationPerAckExtensionSeconds;
    } else if (deadlineSeconds < minDurationPerAckExtensionSeconds) {
      deadlineSeconds = minDurationPerAckExtensionSeconds;
    }

    // Bound deadlineSeconds by hard limits in subscriber
    if (deadlineSeconds < Subscriber.MIN_STREAM_ACK_DEADLINE.getSeconds()) {
      deadlineSeconds = Math.toIntExact(Subscriber.MIN_STREAM_ACK_DEADLINE.getSeconds());
    } else if (deadlineSeconds > Subscriber.MAX_STREAM_ACK_DEADLINE.getSeconds()) {
      deadlineSeconds = Math.toIntExact(Subscriber.MAX_STREAM_ACK_DEADLINE.getSeconds());
    }

    return deadlineSeconds;
  }

  @InternalApi
  void extendDeadlines() {
    int extendSeconds = getMessageDeadlineSeconds();
    int numAckIdToSend = 0;
    Map<Integer, ModackRequestData> deadlineExtensionModacks =
        new HashMap<Integer, ModackRequestData>();
    Instant now = now();
    Instant extendTo = now.plusSeconds(extendSeconds);

    for (Map.Entry<String, AckHandler> entry : pendingMessages.entrySet()) {
      String ackId = entry.getKey();
      Instant totalExpiration = entry.getValue().totalExpiration;
      if (totalExpiration.isAfter(extendTo)) {
        ModackRequestData modackRequestData =
            deadlineExtensionModacks.computeIfAbsent(
                extendSeconds,
                deadlineExtensionSeconds -> new ModackRequestData(deadlineExtensionSeconds));
        modackRequestData.addAckRequestData(entry.getValue().getAckRequestData());
        numAckIdToSend++;
        continue;
      }

      // forget removes from pendingMessages; this is OK, concurrent maps can
      // handle concurrent iterations and modifications.
      entry.getValue().forget();
      if (totalExpiration.isAfter(now)) {
        int sec = Math.max(1, (int) now.until(totalExpiration, ChronoUnit.SECONDS));
        ModackRequestData modackRequestData =
            deadlineExtensionModacks.computeIfAbsent(
                sec, extensionSeconds -> new ModackRequestData(extensionSeconds));
        modackRequestData.addAckRequestData(entry.getValue().getAckRequestData());
        numAckIdToSend++;
      }
    }

    if (numAckIdToSend > 0) {
      logger.log(Level.FINER, "Sending {0} modacks", numAckIdToSend);
      ackProcessor.sendModackOperations(
          new ArrayList<ModackRequestData>(deadlineExtensionModacks.values()));
    }
  }

  @InternalApi
  void processOutstandingOperations() {
    List<ModackRequestData> modackRequestData = new ArrayList<ModackRequestData>();

    // Nacks are modacks with an expiration of 0
    List<AckRequestData> nackRequestDataList = new ArrayList<AckRequestData>();
    pendingNacks.drainTo(nackRequestDataList);

    if (!nackRequestDataList.isEmpty()) {
      modackRequestData.add(new ModackRequestData(0, nackRequestDataList));
    }
    logger.log(Level.FINER, "Sending {0} nacks", nackRequestDataList.size());

    List<AckRequestData> ackRequestDataReceipts = new ArrayList<AckRequestData>();
    pendingReceipts.drainTo(ackRequestDataReceipts);
    if (!ackRequestDataReceipts.isEmpty()) {
      modackRequestData.add(
          new ModackRequestData(this.getMessageDeadlineSeconds(), ackRequestDataReceipts));
    }
    logger.log(Level.FINER, "Sending {0} receipts", ackRequestDataReceipts.size());

    ackProcessor.sendModackOperations(modackRequestData);

    List<AckRequestData> ackRequestDataList = new ArrayList<AckRequestData>();
    pendingAcks.drainTo(ackRequestDataList);
    logger.log(Level.FINER, "Sending {0} acks", ackRequestDataList.size());

    ackProcessor.sendAckOperations(ackRequestDataList);
  }

  private Instant now() {
    return Instant.ofEpochMilli(clock.millisTime());
  }

  /** Builder of {@link MessageDispatcher MessageDispatchers}. */
  public static final class Builder {
    private MessageReceiver receiver;
    private MessageReceiverWithAckResponse receiverWithAckResponse;

    private AckProcessor ackProcessor;
    private Duration ackExpirationPadding;
    private Duration maxAckExtensionPeriod;
    private Duration minDurationPerAckExtension;
    private boolean minDurationPerAckExtensionDefaultUsed;
    private Duration maxDurationPerAckExtension;
    private boolean maxDurationPerAckExtensionDefaultUsed;

    private Distribution ackLatencyDistribution;
    private FlowController flowController;

    private Executor executor;
    private ScheduledExecutorService systemExecutor;
    private ApiClock clock;

    protected Builder(MessageReceiver receiver) {
      this.receiver = receiver;
    }

    protected Builder(MessageReceiverWithAckResponse receiverWithAckResponse) {
      this.receiverWithAckResponse = receiverWithAckResponse;
    }

    public Builder setAckProcessor(AckProcessor ackProcessor) {
      this.ackProcessor = ackProcessor;
      return this;
    }

    public Builder setAckExpirationPadding(Duration ackExpirationPadding) {
      this.ackExpirationPadding = ackExpirationPadding;
      return this;
    }

    public Builder setMaxAckExtensionPeriod(Duration maxAckExtensionPeriod) {
      this.maxAckExtensionPeriod = maxAckExtensionPeriod;
      return this;
    }

    public Builder setMinDurationPerAckExtension(Duration minDurationPerAckExtension) {
      this.minDurationPerAckExtension = minDurationPerAckExtension;
      return this;
    }

    public Builder setMinDurationPerAckExtensionDefaultUsed(
        boolean minDurationPerAckExtensionDefaultUsed) {
      this.minDurationPerAckExtensionDefaultUsed = minDurationPerAckExtensionDefaultUsed;
      return this;
    }

    public Builder setMaxDurationPerAckExtension(Duration maxDurationPerAckExtension) {
      this.maxDurationPerAckExtension = maxDurationPerAckExtension;
      return this;
    }

    public Builder setMaxDurationPerAckExtensionDefaultUsed(
        boolean maxDurationPerAckExtensionDefaultUsed) {
      this.maxDurationPerAckExtensionDefaultUsed = maxDurationPerAckExtensionDefaultUsed;
      return this;
    }

    public Builder setAckLatencyDistribution(Distribution ackLatencyDistribution) {
      this.ackLatencyDistribution = ackLatencyDistribution;
      return this;
    }

    public Builder setFlowController(FlowController flowController) {
      this.flowController = flowController;
      return this;
    }

    public Builder setExecutor(Executor executor) {
      this.executor = executor;
      return this;
    }

    public Builder setSystemExecutor(ScheduledExecutorService systemExecutor) {
      this.systemExecutor = systemExecutor;
      return this;
    }

    public Builder setApiClock(ApiClock clock) {
      this.clock = clock;
      return this;
    }

    public MessageDispatcher build() {
      return new MessageDispatcher(this);
    }
  }

  public static Builder newBuilder(MessageReceiver receiver) {
    return new Builder(receiver);
  }

  public static Builder newBuilder(MessageReceiverWithAckResponse receiverWithAckResponse) {
    return new Builder(receiverWithAckResponse);
  }
}


text:
import * as React from 'react';
export interface IOverlay {
}
export interface IOverlayProps extends React.HTMLProps<HTMLElement> {
    /**
     * Optional callback to access the IOverlay interface. Use this instead of ref for accessing
     * the public methods and properties of the component.
     */
    componentRef?: (component: IOverlay) => void;
    /**
     * Whether to use the dark-themed overlay.
     * @defaultvalue false
     */
    isDarkThemed?: boolean;
}