text:
#include "lib.h"
#include "array.h"
#include "buffer.h"
#include "hash.h"
#include "nfs-workarounds.h"
#include "file-cache.h"
#include "mmap-util.h"
#include "read-full.h"
#include "write-full.h"
#include "mail-cache-private.h"

#include <unistd.h>

#define MAIL_CACHE_MIN_HEADER_READ_SIZE 4096

void mail_cache_set_syscall_error(struct mail_cache *cache,
				  const char *function)
{
	mail_index_file_set_syscall_error(cache->index, cache->filepath,
					  function);
}

static void mail_cache_unlink(struct mail_cache *cache)
{
	if (!cache->index->readonly)
		i_unlink(cache->filepath);
}

void mail_cache_reset(struct mail_cache *cache)
{
	mail_cache_unlink(cache);
	/* mark the cache as unusable */
	cache->hdr = NULL;
}

void mail_cache_set_corrupted(struct mail_cache *cache, const char *fmt, ...)
{
	va_list va;

	mail_cache_reset(cache);

	va_start(va, fmt);
	T_BEGIN {
		mail_index_set_error(cache->index,
				     "Corrupted index cache file %s: %s",
				     cache->filepath,
				     t_strdup_vprintf(fmt, va));
	} T_END;
	va_end(va);
}

void mail_cache_file_close(struct mail_cache *cache)
{
	if (cache->mmap_base != NULL) {
		if (munmap(cache->mmap_base, cache->mmap_length) < 0)
			mail_cache_set_syscall_error(cache, "munmap()");
	}

	if (cache->file_cache != NULL)
		file_cache_set_fd(cache->file_cache, -1);

	cache->mmap_base = NULL;
	cache->hdr = NULL;
	cache->mmap_length = 0;
	cache->last_field_header_offset = 0;

	if (cache->file_lock != NULL)
		file_lock_free(&cache->file_lock);
	cache->locked = FALSE;

	if (cache->fd != -1) {
		if (close(cache->fd) < 0)
			mail_cache_set_syscall_error(cache, "close()");
		cache->fd = -1;
	}
}

static void mail_cache_init_file_cache(struct mail_cache *cache)
{
	struct stat st;

	if (cache->file_cache != NULL)
		file_cache_set_fd(cache->file_cache, cache->fd);

	if (fstat(cache->fd, &st) == 0) {
		if (cache->file_cache != NULL)
			(void)file_cache_set_size(cache->file_cache, st.st_size);
	} else if (!ESTALE_FSTAT(errno)) {
		mail_cache_set_syscall_error(cache, "fstat()");
	}

	cache->st_ino = st.st_ino;
	cache->st_dev = st.st_dev;
}

static int mail_cache_try_open(struct mail_cache *cache)
{
	const void *data;

	cache->opened = TRUE;

	if (MAIL_INDEX_IS_IN_MEMORY(cache->index))
		return 0;

	cache->fd = nfs_safe_open(cache->filepath,
				  cache->index->readonly ? O_RDONLY : O_RDWR);
	if (cache->fd == -1) {
		if (errno == ENOENT) {
			cache->need_compress_file_seq = 0;
			return 0;
		}

		mail_cache_set_syscall_error(cache, "open()");
		return -1;
	}

	mail_cache_init_file_cache(cache);

	if (mail_cache_map(cache, 0, 0, &data) < 0)
		return -1;
	return 1;
}

static bool mail_cache_need_reopen(struct mail_cache *cache)
{
	struct stat st;

	if (MAIL_CACHE_IS_UNUSABLE(cache)) {
		if (cache->need_compress_file_seq != 0) {
			/* we're waiting for compression */
			return FALSE;
		}
		if (MAIL_INDEX_IS_IN_MEMORY(cache->index)) {
			/* disabled */
			return FALSE;
		}
	}

	if (cache->fd == -1)
		return TRUE;

	/* see if the file has changed */
	if ((cache->index->flags & MAIL_INDEX_OPEN_FLAG_NFS_FLUSH) != 0) {
		i_assert(!cache->locked);
		nfs_flush_file_handle_cache(cache->filepath);
	}
	if (nfs_safe_stat(cache->filepath, &st) < 0) {
		mail_cache_set_syscall_error(cache, "stat()");
		return TRUE;
	}

	if (st.st_ino != cache->st_ino ||
	    !CMP_DEV_T(st.st_dev, cache->st_dev)) {
		/* file changed */
		return TRUE;
	}

	if ((cache->index->flags & MAIL_INDEX_OPEN_FLAG_NFS_FLUSH) != 0) {
		/* if the old file has been deleted, the new file may have
		   the same inode as the old one. we'll catch this here by
		   checking if fstat() fails with ESTALE */
		if (fstat(cache->fd, &st) < 0) {
			if (ESTALE_FSTAT(errno))
				return TRUE;
			mail_cache_set_syscall_error(cache, "fstat()");
			return FALSE;
		}
	}
	return FALSE;
}

static int mail_cache_reopen_now(struct mail_cache *cache)
{
	struct mail_index_view *view;
	const struct mail_index_ext *ext;

	mail_cache_file_close(cache);

	if (mail_cache_try_open(cache) <= 0)
		return -1;

	if (mail_cache_header_fields_read(cache) < 0)
		return -1;

	view = mail_index_view_open(cache->index);
	ext = mail_index_view_get_ext(view, cache->ext_id);
	if (ext == NULL || cache->hdr->file_seq != ext->reset_id) {
		/* still different - maybe a race condition or maybe the
		   file_seq really is corrupted. either way, this shouldn't
		   happen often so we'll just mark cache to be compressed
		   later which fixes this. */
		cache->need_compress_file_seq = cache->hdr->file_seq;
		mail_index_view_close(&view);
		return 0;
	}

	mail_index_view_close(&view);
	i_assert(!MAIL_CACHE_IS_UNUSABLE(cache));
	return 1;
}

int mail_cache_reopen(struct mail_cache *cache)
{
	i_assert(!cache->locked);

	if (!mail_cache_need_reopen(cache)) {
		/* reopening does no good */
		return 0;
	}
	return mail_cache_reopen_now(cache);
}

static void mail_cache_update_need_compress(struct mail_cache *cache)
{
	const struct mail_cache_header *hdr = cache->hdr;
	struct stat st;
	unsigned int msg_count;
	unsigned int records_count, cont_percentage, delete_percentage;
	bool want_compress = FALSE;

	if (hdr->minor_version == 0) {
		/* compress to get ourself into the new header version */
		cache->need_compress_file_seq = hdr->file_seq;
		return;
	}

	msg_count = cache->index->map->rec_map->records_count;
	if (msg_count == 0)
		records_count = 1;
	else if (hdr->record_count == 0 || hdr->record_count > msg_count*2) {
		/* probably not the real record_count, but hole offset that
		   Dovecot <=v2.1 versions used to use in this position.
		   we already checked that minor_version>0, but this could
		   happen if old Dovecot was used to access mailbox after
		   it had been updated. */
		records_count = I_MAX(msg_count, 1);
		cache->hdr_copy.record_count = msg_count;
		cache->hdr_modified = TRUE;
	} else {
		records_count = hdr->record_count;
	}

	cont_percentage = hdr->continued_record_count * 100 / records_count;
	if (cont_percentage >= MAIL_CACHE_COMPRESS_CONTINUED_PERCENTAGE) {
		/* too many continued rows, compress */
		want_compress = TRUE;
	}

	delete_percentage = hdr->deleted_record_count * 100 /
		(records_count + hdr->deleted_record_count);
	if (delete_percentage >= MAIL_CACHE_COMPRESS_DELETE_PERCENTAGE) {
		/* too many deleted records, compress */
		want_compress = TRUE;
	}

	if (want_compress) {
		if (fstat(cache->fd, &st) < 0) {
			if (!ESTALE_FSTAT(errno))
				mail_cache_set_syscall_error(cache, "fstat()");
			return;
		}
		if (st.st_size >= MAIL_CACHE_COMPRESS_MIN_SIZE)
			cache->need_compress_file_seq = hdr->file_seq;
	}

}

static bool mail_cache_verify_header(struct mail_cache *cache,
				     const struct mail_cache_header *hdr)
{
	/* check that the header is still ok */
	if (cache->mmap_length < sizeof(struct mail_cache_header)) {
		mail_cache_set_corrupted(cache, "File too small");
		return FALSE;
	}

	if (hdr->major_version != MAIL_CACHE_MAJOR_VERSION) {
		/* version changed - upgrade silently */
		mail_cache_unlink(cache);
		return FALSE;
	}
	if (hdr->compat_sizeof_uoff_t != sizeof(uoff_t)) {
		/* architecture change - handle silently(?) */
		mail_cache_unlink(cache);
		return FALSE;
	}

	if (hdr->indexid != cache->index->indexid) {
		/* index id changed - handle silently */
		mail_cache_unlink(cache);
		return FALSE;
	}
	if (hdr->file_seq == 0) {
		mail_cache_set_corrupted(cache, "file_seq is 0");
		return FALSE;
	}
	return TRUE;
}

static int
mail_cache_map_finish(struct mail_cache *cache, uoff_t offset, size_t size,
		      const void *hdr_data, bool copy_hdr)
{
	const struct mail_cache_header *hdr = hdr_data;

	if (offset == 0) {
		/* verify the header validity only with offset=0. this way
		   we won't waste time re-verifying it all the time */
		if (!mail_cache_verify_header(cache, hdr)) {
			cache->need_compress_file_seq =
				!MAIL_CACHE_IS_UNUSABLE(cache) &&
				cache->hdr->file_seq != 0 ?
				cache->hdr->file_seq : 0;
			cache->hdr = NULL;
			return -1;
		}
	}
	if (hdr_data != NULL) {
		if (!copy_hdr)
			cache->hdr = hdr;
		else {
			memcpy(&cache->hdr_ro_copy, hdr,
			       sizeof(cache->hdr_ro_copy));
			cache->hdr = &cache->hdr_ro_copy;
		}
		mail_cache_update_need_compress(cache);
	} else {
		i_assert(cache->hdr != NULL);
	}
	i_assert(cache->hdr->file_seq != 0);

	if (offset + size > cache->mmap_length)
		return 0;
	return 1;
}

static int
mail_cache_map_with_read(struct mail_cache *cache, size_t offset, size_t size,
			 const void **data_r)
{
	const void *hdr_data;
	void *data;
	ssize_t ret;

	if (cache->read_buf == NULL) {
		cache->read_buf =
			buffer_create_dynamic(default_pool, size);
	} else if (cache->read_offset <= offset &&
		   cache->read_offset + cache->read_buf->used >= offset+size) {
		/* already mapped */
		*data_r = CONST_PTR_OFFSET(cache->read_buf->data,
					   offset - cache->read_offset);
		hdr_data = offset == 0 ? *data_r : NULL;
		return mail_cache_map_finish(cache, offset, size, hdr_data, TRUE);
	} else {
		buffer_set_used_size(cache->read_buf, 0);
	}
	if (offset == 0 && size < MAIL_CACHE_MIN_HEADER_READ_SIZE) {
		/* we can usually read the fields header after the cache
		   header. we need them both, so try to read them all with one
		   pread() call. */
		size = MAIL_CACHE_MIN_HEADER_READ_SIZE;
	}

	data = buffer_append_space_unsafe(cache->read_buf, size);
	ret = pread(cache->fd, data, size, offset);
	if (ret < 0) {
		if (errno != ESTALE)
			mail_cache_set_syscall_error(cache, "read()");

		buffer_set_used_size(cache->read_buf, 0);
		cache->hdr = NULL;
		cache->mmap_length = 0;
		return -1;
	}
	buffer_set_used_size(cache->read_buf, ret);

	cache->read_offset = offset;
	cache->mmap_length = offset + cache->read_buf->used;

	*data_r = data;
	hdr_data = offset == 0 ? *data_r : NULL;
	return mail_cache_map_finish(cache, offset,
				     cache->read_buf->used, hdr_data, TRUE);
}

int mail_cache_map(struct mail_cache *cache, size_t offset, size_t size,
		   const void **data_r)
{
	struct stat st;
	const void *data;
	ssize_t ret;

	if (size == 0)
		size = sizeof(struct mail_cache_header);

	/* verify offset + size before trying to allocate a huge amount of
	   memory due to them. note that we may be prefetching more than we
	   actually need, so don't fail too early. */
	if ((size > cache->mmap_length || offset + size > cache->mmap_length) &&
	    (offset > 0 || size > sizeof(struct mail_cache_header))) {
		if (fstat(cache->fd, &st) < 0) {
			i_error("fstat(%s) failed: %m", cache->filepath);
			return -1;
		}
		if (offset >= (uoff_t)st.st_size) {
			*data_r = NULL;
			return 0;
		}
		if (offset + size > (uoff_t)st.st_size)
			size = st.st_size - offset;
	}

	cache->remap_counter++;
	if (cache->map_with_read)
		return mail_cache_map_with_read(cache, offset, size, data_r);

	if (cache->file_cache != NULL) {
		ret = file_cache_read(cache->file_cache, offset, size);
		if (ret < 0) {
                        /* In case of ESTALE we'll simply fail without error
                           messages. The caller will then just have to
                           fallback to generating the value itself.

                           We can't simply reopen the cache flie, because
                           using it requires also having updated file
                           offsets. */
                        if (errno != ESTALE)
                                mail_cache_set_syscall_error(cache, "read()");
			cache->hdr = NULL;
			return -1;
		}

		data = file_cache_get_map(cache->file_cache,
					  &cache->mmap_length);
		*data_r = offset > cache->mmap_length ? NULL :
			CONST_PTR_OFFSET(data, offset);
		return mail_cache_map_finish(cache, offset, size,
					     offset == 0 ? data : NULL, TRUE);
	}

	if (offset < cache->mmap_length &&
	    size <= cache->mmap_length - offset) {
		/* already mapped */
		i_assert(cache->mmap_base != NULL);
		*data_r = CONST_PTR_OFFSET(cache->mmap_base, offset);
		return 1;
	}

	if (cache->mmap_base != NULL) {
		if (munmap(cache->mmap_base, cache->mmap_length) < 0)
			mail_cache_set_syscall_error(cache, "munmap()");
	} else {
		if (cache->fd == -1) {
			/* unusable, waiting for compression or
			   index is in memory */
			i_assert(cache->need_compress_file_seq != 0 ||
				 MAIL_INDEX_IS_IN_MEMORY(cache->index));
			return -1;
		}
	}

	/* map the whole file */
	cache->hdr = NULL;
	cache->mmap_length = 0;

	cache->mmap_base = mmap_ro_file(cache->fd, &cache->mmap_length);
	if (cache->mmap_base == MAP_FAILED) {
		cache->mmap_base = NULL;
		cache->mmap_length = 0;
		mail_cache_set_syscall_error(cache, "mmap()");
		return -1;
	}
	*data_r = offset > cache->mmap_length ? NULL :
		CONST_PTR_OFFSET(cache->mmap_base, offset);
	return mail_cache_map_finish(cache, offset, size,
				     cache->mmap_base, FALSE);
}

int mail_cache_open_and_verify(struct mail_cache *cache)
{
	int ret;

	ret = mail_cache_try_open(cache);
	if (ret > 0)
		ret = mail_cache_header_fields_read(cache);
	if (ret < 0) {
		/* failed for some reason - doesn't really matter,
		   it's disabled for now. */
		mail_cache_file_close(cache);
	}
	return ret;
}

static struct mail_cache *mail_cache_alloc(struct mail_index *index)
{
	struct mail_cache *cache;

	cache = i_new(struct mail_cache, 1);
	cache->index = index;
	cache->fd = -1;
	cache->filepath =
		i_strconcat(index->filepath, MAIL_CACHE_FILE_SUFFIX, NULL);
	cache->field_pool = pool_alloconly_create("Cache fields", 2048);
	hash_table_create(&cache->field_name_hash, cache->field_pool, 0,
			  strcase_hash, strcasecmp);

	cache->dotlock_settings.use_excl_lock =
		(index->flags & MAIL_INDEX_OPEN_FLAG_DOTLOCK_USE_EXCL) != 0;
	cache->dotlock_settings.nfs_flush =
		(index->flags & MAIL_INDEX_OPEN_FLAG_NFS_FLUSH) != 0;
	cache->dotlock_settings.timeout =
		I_MIN(MAIL_CACHE_LOCK_TIMEOUT, index->max_lock_timeout_secs);
	cache->dotlock_settings.stale_timeout = MAIL_CACHE_LOCK_CHANGE_TIMEOUT;

	if (!MAIL_INDEX_IS_IN_MEMORY(index) &&
	    (index->flags & MAIL_INDEX_OPEN_FLAG_MMAP_DISABLE) != 0)
		cache->file_cache = file_cache_new(-1);
	cache->map_with_read =
		(cache->index->flags & MAIL_INDEX_OPEN_FLAG_SAVEONLY) != 0;

	cache->ext_id =
		mail_index_ext_register(index, "cache", 0,
					sizeof(uint32_t), sizeof(uint32_t));
	mail_index_register_expunge_handler(index, cache->ext_id, FALSE,
					    mail_cache_expunge_handler, cache);
	return cache;
}

struct mail_cache *mail_cache_open_or_create(struct mail_index *index)
{
	struct mail_cache *cache;

	cache = mail_cache_alloc(index);
	return cache;
}

void mail_cache_free(struct mail_cache **_cache)
{
	struct mail_cache *cache = *_cache;

	*_cache = NULL;
	if (cache->file_cache != NULL)
		file_cache_free(&cache->file_cache);

	mail_index_unregister_expunge_handler(cache->index, cache->ext_id);
	mail_cache_file_close(cache);

	if (cache->read_buf != NULL)
		buffer_free(&cache->read_buf);
	hash_table_destroy(&cache->field_name_hash);
	pool_unref(&cache->field_pool);
	i_free(cache->field_file_map);
	i_free(cache->file_field_map);
	i_free(cache->fields);
	i_free(cache->filepath);
	i_free(cache);
}

static int mail_cache_lock_file(struct mail_cache *cache, bool nonblock)
{
	unsigned int timeout_secs;
	int ret;

	if (cache->last_lock_failed) {
		/* previous locking failed. don't waste time waiting on it
		   again, just try once to see if it's available now. */
		nonblock = TRUE;
	}

	if (cache->index->lock_method != FILE_LOCK_METHOD_DOTLOCK) {
		i_assert(cache->file_lock == NULL);
		timeout_secs = I_MIN(MAIL_CACHE_LOCK_TIMEOUT,
				     cache->index->max_lock_timeout_secs);

		ret = mail_index_lock_fd(cache->index, cache->filepath,
					 cache->fd, F_WRLCK,
					 nonblock ? 0 : timeout_secs,
					 &cache->file_lock);
	} else {
		enum dotlock_create_flags flags =
			nonblock ? DOTLOCK_CREATE_FLAG_NONBLOCK : 0;

		i_assert(cache->dotlock == NULL);
		ret = file_dotlock_create(&cache->dotlock_settings,
					  cache->filepath, flags,
					  &cache->dotlock);
		if (ret < 0) {
			mail_cache_set_syscall_error(cache,
						     "file_dotlock_create()");
		}
	}
	cache->last_lock_failed = ret <= 0;

	/* don't bother warning if locking failed due to a timeout. since cache
	   updating isn't all that important we're using a very short timeout
	   so it can be triggered sometimes on heavy load */
	if (ret <= 0)
		return ret;

	mail_index_flush_read_cache(cache->index, cache->filepath, cache->fd,
				    TRUE);
	return 1;
}

static void mail_cache_unlock_file(struct mail_cache *cache)
{
	if (cache->index->lock_method != FILE_LOCK_METHOD_DOTLOCK)
		file_unlock(&cache->file_lock);
	else
		file_dotlock_delete(&cache->dotlock);
}

static int
mail_cache_lock_full(struct mail_cache *cache, bool nonblock)
{
	const struct mail_index_ext *ext;
	const void *data;
	struct mail_index_view *iview;
	uint32_t reset_id;
	int i;

	i_assert(!cache->locked);

	if (!cache->opened)
		(void)mail_cache_open_and_verify(cache);

	if (MAIL_CACHE_IS_UNUSABLE(cache) ||
	    MAIL_INDEX_IS_IN_MEMORY(cache->index) ||
	    cache->index->readonly)
		return 0;

	for (;;) {
		if (mail_cache_lock_file(cache, nonblock) <= 0)
			return -1;
		i_assert(!MAIL_CACHE_IS_UNUSABLE(cache));
		if (!mail_cache_need_reopen(cache)) {
			/* locked the latest file */
			break;
		}
		if (mail_cache_reopen_now(cache) <= 0) {
			i_assert(cache->file_lock == NULL);
			return -1;
		}
		i_assert(cache->file_lock == NULL);
		/* okay, so it was just compressed. try again. */
	}

	/* now verify that the index reset_id matches the cache's file_seq */
	for (i = 0; ; i++) {
		iview = mail_index_view_open(cache->index);
		ext = mail_index_view_get_ext(iview, cache->ext_id);
		reset_id = ext == NULL ? 0 : ext->reset_id;
		mail_index_view_close(&iview);

		if (cache->hdr->file_seq == reset_id)
			break;
		/* mismatch. try refreshing index once. if that doesn't help,
		   we can't use the cache. */
		if (i > 0 || cache->index->mapping) {
			mail_cache_unlock_file(cache);
			return 0;
		}
		if (mail_index_refresh(cache->index) < 0) {
			mail_cache_unlock_file(cache);
			return -1;
		}
	}

	/* successfully locked - make sure our header is up to date */
	cache->locked = TRUE;
	cache->hdr_modified = FALSE;

	if (cache->file_cache != NULL) {
		file_cache_invalidate(cache->file_cache, 0,
				      sizeof(struct mail_cache_header));
	}
	if (cache->read_buf != NULL)
		buffer_set_used_size(cache->read_buf, 0);
	if (mail_cache_map(cache, 0, 0, &data) <= 0) {
		(void)mail_cache_unlock(cache);
		return -1;
	}
	cache->hdr_copy = *cache->hdr;
	return 1;
}

int mail_cache_lock(struct mail_cache *cache)
{
	return mail_cache_lock_full(cache, FALSE);
}

int mail_cache_try_lock(struct mail_cache *cache)
{
	return mail_cache_lock_full(cache, TRUE);
}

int mail_cache_unlock(struct mail_cache *cache)
{
	int ret = 0;

	i_assert(cache->locked);

	if (cache->field_header_write_pending)
                ret = mail_cache_header_fields_update(cache);

	if (MAIL_CACHE_IS_UNUSABLE(cache)) {
		/* we found it to be broken during the lock. just clean up. */
		cache->hdr_modified = FALSE;
		cache->locked = FALSE;
		return -1;
	}

	if (cache->hdr_modified) {
		cache->hdr_modified = FALSE;
		if (mail_cache_write(cache, &cache->hdr_copy,
				     sizeof(cache->hdr_copy), 0) < 0)
			ret = -1;
		cache->hdr_ro_copy = cache->hdr_copy;
		mail_cache_update_need_compress(cache);
	}

	if (cache->index->fsync_mode == FSYNC_MODE_ALWAYS) {
		if (fdatasync(cache->fd) < 0)
			mail_cache_set_syscall_error(cache, "fdatasync()");
	}

	cache->locked = FALSE;
	mail_cache_unlock_file(cache);
	return ret;
}

int mail_cache_write(struct mail_cache *cache, const void *data, size_t size,
		     uoff_t offset)
{
	i_assert(cache->locked);

	if (pwrite_full(cache->fd, data, size, offset) < 0) {
		mail_cache_set_syscall_error(cache, "pwrite_full()");
		return -1;
	}

	if (cache->file_cache != NULL)
		file_cache_write(cache->file_cache, data, size, offset);
	if (cache->read_buf != NULL)
		buffer_set_used_size(cache->read_buf, 0);
	return 0;
}

int mail_cache_append(struct mail_cache *cache, const void *data, size_t size,
		      uint32_t *offset)
{
	struct stat st;

	if (*offset == 0) {
		if (fstat(cache->fd, &st) < 0) {
			if (!ESTALE_FSTAT(errno))
				mail_cache_set_syscall_error(cache, "fstat()");
			return -1;
		}
		*offset = st.st_size;
	}
	if (*offset > (uint32_t)-1 || (uint32_t)-1 - *offset < size) {
		mail_cache_set_corrupted(cache, "Cache file too large");
		return -1;
	}
	if (mail_cache_write(cache, data, size, *offset) < 0)
		return -1;

	/* FIXME: this is updated only so that older Dovecot versions (<=v2.1)
	   can read this file. we can remove this later. */
	cache->hdr_modified = TRUE;
	cache->hdr_copy.backwards_compat_used_file_size = *offset + size;
	return 0;
}

bool mail_cache_exists(struct mail_cache *cache)
{
	return !MAIL_CACHE_IS_UNUSABLE(cache);
}

struct mail_cache_view *
mail_cache_view_open(struct mail_cache *cache, struct mail_index_view *iview)
{
	struct mail_cache_view *view;

	view = i_new(struct mail_cache_view, 1);
	view->cache = cache;
	view->view = iview;
	view->cached_exists_buf =
		buffer_create_dynamic(default_pool,
				      cache->file_fields_count + 10);
	return view;
}

void mail_cache_view_close(struct mail_cache_view **_view)
{
	struct mail_cache_view *view = *_view;

	i_assert(view->trans_view == NULL);

	*_view = NULL;
	if (view->cache->field_header_write_pending &&
	    !view->cache->compressing)
                (void)mail_cache_header_fields_update(view->cache);

	buffer_free(&view->cached_exists_buf);
	i_free(view);
}

void mail_cache_view_update_cache_decisions(struct mail_cache_view *view,
					    bool update)
{
	view->no_decision_updates = !update;
}

uint32_t mail_cache_get_first_new_seq(struct mail_index_view *view)
{
	const struct mail_index_header *idx_hdr;
	uint32_t first_new_seq, message_count;

	idx_hdr = mail_index_get_header(view);
	if (idx_hdr->day_first_uid[7] == 0)
		return 1;

	if (!mail_index_lookup_seq_range(view, idx_hdr->day_first_uid[7],
					 (uint32_t)-1, &first_new_seq,
					 &message_count)) {
		/* all messages are too old */
		return message_count+1;
	}
	return first_new_seq;
}


text:
package io.github.tcdl.msb.api;

import org.apache.commons.lang3.Validate;

import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.Set;

public class ActiveMQResponderOptions extends ResponderOptions {

    private final SubscriptionType subscriptionType;
    private final Set<String> bindingKeys;

    private ActiveMQResponderOptions(Set<String> bindingKeys,
                                   MessageTemplate messageTemplate,
                                   SubscriptionType subscriptionType) {
        super(bindingKeys, messageTemplate);
        this.bindingKeys = bindingKeys;
        this.subscriptionType = subscriptionType;
    }

    public SubscriptionType getSubscriptionType() {
        return subscriptionType;
    }

    public Set<String> getBindingKeys() {
        return bindingKeys;
    }

    public static class Builder extends ResponderOptions.Builder {

        private SubscriptionType subscriptionType = SubscriptionType.QUEUE;
        private Set<String> bindingKeys;

        public Builder withMessageTemplate(MessageTemplate responseMessageTemplate) {
            this.messageTemplate = responseMessageTemplate;
            return this;
        }

        public Builder withBindingKeys(Set<String> bindingKeys) {
            this.bindingKeys = bindingKeys;
            return this;
        }

        public Builder withSubscriptionType(@Nonnull SubscriptionType subscriptionType){
            Validate.notNull(subscriptionType);
            this.subscriptionType = subscriptionType;
            return this;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ResponderOptions build() {
            Set<String> bindingKeys = this.bindingKeys == null || this.bindingKeys.isEmpty()
                    ? Collections.emptySet()
                    : this.bindingKeys;
            return new ActiveMQResponderOptions(bindingKeys, messageTemplate, subscriptionType);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace BGE;

PhysicsGame1::PhysicsGame1(void)
{
	physicsFactory = NULL;
	dynamicsWorld = NULL;
	broadphase = NULL;
	dispatcher = NULL;
	solver = NULL;
	fullscreen = false;

}

PhysicsGame1::~PhysicsGame1(void)
{
}

shared_ptr<PhysicsController> cyl;
std::shared_ptr<GameComponent> station;

bool PhysicsGame1::Initialise()
{
	riftEnabled = false;
	// Set up the collision configuration and dispatcher
    collisionConfiguration = new btDefaultCollisionConfiguration();
    dispatcher = new btCollisionDispatcher(collisionConfiguration);

    // The world.
	btVector3 worldMin(-1000,-1000,-1000);
	btVector3 worldMax(1000,1000,1000);
	broadphase = new btAxisSweep3(worldMin,worldMax);
	solver = new btSequentialImpulseConstraintSolver();
	dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);
    dynamicsWorld->setGravity(btVector3(0,0,0));

	physicsFactory = make_shared<PhysicsFactory>(dynamicsWorld);

	physicsFactory->CreateGroundPhysics();
	physicsFactory->CreateCameraPhysics();

	//physicsFactory->CreateWall(glm::vec3(-20,0,20), 10, 10);
	//// Now some constraints
	//

	//
	//physicsFactory->CreateVehicle(glm::vec3(0,10,-30));

	shared_ptr<PhysicsController> box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(5, 5, 0), glm::quat());
	shared_ptr<PhysicsController> box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(5, 5, 5), glm::quat());

	// A hinge
	btHingeConstraint * hinge = new btHingeConstraint(*box1->rigidBody, *box2->rigidBody, btVector3(0,0,2.5f),btVector3(0,0,-2.5f), btVector3(0,1,0), btVector3(0,1,0), true);
	dynamicsWorld->addConstraint(hinge);

	// Another hinge
	box1 = physicsFactory->CreateBox(6,1,2, glm::vec3(15, 5, 0), glm::quat());
	cyl = physicsFactory->CreateCylinder(2, 1, glm::vec3(15, 5, -5), glm::angleAxis(90.0f, glm::vec3(1,0,0)));
	hinge = new btHingeConstraint(*box1->rigidBody, *cyl->rigidBody, btVector3(0,0,-2),btVector3(0,2,0), btVector3(0,0,1), btVector3(0,1,0), true);
	dynamicsWorld->addConstraint(hinge);

	// A Ball and socket
	box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(20, 5, 0), glm::quat());
	box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(20, 5, 5), glm::quat());

	btPoint2PointConstraint * ptpConstraint = new btPoint2PointConstraint(*box1->rigidBody, *box2->rigidBody, btVector3(0,0,2.5f),btVector3(0,0,-2.5f));
	dynamicsWorld->addConstraint(ptpConstraint);

	// A Slider
	box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(25, 5, 0), glm::quat());
	box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(25, 5, 5), glm::quat());
	btTransform box1Transform;
	btTransform box2Transform;
	box1Transform.setIdentity();
	box2Transform.setIdentity();

	// You have to make the x axis rotate to the axis you want to slide
	box1Transform.setRotation(GLToBtQuat(glm::angleAxis(90.0f, glm::vec3(0,1,0))));
	box2Transform.setRotation(GLToBtQuat(glm::angleAxis(90.0f, glm::vec3(0,1,0))));

	btSliderConstraint * slider = new btSliderConstraint(*box1->rigidBody, *box2->rigidBody, box1Transform, box2Transform, true);
	dynamicsWorld->addConstraint(slider);

	if (!Game::Initialise()) {
		return false;
	}

	camera->GetController()->position = glm::vec3(0,10, 20);

	return true;
}

void BGE::PhysicsGame1::Update(float timeDelta)
{
	cyl->rigidBody->applyTorque(GLToBtVector(glm::vec3(0.0f,0.0f,1.0f)));

	dynamicsWorld->stepSimulation(timeDelta,100);
	Game::Update(timeDelta);
}

void BGE::PhysicsGame1::Cleanup()
{
	Game::Cleanup();
}


text:
local victory = {}

function victory:init()

end

function victory:enter(prev)
    self.prevState = prev
end

function victory:update(dt)

end

function victory:keypressed(key, code)
    State.switch(States.game)
end

function victory:keyreleased(key, code)

end

function victory:touchreleased(id, x, y, dx, dy, pressure)

end

function victory:mousepressed(x, y, mbutton)

end

local function drawCenteredText(text, y)
    love.graphics.printf(text, 0, y, love.graphics.getWidth(), "center")
end

function victory:draw()
    self.prevState:draw()
    love.graphics.setColor(0, 0, 0, 200)
    love.graphics.rectangle('fill', 0, 0, love.graphics.getWidth(), love.graphics.getHeight())

    local text = "YOU SURVIVED"
    love.graphics.setColor(33, 180, 33)
    love.graphics.setFont(Fonts.bold[72])
    drawCenteredText(text, love.graphics.getHeight()/4)

    -- SCORE
    local scoreText = ""
    if self.prevState.roundTime then
        scoreText = scoreText .. string.format("Completed in %.3f space seconds!\n", self.prevState.roundTime)
    end
    if self.prevState.enemyKills then
        scoreText = scoreText .. string.format("You killed " .. self.prevState.enemyKills .. " space squids!\n")
    end
    love.graphics.setColor(238, 230, 35)
    love.graphics.setFont(Fonts.bold[52])
    drawCenteredText(scoreText, love.graphics.getHeight()/2)

    local text = "Press any key to restart"
    love.graphics.setColor(255, 255, 255)
    love.graphics.setFont(Fonts.default[36])
    drawCenteredText(text, love.graphics.getHeight()*3/4)
end

return victory


text:
System.register(['./chunk-ad0e6b97.js'],function(exports,module){'use strict';var fn;return{setters:[function(module){fn=module.a;}],execute:function(){function fn$1 () {
  console.log('dep1 fn');
}class Main1 {
  constructor () {
    fn$1();
    fn();
  }
} exports('default', Main1);}}});


text:
The `latest` Docker tag and the `master` git branch are for Meteor 1.4+.  For
prior versions of Meteor, please use the `legacy` tag and branch.

In order to keep the size of the image down, the `current` tag does _not_
include `build-essential` tools.  If you are using modules which do not supply
binary versions for your platform, please use the `build` tag, which does
include `build-essential`.

## Features:

 * Meteor 1.4+ package/bundle support (for previous Meteor versions, use the
   `legacy` branch/tag)
 * Bundle-based execution
   * directory referenced as `APP_DIR` (meteor build --directory); defaults to `/home/meteor/www`
   * downloaded with `curl` from `BUNDLE_URL` (if supplied)
   * set `CURL_OPTS` if you need to pass additional parameters
 * Source-based build/execution
   * Downloads latest Meteor tool at runtime (always the latest tool version unless a `RELEASE` is specified, but apps run with their own versions)
   * Supply source at `SRC_DIR` (defaults to `/home/meteor/src`)
   * Supply source from `REPO` (git clone URL)
      * Optionally specify a `DEPLOY_KEY` file for SSH authentication to private repositories
      * Optionally specify a `BRANCH` is not the default `master` (can also be a tag name)
 * References your external MongoDB database
   * Uses Docker links (i.e. `MONGO_PORT`...)
   * Explicit Mongo URLs by at `MONGO_URL`
   * NOTE: This does NOT set `MONGO_OPLOG_URL`.  There were too many potention complications.  As a result, unless you explicitly set `MONGO_OPLOG_URL`, Meteor will fall back to a polling-based approach to database synchronization.  Note that oplog tailing requires a working replica set on your MongoDB server as well as access to the `local` database.
 * Optionally specify the port on which the web server should run (`PORT`); defaults to 80
 * Non-root location of Meteor tree; the script will search for the first .meteor directory
 * _NOTE_: PhantomJS is no longer pre-installed.  This package was swelling the size of the image by 50%, and it is not maintainable with the standard Docker Node images.  Instead, please use one of the docker-friendly (read port-based) spiderable packages on Meteor, such as [ongoworks:spiderable](https://atmospherejs.com/ongoworks/spiderable);  if there is demand, please create an issue on Github, and I'll see about managing a separate branch for it.

## Versions

The Meteor tool (if required; see Modes of Operation below) is downloaded at
runtime, so it is no longer packaged and the version of this docker image does
not matter for the version of meteor.

You can specify which version of Meteor you want to be installed by setting the
`RELEASE` as required.  However, this release of `ulexus/meteor` does require a
minimum version of 1.4 for your Meteor application.

## Modes of operation

There are two basic modes of operation for this image: source and pre-bundled.
The source method allows the greatest flexibility, since it builds and bundles
Meteor on the deployment system inside the same container.  However, it also
takes much longer and requires a much larger disk footprint.

### Source mode

To utilize source mode, define one of `SRC_DIR` or `REPO`:

  - `SRC_DIR`
      If you put your application source in the directory pointed to by `SRC_DIR` (`/home/meteor/src`, by default), this container will download the Meteor tool,
      build your application, bundle it, then execute it.  It is usually sufficient to simply pass `docker run` an argument like `-v /srv/myApp:/src/app`.

  - `REPO`
      If you populate the `REPO` environment variable, it is presumed that this is where your application source resides.  This container will
      `git pull` your `REPO`, change to `master` or the supplied `BRANCH` (which can also be a tag).  The source tree will be placed in
      `APP_DIR`, and the script will pick up processing `APP_DIR` (above) from there.

When the container is run, the appropriate version of the Meteor tool will be
downloaded and installed, your application will be built/bundled, and then it
will be run.  This process can take several *minutes* to complete.

#### Running without root

As of Meteor 1.4.2, running Meteor as root has been strongly dissuaded.  As a
result, we now drop root privileges after starting the container.  This means
that if you are bind-mounting your source or bundle directories, the files must
be **readable** and **writable** by the container's unprivileged user (**UID 1000**).

### Pre-bundled mode

To utilize the pre-bundled mode, **DO NOT** define `SRC_DIR` or `REPO`.  Instead
define one of `APP_DIR` or `BUNDLE_DIR`:

  - `APP_DIR`
      If you put your bundled application in the directory pointed to by `APP_DIR` (`/home/meteor/www`, by default), this container will attempt to find a Meteor bundle
      in this directory and then start Node to run that bundle.  The Meteor tool will not be installed (as a bundled Meteor app needs only Node).
      The default `APP_DIR` is `/home/meteor/www`, so you may attach that as a volume, for greatest simplicity.  Something like: `-v /srv/myApp:/home/meteor/www`.
  - `BUNDLE_URL`
      If you populate `BUNDLE_URL`, the container expects to find a bundled tarball, as generated by `meteor build ./` at this URL.  The tarball is
      downloaded (with curl... so you may set `CURL_OPTS` as required) and extracted to the bundle directory, and the process continues from `BUNDLE_DIR` (above).

When the container is run, the Meteor tool will NOT be downloaded.  Instead,
`npm install` will be run to resolve any dependencies for the server, and your
application will be run directly with NodeJS.

## Examples:

### git repo with non-default (master) branch
```sh
docker run --rm \
  -e ROOT_URL=http://testsite.com \
  -e REPO=https://github.com/yourName/testsite \
  -e BRANCH=testing \
  -e MONGO_URL=mongodb://mymongoserver.com:27017/mydatabase \
  -e MONGO_OPLOG_URL=mongodb://mymongoserver.com:27017/local \
  ulexus/meteor
```

### app source from a local directory on host (/home/user/myapp)
```sh
docker run --rm \
  -e ROOT_URL=http://testsite.com \
  -v /home/user/myapp:/home/meteor/src \
  -e MONGO_URL=mongodb://mymongoserver.com:27017/appdb \
  -e MONGO_OPLOG_URL=mongodb://mymongoserver.com:27017/local \
  ulexus/meteor
```

### pre-bundled app from a local directory on host (/home/user/myapp)
```sh
docker run --rm \
  -e ROOT_URL=http://testsite.com \
  -v /home/user/myapp:/home/meteor/www \
  -e MONGO_URL=mongodb://mymongoserver.com:27017/appdb \
  -e MONGO_OPLOG_URL=mongodb://mymongoserver.com:27017/local \
  ulexus/meteor
```

### local app source directory on host (/home/user/myapp) with specific Meteor release (1.4.2.1)
```sh
docker run --rm \
  -e ROOT_URL=http://testsite.com \
  -v /home/user/myapp:/home/meteor/src \
  -e MONGO_URL=mongodb://mymongoserver.com:27017/appdb \
  -e MONGO_OPLOG_URL=mongodb://mymongoserver.com:27017/local \
  -e RELEASE=1.4.2.1 \
  ulexus/meteor
```

### Unit file

There is also a sample systemd [unit file](meteor.myapp@.service) in the Github repository.

### Build with bundled app

Pre-bundling your Meteor application will make it start *much* faster and will
allow the container to maintain a smaller storage footprint.  However, it does
require that you build for the same architecture on which you will be deploying.

```bash
cd $app_source
meteor build --directory /tmp/export-meteor/build
cat >/tmp/export-meteor/Dockerfile <<ENDHERE
FROM ulexus/meteor
COPY build /home/meteor/www
RUN chown -R meteor:meteor /home/meteor/
ENDHERE
cd /tmp/export-meteor
docker build -t myapp .
docker push myapp
```

### Kubernetes

There is a complete example with build script of building and running a
versioned container in kubernetes in the
[examples](https://github.com/CyCoreSystems/docker-meteor/tree/v1.4/examples)
directory.


text:
/****************************************************************************
** Meta object code from reading C++ file 'trighelper.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/

#include "../TrigHelper/trighelper.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'trighelper.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif

QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_TrigHelper[] = {

 // content:
       6,       // revision
       0,       // classname
       0,    0, // classinfo
       1,   14, // methods
       0,    0, // properties
       0,    0, // enums/sets
       0,    0, // constructors
       0,       // flags
       0,       // signalCount

 // slots: signature, parameters, type, tag, flags
      12,   11,   11,   11, 0x08,

       0        // eod
};

static const char qt_meta_stringdata_TrigHelper[] = {
    "TrigHelper\0\0on_calculate_button_clicked()\0"
};

void TrigHelper::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
    if (_c == QMetaObject::InvokeMetaMethod) {
        Q_ASSERT(staticMetaObject.cast(_o));
        TrigHelper *_t = static_cast<TrigHelper *>(_o);
        switch (_id) {
        case 0: _t->on_calculate_button_clicked(); break;
        default: ;
        }
    }
    Q_UNUSED(_a);
}

const QMetaObjectExtraData TrigHelper::staticMetaObjectExtraData = {
    0,  qt_static_metacall
};

const QMetaObject TrigHelper::staticMetaObject = {
    { &QWidget::staticMetaObject, qt_meta_stringdata_TrigHelper,
      qt_meta_data_TrigHelper, &staticMetaObjectExtraData }
};

#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &TrigHelper::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION

const QMetaObject *TrigHelper::metaObject() const
{
    return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}

void *TrigHelper::qt_metacast(const char *_clname)
{
    if (!_clname) return 0;
    if (!strcmp(_clname, qt_meta_stringdata_TrigHelper))
        return static_cast<void*>(const_cast< TrigHelper*>(this));
    return QWidget::qt_metacast(_clname);
}

int TrigHelper::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QWidget::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 1)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 1;
    }
    return _id;
}
QT_END_MOC_NAMESPACE


text:
package org.projectfloodlight.openflow.protocol.ver11;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;

class OFActionSetTpDstVer11 implements OFActionSetTpDst {
    private static final Logger logger = LoggerFactory.getLogger(OFActionSetTpDstVer11.class);
    // version: 1.1
    final static byte WIRE_VERSION = 2;
    final static int LENGTH = 8;

        private final static TransportPort DEFAULT_TP_PORT = TransportPort.NONE;

    // OF message fields
    private final TransportPort tpPort;
//
    // Immutable default instance
    final static OFActionSetTpDstVer11 DEFAULT = new OFActionSetTpDstVer11(
        DEFAULT_TP_PORT
    );

    // package private constructor - used by readers, builders, and factory
    OFActionSetTpDstVer11(TransportPort tpPort) {
        if(tpPort == null) {
            throw new NullPointerException("OFActionSetTpDstVer11: property tpPort cannot be null");
        }
        this.tpPort = tpPort;
    }

    // Accessors for OF message fields
    @Override
    public OFActionType getType() {
        return OFActionType.SET_TP_DST;
    }

    @Override
    public TransportPort getTpPort() {
        return tpPort;
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_11;
    }

    public OFActionSetTpDst.Builder createBuilder() {
        return new BuilderWithParent(this);
    }

    static class BuilderWithParent implements OFActionSetTpDst.Builder {
        final OFActionSetTpDstVer11 parentMessage;

        // OF message fields
        private boolean tpPortSet;
        private TransportPort tpPort;

        BuilderWithParent(OFActionSetTpDstVer11 parentMessage) {
            this.parentMessage = parentMessage;
        }

    @Override
    public OFActionType getType() {
        return OFActionType.SET_TP_DST;
    }

    @Override
    public TransportPort getTpPort() {
        return tpPort;
    }

    @Override
    public OFActionSetTpDst.Builder setTpPort(TransportPort tpPort) {
        this.tpPort = tpPort;
        this.tpPortSet = true;
        return this;
    }
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_11;
    }

        @Override
        public OFActionSetTpDst build() {
                TransportPort tpPort = this.tpPortSet ? this.tpPort : parentMessage.tpPort;
                if(tpPort == null)
                    throw new NullPointerException("Property tpPort must not be null");

                //
                return new OFActionSetTpDstVer11(
                    tpPort
                );
        }

    }

    static class Builder implements OFActionSetTpDst.Builder {
        // OF message fields
        private boolean tpPortSet;
        private TransportPort tpPort;

    @Override
    public OFActionType getType() {
        return OFActionType.SET_TP_DST;
    }

    @Override
    public TransportPort getTpPort() {
        return tpPort;
    }

    @Override
    public OFActionSetTpDst.Builder setTpPort(TransportPort tpPort) {
        this.tpPort = tpPort;
        this.tpPortSet = true;
        return this;
    }
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_11;
    }

//
        @Override
        public OFActionSetTpDst build() {
            TransportPort tpPort = this.tpPortSet ? this.tpPort : DEFAULT_TP_PORT;
            if(tpPort == null)
                throw new NullPointerException("Property tpPort must not be null");

            return new OFActionSetTpDstVer11(
                    tpPort
                );
        }

    }

    final static Reader READER = new Reader();
    static class Reader implements OFMessageReader<OFActionSetTpDst> {
        @Override
        public OFActionSetTpDst readFrom(ByteBuf bb) throws OFParseError {
            int start = bb.readerIndex();
            // fixed value property type == 10
            short type = bb.readShort();
            if(type != (short) 0xa)
                throw new OFParseError("Wrong type: Expected=OFActionType.SET_TP_DST(10), got="+type);
            int length = U16.f(bb.readShort());
            if(length != 8)
                throw new OFParseError("Wrong length: Expected=8(8), got="+length);
            if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
                // Buffer does not have all data yet
                bb.readerIndex(start);
                return null;
            }
            if(logger.isTraceEnabled())
                logger.trace("readFrom - length={}", length);
            TransportPort tpPort = TransportPort.read2Bytes(bb);
            // pad: 2 bytes
            bb.skipBytes(2);

            OFActionSetTpDstVer11 actionSetTpDstVer11 = new OFActionSetTpDstVer11(
                    tpPort
                    );
            if(logger.isTraceEnabled())
                logger.trace("readFrom - read={}", actionSetTpDstVer11);
            return actionSetTpDstVer11;
        }
    }

    public void putTo(PrimitiveSink sink) {
        FUNNEL.funnel(this, sink);
    }

    final static OFActionSetTpDstVer11Funnel FUNNEL = new OFActionSetTpDstVer11Funnel();
    static class OFActionSetTpDstVer11Funnel implements Funnel<OFActionSetTpDstVer11> {
        private static final long serialVersionUID = 1L;
        @Override
        public void funnel(OFActionSetTpDstVer11 message, PrimitiveSink sink) {
            // fixed value property type = 10
            sink.putShort((short) 0xa);
            // fixed value property length = 8
            sink.putShort((short) 0x8);
            message.tpPort.putTo(sink);
            // skip pad (2 bytes)
        }
    }

    public void writeTo(ByteBuf bb) {
        WRITER.write(bb, this);
    }

    final static Writer WRITER = new Writer();
    static class Writer implements OFMessageWriter<OFActionSetTpDstVer11> {
        @Override
        public void write(ByteBuf bb, OFActionSetTpDstVer11 message) {
            // fixed value property type = 10
            bb.writeShort((short) 0xa);
            // fixed value property length = 8
            bb.writeShort((short) 0x8);
            message.tpPort.write2Bytes(bb);
            // pad: 2 bytes
            bb.writeZero(2);

        }
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFActionSetTpDstVer11(");
        b.append("tpPort=").append(tpPort);
        b.append(")");
        return b.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        OFActionSetTpDstVer11 other = (OFActionSetTpDstVer11) obj;

        if (tpPort == null) {
            if (other.tpPort != null)
                return false;
        } else if (!tpPort.equals(other.tpPort))
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;

        result = prime * result + ((tpPort == null) ? 0 : tpPort.hashCode());
        return result;
    }

}


text:
		<input type="text" value="Bad" ng-model="qs.rating.min" class="form-control"/>

			1 to

			<input type="number" min="1" value="1" ng-model="qs.rating.value" class="form-control"/>

		<input type="text" value="Good" ng-model="qs.rating.max" class="form-control" />

			<input type="checkbox" name="name" ng-model="qs.rating.not_applicable">
			 Not Applicable

		<input class="form-control" type="text" ng-show="qs.rating.not_applicable" ng-model="qs.rating.not_applicable_value" placeholder="Input Not applicable" />

			<input type="checkbox" ng-model="qs.rating.required" name=""/>
			 Required

		<input type="text" class="form-control" ng-model="qs.rating.message.required" ng-show="qs.rating.required" value="" placeholder="Validation message ...">


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Class: Game::Database::RelationShips::UserFragmentMessage

    — Documentation by YARD 0.8.7.6

</title>

  <link rel="stylesheet" href="../../../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../../../css/common.css" type="text/css" charset="utf-8" />

    Index (U) »
    Game » Database » RelationShips
     »
    UserFragmentMessage

(no frames)

      Class List

      Method List

      File List

Class: Game::Database::RelationShips::UserFragmentMessage

Inherits:

      Object

Object

Game::Database::RelationShips::UserFragmentMessage

        show all

Includes:

Neo4j::ActiveRel

Defined in:

rb/db/relations/user-message_fragment.rb

Overview

Relación para definir los fragmentos recolectados por un usuario.

Contendrá la fecha de recolección del fragmento.

      Instance Method Summary
      (collapse)

      - (DateTime) created_at

Timestamp o fecha de completación del mensaje.

      - (Game::Database::User) from_class

Relaciona la clase User con la clase MessageFragment, para saber cuando ha
recogido el fragmento.

      - (Game::Database::MessageFragment) to_class

Relaciona la clase User con la clase MessageFragment, para saber cuando ha
recogido el fragmento.

      - (String) type

Tipo o nombrel del enlace.

Instance Method Details

    - (<tt>DateTime</tt>) created_at

Timestamp o fecha de completación del mensaje.

Returns:

        (<tt>DateTime</tt>)

        —

Fecha de creación.

45

# File 'rb/db/relations/user-message_fragment.rb', line 45

property :created_at

    - (<tt>Game::Database::User</tt>) from_class

Relaciona la clase User con la clase MessageFragment, para saber cuando ha
recogido el fragmento.

Returns:

        (<tt>Game::Database::User</tt>)

27

# File 'rb/db/relations/user-message_fragment.rb', line 27

from_class Game::Database::User

    - (<tt>Game::Database::MessageFragment</tt>) to_class

Relaciona la clase User con la clase MessageFragment, para saber cuando ha
recogido el fragmento.

Returns:

        (<tt>Game::Database::MessageFragment</tt>)

32

# File 'rb/db/relations/user-message_fragment.rb', line 32

to_class   Game::Database::MessageFragment

    - (<tt>String</tt>) type

Tipo o nombrel del enlace.

Returns:

        (<tt>String</tt>)

        —

'owns_fragmented_message'

37

# File 'rb/db/relations/user-message_fragment.rb', line 37

type 'owns_fragmented_message'

  Generated on Fri May 22 14:15:11 2015 by
  yard
  0.8.7.6 (ruby-2.2.0).


text:
@implementation KMLAbstractGeometry (MapKit)

- (KMLPlacemark *)placemark
{
    KMLElement *parent = self.parent;
    while (parent) {
        if ([parent isKindOfClass:[KMLPlacemark class]]) {
            return (KMLPlacemark *)parent;
        }

        parent = parent.parent;
    }

    return nil;
}

- (MKShape *)mapkitShape
{
    return nil;
}

- (MKAnnotationView *)annotationViewForMapView:(MKMapView *)mapView annotation:(id<MKAnnotation>)annotation
{
    return nil;
}

- (MKOverlayView *)overlayViewForMapView:(MKMapView *)mapView overlay:(id<MKOverlay>)overlay
{
    return nil;
}

@end


text:
import ConfigParser
import os
import subprocess
import logging
import sys
import datetime
import time
import fnmatch
from PIL import Image, ImageChops, ImageOps, ImageStat
import math, operator
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import urlparse
import base64
import threading
from collections import namedtuple

# use RAM-backed temporary file store location - to reduce writes to the SD card
tmp_file = '/dev/shm/secpy.jpg'

# create the internal logger
log = logging.getLogger('secpy')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
#create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
#add formatter to ch
ch.setFormatter(formatter)
#add ch to logger
log.addHandler(ch)

# read configuration
config = ConfigParser.RawConfigParser()
config.read('secpy.cfg')

last_filename = tmp_file
force_shot = True

debug_last_motion_value = 0.0
recording_enabled = True

#def capture(schedular):
def capture():
    if recording_enabled is False:
        return
    # get the config settings for image capture
    exposure_time = config.get('image_properties', 'exposure_time')
    width = config.get('image_properties', 'width')
    height = config.get('image_properties', 'height')
    exposure_options = config.get('image_properties', 'exposure_options')
    try:
        subprocess.call(["raspistill", "-o", tmp_file, "-t", exposure_time, "-w", width, "-h", height, "-ex", exposure_options])
    except OSError as e:
        if e.errno == os.errno.ENOENT:
            # raspstill doesn't exist - so warn the user that it's required
            log.critical("Can't find the program 'raspistill'.  Have you enabled the cameramodule on Raspbian?")
            sys.exit(1)
        else:
            raise

    # compare the currently taken image with the last image, and see if there is a enough difference to bother storing it
    global last_filename, force_shot
    diff = compare2(last_filename, tmp_file)

    global debug_last_motion_value
    debug_last_motion_value = diff

    if diff > config.getfloat('image_properties', 'motion_threshold' ) or force_shot is True:
        force_shot = False
        log.debug('Change happened!')
        # create a filename using the current time and date
        now = datetime.datetime.now()
        timestr = now.strftime('/%Y-%m-%d_%H-%M-%S.jpg')
        dest_folder = config.get('image_properties', 'destination_folder')
        dest_filename = dest_folder + timestr
        last_filename = dest_filename
        # copy tmp file to permanant storage
        # check the file will fit in the destination folder
        file_size = os.path.getsize(tmp_file)
        disk_usage_stats = disk_usage(dest_folder)
        if file_size > disk_usage_stats.free:
            ensure_free_space(dest_folder, file_size)

        subprocess.call(["cp", tmp_file, dest_filename])

def compare(file1, file2):
    try:
        image1 = Image.open(file1)
        image2 = Image.open(file2)
    except IOError as e:
        log.critical(e)
        return 0.0

    h1 = image1.histogram()
    h2 = image2.histogram()
    rms = math.sqrt(reduce(operator.add,map(lambda a,b: (a-b)**2, h1, h2))/len(h1))
    return rms

def compare2(file1, file2):
    try:
        image1 = Image.open(file1)
        image2 = Image.open(file2)
    except IOError as e:
        log.critical(e)
        return 0.0

    # 1) get the difference between the two images
    # 2) convert the resulting image into greyscale
    # 3) find the medium value of the grey pixels
    # 4) if over a certain threshold, then we have movement

    image_diff = ImageChops.difference(image1, image2)
    image_diff = ImageOps.grayscale(image_diff)
    image_stat = ImageStat.Stat(image_diff)
    return image_stat.mean[0]

# following is from : http://stackoverflow.com/questions/787776/find-free-disk-space-in-python-on-os-x
_ntuple_diskusage = namedtuple('usage', 'total used free')
def disk_usage(path):
    """Return disk usage statistics about the given path.

    Returned values is a named tuple with attributes 'total', 'used' and
    'free', which are the amount of total, used and free space, in bytes.
    """
    st = os.statvfs(path)
    free = st.f_bavail * st.f_frsize
    total = st.f_blocks * st.f_frsize
    used = (st.f_blocks - st.f_bfree) * st.f_frsize
    return _ntuple_diskusage(total, used, free)

def ensure_free_space(path, free_space_bytes):
    """WARNING: This function is dangerous as it will delete .jpg files in the given path.  It ensures that there's enough free space at the given location - by deleting old .jpg files."""

    # gather list of .jpg files
    file_list = []
    for filename in os.listdir(path):
        if fnmatch.fnmatch(filename, '*.jpg'):
            full_fname = path + os.sep + filename
            file_list.append((os.stat(full_fname).st_mtime, full_fname))

    # reverse-sort by modified date
    file_list.sort(key=lambda a: a[0], reverse = True)

    # while we don't have enough space...
    while True:
        disk_usage_stats = disk_usage(path)
        dst_free_space = disk_usage_stats.free

        if len(file_list) == 0:
            break

        if dst_free_space < free_space_bytes:
            try:
                # delete oldest file
                log.debug("Removed : " + file_list[0][1])
                os.remove(file_list[0][1])
                file_list.pop(0)
            except IOError as e:
                log.critical(e)
        else:
            # we have enough space, so break out
            break

class HTTPThread(threading.Thread):
    def run(self):
        # check password isn't the default
        if config.get('server', 'password') == 'changeme':
            log.warning('Password is set to default!  Consider changing it to a unique password in secpy.cfg.')

        log.debug('Starting HTTP server on port : ' + config.get('server', 'port'))

        server_address = ("", config.getint('server', 'port'))
        server = HTTPServer(server_address, SecpyHttpHandler)
        server.serve_forever()

class SecpyHttpHandler(BaseHTTPRequestHandler):
    ''' Main class to present webpages and authentication. '''
    def do_HEAD(self):
        print "send header"
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_AUTHHEAD(self):
        print "send header"
        self.send_response(401)
        self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        ''' Present frontpage with user authentication. '''

        # generate base64 encoding of the username and password
        credentials64 = base64.b64encode ( config.get('server', 'username') + ":" + config.get('server', 'password') )

        if self.headers.getheader('Authorization') == None:
            self.do_AUTHHEAD()
            self.wfile.write('no auth header received')
            pass
        elif self.headers.getheader('Authorization') == ('Basic ' + credentials64):
            return self.index_page()
        else:
            self.do_AUTHHEAD()
            self.wfile.write(self.headers.getheader('Authorization'))
            self.wfile.write(' - not authenticated')
            pass

    def index_page(self):
        # see http://www.acmesystems.it/python_httpserver

        # discover any parameters
        query_str = urlparse.urlsplit(self.path).query
        params = None
        if len(query_str) > 0:
            params = urlparse.parse_qsl(query_str, 0, 1)

        global recording_enabled
        global force_shot
        if params is not None:
            if ('enable_recording', 'False') in params:
                # stop recording
                recording_enabled = False
            elif ('enable_recording', 'True') in params:
                # start recording
                recording_enabled = True

            if ('force_shot', 'True') in params:
                # force a shot to be taken and stored
                force_shot = True

            self.send_response(302)
            self.send_header('Location','/')
            self.end_headers()
            return

        try:
            send_reply = False

            if self.path.endswith(".html"):
                mimetype='text/html'
                send_reply = True
            if self.path.endswith(".jpg"):
                mimetype='image/jpg'
                send_reply = True
            if self.path.endswith(".gif"):
                mimetype='image/gif'
                send_reply = True
            if self.path.endswith(".js"):
                mimetype='application/javascript'
                send_reply = True
            if self.path.endswith(".css"):
                mimetype='text/css'
                send_reply = True

            if send_reply == True:
                #Open the static file requested and send it
                f = open(config.get('image_properties', 'destination_folder') + self.path)
                self.send_response(200)
                self.send_header('Content-type',mimetype)
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
            else:
                self.send_response(200)
                self.send_header('Content-type','text/html')
                self.end_headers()
                self.wfile.write("""<!DOCTYPE html>

                                            <title>Raspberry Pi Security System 1.0</title>

                                        """)

                if recording_enabled:
                    self.wfile.write("
Disable recording
\n")
                else:
                    self.wfile.write("
Enable recording
\n")
                self.wfile.write("
Force shot (forces a picture to be taken and saved)
\n")
                self.wfile.write("
Last motion-detection value = " + str(debug_last_motion_value) + "
\n")
                dest_dir = config.get('image_properties', 'destination_folder')

                # spin through all the files in the images folder and add links to them
                dir_list=os.listdir(dest_dir)
                dir_list.sort(reverse=True)
                if len(dir_list) > 0:
                    # show preview of latest image
                    self.wfile.write("

\n")
                self.wfile.write("
Motion history:
\n")
                for fname in dir_list:
                    self.wfile.write('
' + fname + '
\n')

                self.wfile.write("""
                                    """)
            return

        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)

if __name__ == '__main__':
    log.debug("Starting secpy")

    # fire up the HTTP server?
    if config.getboolean('server', 'server_enable') is True:
        http_thread = HTTPThread()
        http_thread.daemon = True
        http_thread.start()

    while True:
        capture()


text:
/**
 * This software is released as part of the Pumpernickel project.
 *
 * All com.pump resources in the Pumpernickel project are distributed under the
 * MIT License:
 * https://github.com/mickleness/pumpernickel/raw/master/License.txt
 *
 * More information about the Pumpernickel project is available here:
 * https://mickleness.github.io/pumpernickel/
 */
package com.pump.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;

/**
 * This object encodes a series of bytes (expressed as [0,255] integers).
 *

 * This data can be made available either in a dual-threaded push/pull model, or
 * in a single-threaded model by using the inner {@link DataListener} interface.
 */
public abstract class ByteEncoder implements AutoCloseable {

	/**
	 * This is notified when data is available or when an encoder is closed.
	 * This is is intended for single-threaded encoding.
	 */
	public static interface DataListener {
		public void chunkAvailable(ByteEncoder encoder) throws IOException;

		public void encoderClosed(ByteEncoder encoder) throws IOException;
	}

	protected boolean closed = false;
	private int waiting = 0;
	private DataListener listener = null;

	/**
	 * Assign a DataListener for this encoder.
	 *

	 * An encoder only has 1 listener at a time, so you cannot add multiple
	 * listeners.
	 *
	 * @param listener
	 *            the listener to assign. This replaces any previously assigned
	 *            listener.
	 */
	public synchronized void setListener(DataListener listener) {
		this.listener = listener;
	}

	/**
	 * Return the existing DataListener that has already been assigned to this
	 * encoder.
	 */
	public synchronized DataListener getDataListener() {
		return listener;
	}

	/**
	 * This indicates that no more data will be made available.
	 *

	 * Subsequent calls to push() will result in an
	 * IllegalStateException. Calling this method may immediately
	 * release new data (which you can access by calling
	 * pullImmediately).
	 *
	 * @see #push(int)
	 * @see #pull()
	 */
	@Override
	public synchronized void close() throws IOException {
		if (closed)
			return;

		flush();
		closed = true;
		if (listener != null)
			listener.encoderClosed(this);
		if (waiting > 0)
			notify();
	}

	/**
	 * Pull a series of bytes (all within [0,255]) as they become available.
	 *
	 * @return encoded bytes, or null if if close() has been
	 *         called.
	 *
	 * @see #pullImmediately()
	 * @see #push(int)
	 * @see #close()
	 */
	public synchronized int[] pull() throws IOException {
		while (outgoingData == null && (!closed)) {
			waiting++;
			try {
				wait();
			} catch (InterruptedException e) {
			} finally {
				waiting--;
			}

		}
		int[] returnValue = outgoingData;
		outgoingData = null;
		if (waiting > 0)
			notify();
		return returnValue;
	}

	/**
	 * Push a byte for this encoder to process.
	 *

	 * As data accumulates it will eventually have to be retrieved via the
	 * pull() method. This method may block if data is waiting to
	 * be retrieved.
	 *
	 * @param b
	 *            a byte from [0, 255]
	 *
	 * @see #pull()
	 * @see #close()
	 */
	public abstract void push(int b) throws IOException;

	/**
	 * This is exclusively called during close() to give this
	 * encoder an opportunity to write any remaining data.
	 */
	protected abstract void flush() throws IOException;

	private static final int[] EMPTY_ARRAY = new int[] {};

	/**
	 * This will return one of three things: an array of available bytes, an
	 * empty array if no data is available, or null if this encoder has been
	 * closed.
	 *
	 * @return One of three things: an array of available bytes, an empty array
	 *         if no data is available, or null if this encoder has been closed.
	 *
	 * @see #pull()
	 * @see #push(int)
	 * @see #close()
	 */
	public synchronized int[] pullImmediately() {
		int[] returnValue = outgoingData;
		outgoingData = null;
		if (returnValue == null && (!closed))
			return EMPTY_ARRAY;
		return returnValue;
	}

	private int[] outgoingData;

	/**
	 * Make a chunk of data available to be read. If there is any data that
	 * hasn't been processed yet, then this method may block until previously
	 * pushed chunks are cleared by calling {@link #pull()}.
	 *
	 * @param data
	 *            a chunk of data that is ready to be pulled.
	 */
	protected void pushChunk(int[] data) throws IOException {
		while (outgoingData != null) {
			waiting++;
			try {
				wait();
			} catch (InterruptedException e) {

			} finally {
				waiting--;
			}
		}
		outgoingData = data;
		if (listener != null)
			listener.chunkAvailable(this);
		if (waiting > 0)
			notify();
	}

	/**
	 * Encode a String using UTF-8.
	 *

	 * This breaks the String into an array of bytes, passes the bytes through
	 * this encoder, and returns the resulting bytes re-assembled in a String
	 * using UTF-8.
	 *
	 * @param string
	 *            the String to encode.
	 * @return the encoded String.
	 */
	public String encode(String string) {
		return encode(string, StandardCharsets.UTF_8);
	}

	/**
	 * Encode a String.
	 *

	 * This breaks the String into an array of bytes, passes the bytes through
	 * this encoder, and returns the resulting bytes re-assembled into a String.
	 *
	 * @param string
	 *            the String to encode.
	 * @param charset
	 *            the charset to convert the String to byte data.
	 * @return the encoded String.
	 */
	public String encode(String string, Charset charset) {
		byte[] data = string.getBytes(charset);
		data = encode(data);
		return new String(data, charset);
	}

	/**
	 * Encode an array of bytes.
	 *
	 * @param data
	 *            the bytes to encode.
	 * @return the encoded bytes.
	 */
	public byte[] encode(byte[] data) {
		try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(
				data.length)) {
			try (OutputStream out = createOutputStream(byteOut)) {
				out.write(data);
			}
			return byteOut.toByteArray();
		} catch (IOException e) {
			// this shouldn't happen if we're dealing in-memory IO.
			throw new RuntimeException(e);
		}
	}

	/**
	 * This filters an InputStream through this encoder.
	 */
	protected class EncodedInputStream extends InputStream {
		class Chunk {
			int[] data;
			int pos;

			public Chunk(int[] array) {
				data = new int[array.length];
				System.arraycopy(array, 0, data, 0, array.length);
			}
		}

		InputStream in;
		List<Chunk> chunks = new LinkedList<>();

		protected EncodedInputStream(InputStream in) throws IOException {
			this.in = in;
			setListener(new DataListener() {
				@Override
				public void chunkAvailable(ByteEncoder encoder)
						throws IOException {
					int[] array = encoder.pull();
					if (array.length != 0)
						chunks.add(new Chunk(array));
				}

				@Override
				public void encoderClosed(ByteEncoder encoder)
						throws IOException {
				}
			});
			queueNext();
		}

		int ctr = 0;

		private synchronized void queueNext() throws IOException {
			while (chunks.size() == 0) {
				int z = in.read();
				if (z == -1) {
					ByteEncoder.this.close();
					return;
				} else {
					push(z);
					ctr++;
				}
			}
		}

		@Override
		public synchronized int read() throws IOException {
			if (chunks.size() == 0)
				return -1;
			Chunk chunk = chunks.get(0);
			int value = chunk.data[chunk.pos++];
			if (chunk.pos == chunk.data.length) {
				chunks.remove(0);
			}
			if (chunks.size() == 0)
				queueNext();
			return value;
		}
	}

	/**
	 * Create an InputStrem that filters the argument's incoming data through
	 * this encoder.
	 *
	 * @param in
	 *            the InputStream to filter.
	 * @return the encoded InputStream.
	 */
	public synchronized InputStream createInputStream(InputStream in)
			throws IOException {
		return new EncodedInputStream(in);
	}

	/**
	 * Create an OutputStream that encodes the data as it is written to the
	 * underlying OutputStream.
	 *
	 * @param out
	 *            the OutputStream to write encoded data to.
	 * @return a stream that encodes data as it writes it to the underlying
	 *         OutputStream.
	 */
	public synchronized OutputStream createOutputStream(final OutputStream out) {
		setListener(new DataListener() {
			@Override
			public void chunkAvailable(ByteEncoder encoder) throws IOException {
				int[] chunk = encoder.pull();
				for (int a = 0; a < chunk.length; a++) {
					out.write(chunk[a]);
				}
			}

			@Override
			public void encoderClosed(ByteEncoder encoder) throws IOException {
			}
		});
		return new OutputStream() {
			@Override
			public void write(int b) throws IOException {
				push(b);
			}

			@Override
			public void close() throws IOException {
				super.close();
				ByteEncoder.this.close();
			}
		};
	}
}


text:
package org.copperengine.core.util;

public class Blocker {

    private volatile boolean blocked = false;
    private final Object mutex = new Object();

    public Blocker(boolean blocked) {
        this.blocked = blocked;
    }

    public void block() {
        synchronized (mutex) {
            blocked = true;
        }
    }

    public void unblock() {
        synchronized (mutex) {
            blocked = false;
            mutex.notifyAll();
        }
    }

    public void pass() throws InterruptedException {
        if (blocked) {
            synchronized (mutex) {
                while (blocked) {
                    mutex.wait();
                }
            }
        }
    }
}


text:
import { Component, OnInit } from '@angular/core';
import {Recipe} from '../../classes/recipe';
import {ModalDialogComponent} from '../modal-dialog/modal-dialog.component';
import {ActivatedRoute, Router} from '@angular/router';
import {AuthService} from '../../services/auth.service';
import {BrewContextService} from '../../services/brew-context.service';
import {DatabaseService} from '../../services/database.service';
import {MatDialog} from '@angular/material';
import {Beer} from '../../classes/beer';
import {CalculatorService} from '../../services/calculator.service';

@Component({
  selector: 'app-recipe-list',
  templateUrl: './recipe-list.component.html',
  styleUrls: ['./recipe-list.component.css']
})
export class RecipeListComponent implements OnInit {

  constructor(private router: Router,
              private route: ActivatedRoute,
              private authService: AuthService,
              public brewContext: BrewContextService,
              private dbService: DatabaseService,
              private calculatorService: CalculatorService,
              public dialog: MatDialog) {
    this.authService.authenticationEvent.subscribe( () => {
      this.findAllRecipes();
      this.getSetup();
    });
  }

  ngOnInit() {
    this.findAllRecipes();
    this.getSetup();
  }

  findAllRecipes() {
    if (this.authService.isAuthenticated()) {
      this.dbService.getAllRecipes().subscribe(
        recipes => {
          const parsedRecipes: Recipe[] = [];
          for (const ind in recipes) {
            const recipe = recipes[ind];
            const rcp = new Recipe();
            for (const idx in recipe) {
              rcp[idx] = recipe[idx];
            }
            if (!rcp.name || rcp.name === '') { rcp.name = 'noname recipe'; }
            parsedRecipes.push(rcp);
          }

          this.brewContext.userRecipes = parsedRecipes;
        },
        err => {
          console.log(err);
        }
      );
    }
  }

  editRecipe(recipe: Recipe) {
    this.brewContext.recipe = recipe;
    this.brewContext.setRecipe();
    const link = ['../calculator', recipe._id];
    this.router.navigate(link, {relativeTo: this.route});
  }

  newRecipe() {
    this.brewContext.recipe = new Recipe();
    this.brewContext.selectedMashName = null;
    this.brewContext.selectedStyleName = null;
    const link = ['../calculator'];
    this.router.navigate(link, {relativeTo: this.route});
  }

  getSetup() {
    if (this.authService.isAuthenticated()) {
      this.dbService.getBrewSetup().subscribe(bs => {
        this.brewContext.brewSetup = bs[0];
      });
    }
  }

  deleteRecipe(recipe: Recipe) {
    const dialogRef = this.dialog.open(ModalDialogComponent, {
      width: '600px',
      data: {description: 'Are you sure you want to delete this recipe?'}
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.brewContext.deleteRecipe(recipe);
      }
    });
  }

  getBeerColor(recipe: Recipe) {
    return this.calculatorService.getBeerColor(recipe.color);
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TradeHub.MarketDataProvider.Tradier.ValueObject
{
    /// <summary>
    /// Contains individual JSON elements received through streaming quotes
    /// </summary>
    public class QuoteStream
    {
        public string type { get; set; }
        public string symbol { get; set; }
        public string exch { get; set; }
        public string price { get; set; }
        public string size { get; set; }
        public string cvol { get; set; }
        public string date { get; set; }
        public string bid { get; set; }
        public string bidsz { get; set; }
        public string bidexch { get; set; }
        public string biddate { get; set; }
        public string ask { get; set; }
        public string asksz { get; set; }
        public string askexch { get; set; }
        public string askdate { get; set; }
        public string open { get; set; }
        public string high { get; set; }
        public string low { get; set; }
        public string prevClose { get; set; }
    }
}


text:
package net.finmath.montecarlo.interestrate;

import java.util.Map;

import net.finmath.exception.CalculationException;
import net.finmath.marketdata.model.AnalyticModel;
import net.finmath.marketdata.model.curves.DiscountCurve;
import net.finmath.marketdata.model.curves.ForwardCurve;
import net.finmath.montecarlo.model.ProcessModel;
import net.finmath.montecarlo.process.MonteCarloProcess;
import net.finmath.stochastic.RandomVariable;

/**
 * @author Christian Fries
 *
 * @version 1.0
 */
public interface TermStructureModel extends ProcessModel {

	/**
	 * Returns the time \( t \) forward rate on the models forward curve.
	 *
	 * Note: It is guaranteed that the random variable returned by this method is \( \mathcal{F}_{t} ) \)-measurable.
	 *
	 * @param process The discretization process generating this model. The process provides call backs for TimeDiscretization and allows calls to getProcessValue for timeIndices less or equal the given one.
	 * @param time The evaluation time.
	 * @param periodStart The period start of the forward rate.
	 * @param periodEnd The period end of the forward rate.
	 * @return The forward rate.
	 * @throws CalculationException Thrown if model fails to calculate the random variable.
	 */
	RandomVariable getForwardRate(MonteCarloProcess process, double time, double periodStart, double periodEnd) throws CalculationException;

	/**
	 * Returns the time \( t \) forward bond derived from the numeraire, i.e., \( P(T;t) = E( \frac{N(t)}{N(T)} \vert \mathcal{F}_{t} ) \).
	 *
	 * Note: It is guaranteed that the random variabble returned by this method is \( \mathcal{F}_{t} ) \)-measurable.
	 *
	 * @param process The discretization process generating this model. The process provides call backs for TimeDiscretization and allows calls to getProcessValue for timeIndices less or equal the given one.
	 * @param time The evaluation time.
	 * @param maturity The maturity.
	 * @return The forward bond P(T;t).
	 * @throws CalculationException Thrown if model fails to calculate the random variable.
	 */
	default RandomVariable getForwardDiscountBond(MonteCarloProcess process, final double time, final double maturity) throws CalculationException {
		throw new UnsupportedOperationException("The model does not support this method. Note: implemenation will become mandatory is future releases.");
	}

	/**
	 * Return the associated analytic model, a collection of market date object like discount curve, forward curve
	 * and volatility surfaces.
	 *
	 * @return The associated analytic model.
	 */
	AnalyticModel getAnalyticModel();

	/**
	 * Return the discount curve associated the forwards.
	 *
	 * @return the discount curve associated the forwards.
	 */
	DiscountCurve getDiscountCurve();

	/**
	 * Return the initial forward rate curve.
	 *
	 * @return the forward rate curve
	 */
	ForwardCurve getForwardRateCurve();

	/*+
	 * Returns the term structure covariance model.
	 *
	 * @return the term structure covariance model.
	 */
	//	TermStructureCovarianceModelInterface getCovarianceModel();

	/**
	 * Create a new object implementing TermStructureModel, using the new data.
	 *
	 * @param dataModified A map with values to be used in constructions (keys are identical to parameter names of the constructors).
	 * @return A new object implementing TermStructureModel, using the new data.
	 * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the cause() method.
	 */
	@Override
	TermStructureModel getCloneWithModifiedData(Map<String, Object> dataModified) throws CalculationException;

	/**
	 * Returns the time \( t \) forward rate on the models forward curve.
	 *
	 * Note: It is guaranteed that the random variable returned by this method is \( \mathcal{F}_{t} ) \)-measurable.
	 *
	 * @param process The discretization process generating this model. The process provides call backs for TimeDiscretization and allows calls to getProcessValue for timeIndices less or equal the given one.
	 * @param time The evaluation time.
	 * @param periodStart The period start of the forward rate.
	 * @param periodEnd The period end of the forward rate.
	 * @return The forward rate.
	 * @throws CalculationException Thrown if model fails to calculate the random variable.
	 */
	default RandomVariable getLIBOR(MonteCarloProcess process, double time, double periodStart, double periodEnd) throws CalculationException {
		return getForwardRate(process, time, periodStart, periodEnd);
	}
}


text:
Basic test for posix_clock_gettime()
--SKIPIF--
<?php if (!extension_loaded("posixrealtime")) print "skip"; ?>
--FILE--
<?php
var_dump(function_exists('posix_clock_gettime'));

var_dump(posix_clock_gettime());

--EXPECTF--
bool(true)
string(%d) "%d.%d"