text:
#include <linux/swap.h>
#include <linux/migrate.h>
#include <linux/compaction.h>
#include <linux/mm_inline.h>
#include <linux/backing-dev.h>
#include <linux/sysctl.h>
#include <linux/sysfs.h>
#include <linux/balloon_compaction.h>
#include <linux/page-isolation.h>
#include "internal.h"

#ifdef CONFIG_COMPACTION
static inline void count_compact_event(enum vm_event_item item)
{
	count_vm_event(item);
}

static inline void count_compact_events(enum vm_event_item item, long delta)
{
	count_vm_events(item, delta);
}
#else
#define count_compact_event(item) do { } while (0)
#define count_compact_events(item, delta) do { } while (0)
#endif

#if defined CONFIG_COMPACTION || defined CONFIG_CMA

#define CREATE_TRACE_POINTS
#include <trace/events/compaction.h>

static unsigned long release_freepages(struct list_head *freelist)
{
	struct page *page, *next;
	unsigned long count = 0;

	list_for_each_entry_safe(page, next, freelist, lru) {
		list_del(&page->lru);
		__free_page(page);
		count++;
	}

	return count;
}

static void map_pages(struct list_head *list)
{
	struct page *page;

	list_for_each_entry(page, list, lru) {
		arch_alloc_page(page, 0);
		kernel_map_pages(page, 1, 1);
	}
}

static inline bool migrate_async_suitable(int migratetype)
{
	return is_migrate_cma(migratetype) || migratetype == MIGRATE_MOVABLE;
}

#ifdef CONFIG_COMPACTION
/* Returns true if the pageblock should be scanned for pages to isolate. */
static inline bool isolation_suitable(struct compact_control *cc,
					struct page *page)
{
	if (cc->ignore_skip_hint)
		return true;

	return !get_pageblock_skip(page);
}

/*
 * This function is called to clear all cached information on pageblocks that
 * should be skipped for page isolation when the migrate and free page scanner
 * meet.
 */
static void __reset_isolation_suitable(struct zone *zone)
{
	unsigned long start_pfn = zone->zone_start_pfn;
	unsigned long end_pfn = zone_end_pfn(zone);
	unsigned long pfn;

	zone->compact_cached_migrate_pfn = start_pfn;
	zone->compact_cached_free_pfn = end_pfn;
	zone->compact_blockskip_flush = false;

	/* Walk the zone and mark every pageblock as suitable for isolation */
	for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
		struct page *page;

		cond_resched();

		if (!pfn_valid(pfn))
			continue;

		page = pfn_to_page(pfn);
		if (zone != page_zone(page))
			continue;

		clear_pageblock_skip(page);
	}
}

void reset_isolation_suitable(pg_data_t *pgdat)
{
	int zoneid;

	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
		struct zone *zone = &pgdat->node_zones[zoneid];
		if (!populated_zone(zone))
			continue;

		/* Only flush if a full compaction finished recently */
		if (zone->compact_blockskip_flush)
			__reset_isolation_suitable(zone);
	}
}

/*
 * If no pages were isolated then mark this pageblock to be skipped in the
 * future. The information is later cleared by __reset_isolation_suitable().
 */
static void update_pageblock_skip(struct compact_control *cc,
			struct page *page, unsigned long nr_isolated,
			bool migrate_scanner)
{
	struct zone *zone = cc->zone;

	if (cc->ignore_skip_hint)
		return;

	if (!page)
		return;

	if (!nr_isolated) {
		unsigned long pfn = page_to_pfn(page);
		set_pageblock_skip(page);

		/* Update where compaction should restart */
		if (migrate_scanner) {
			if (!cc->finished_update_migrate &&
			    pfn > zone->compact_cached_migrate_pfn)
				zone->compact_cached_migrate_pfn = pfn;
		} else {
			if (!cc->finished_update_free &&
			    pfn < zone->compact_cached_free_pfn)
				zone->compact_cached_free_pfn = pfn;
		}
	}
}
#else
static inline bool isolation_suitable(struct compact_control *cc,
					struct page *page)
{
	return true;
}

static void update_pageblock_skip(struct compact_control *cc,
			struct page *page, unsigned long nr_isolated,
			bool migrate_scanner)
{
}
#endif /* CONFIG_COMPACTION */

static inline bool should_release_lock(spinlock_t *lock)
{
	return need_resched() || spin_is_contended(lock);
}

/*
 * Compaction requires the taking of some coarse locks that are potentially
 * very heavily contended. Check if the process needs to be scheduled or
 * if the lock is contended. For async compaction, back out in the event
 * if contention is severe. For sync compaction, schedule.
 *
 * Returns true if the lock is held.
 * Returns false if the lock is released and compaction should abort
 */
static bool compact_checklock_irqsave(spinlock_t *lock, unsigned long *flags,
				      bool locked, struct compact_control *cc)
{
	if (should_release_lock(lock)) {
		if (locked) {
			spin_unlock_irqrestore(lock, *flags);
			locked = false;
		}

		/* async aborts if taking too long or contended */
		if (!cc->sync) {
			cc->contended = true;
			return false;
		}

		cond_resched();
	}

	if (!locked)
		spin_lock_irqsave(lock, *flags);
	return true;
}

static inline bool compact_trylock_irqsave(spinlock_t *lock,
			unsigned long *flags, struct compact_control *cc)
{
	return compact_checklock_irqsave(lock, flags, false, cc);
}

/* Returns true if the page is within a block suitable for migration to */
static bool suitable_migration_target(struct page *page)
{
	int migratetype = get_pageblock_migratetype(page);

	/* Don't interfere with memory hot-remove or the min_free_kbytes blocks */
	if (migratetype == MIGRATE_RESERVE)
		return false;

	if (is_migrate_isolate(migratetype))
		return false;

	/* If the page is a large free page, then allow migration */
	if (PageBuddy(page) && page_order(page) >= pageblock_order)
		return true;

	/* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
	if (migrate_async_suitable(migratetype))
		return true;

	/* Otherwise skip the block */
	return false;
}

/*
 * Isolate free pages onto a private freelist. Caller must hold zone->lock.
 * If @strict is true, will abort returning 0 on any invalid PFNs or non-free
 * pages inside of the pageblock (even though it may still end up isolating
 * some pages).
 */
static unsigned long isolate_freepages_block(struct compact_control *cc,
				unsigned long blockpfn,
				unsigned long end_pfn,
				struct list_head *freelist,
				bool strict)
{
	int nr_scanned = 0, total_isolated = 0;
	struct page *cursor, *valid_page = NULL;
	unsigned long flags;
	bool locked = false;

	cursor = pfn_to_page(blockpfn);

	/* Isolate free pages. */
	for (; blockpfn < end_pfn; blockpfn++, cursor++) {
		int isolated, i;
		struct page *page = cursor;

		nr_scanned++;
		if (!pfn_valid_within(blockpfn))
			goto isolate_fail;

		if (!valid_page)
			valid_page = page;
		if (!PageBuddy(page))
			goto isolate_fail;

		/*
		 * The zone lock must be held to isolate freepages.
		 * Unfortunately this is a very coarse lock and can be
		 * heavily contended if there are parallel allocations
		 * or parallel compactions. For async compaction do not
		 * spin on the lock and we acquire the lock as late as
		 * possible.
		 */
		locked = compact_checklock_irqsave(&cc->zone->lock, &flags,
								locked, cc);
		if (!locked)
			break;

		/* Recheck this is a suitable migration target under lock */
		if (!strict && !suitable_migration_target(page))
			break;

		/* Recheck this is a buddy page under lock */
		if (!PageBuddy(page))
			goto isolate_fail;

		/* Found a free page, break it into order-0 pages */
		isolated = split_free_page(page);
		total_isolated += isolated;
		for (i = 0; i < isolated; i++) {
			list_add(&page->lru, freelist);
			page++;
		}

		/* If a page was split, advance to the end of it */
		if (isolated) {
			blockpfn += isolated - 1;
			cursor += isolated - 1;
			continue;
		}

isolate_fail:
		if (strict)
			break;
		else
			continue;

	}

	trace_mm_compaction_isolate_freepages(nr_scanned, total_isolated);

	/*
	 * If strict isolation is requested by CMA then check that all the
	 * pages requested were isolated. If there were any failures, 0 is
	 * returned and CMA will fail.
	 */
	if (strict && blockpfn < end_pfn)
		total_isolated = 0;

	if (locked)
		spin_unlock_irqrestore(&cc->zone->lock, flags);

	/* Update the pageblock-skip if the whole pageblock was scanned */
	if (blockpfn == end_pfn)
		update_pageblock_skip(cc, valid_page, total_isolated, false);

	count_compact_events(COMPACTFREE_SCANNED, nr_scanned);
	if (total_isolated)
		count_compact_events(COMPACTISOLATED, total_isolated);
	return total_isolated;
}

/**
 * isolate_freepages_range() - isolate free pages.
 * @start_pfn: The first PFN to start isolating.
 * @end_pfn:   The one-past-last PFN.
 *
 * Non-free pages, invalid PFNs, or zone boundaries within the
 * [start_pfn, end_pfn) range are considered errors, cause function to
 * undo its actions and return zero.
 *
 * Otherwise, function returns one-past-the-last PFN of isolated page
 * (which may be greater then end_pfn if end fell in a middle of
 * a free page).
 */
unsigned long
isolate_freepages_range(struct compact_control *cc,
			unsigned long start_pfn, unsigned long end_pfn)
{
	unsigned long isolated, pfn, block_end_pfn;
	LIST_HEAD(freelist);

	for (pfn = start_pfn; pfn < end_pfn; pfn += isolated) {
		if (!pfn_valid(pfn) || cc->zone != page_zone(pfn_to_page(pfn)))
			break;

		/*
		 * On subsequent iterations ALIGN() is actually not needed,
		 * but we keep it that we not to complicate the code.
		 */
		block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
		block_end_pfn = min(block_end_pfn, end_pfn);

		isolated = isolate_freepages_block(cc, pfn, block_end_pfn,
						   &freelist, true);

		/*
		 * In strict mode, isolate_freepages_block() returns 0 if
		 * there are any holes in the block (ie. invalid PFNs or
		 * non-free pages).
		 */
		if (!isolated)
			break;

		/*
		 * If we managed to isolate pages, it is always (1 << n) *
		 * pageblock_nr_pages for some non-negative n.  (Max order
		 * page may span two pageblocks).
		 */
	}

	/* split_free_page does not map the pages */
	map_pages(&freelist);

	if (pfn < end_pfn) {
		/* Loop terminated early, cleanup. */
		release_freepages(&freelist);
		return 0;
	}

	/* We don't use freelists for anything. */
	return pfn;
}

/* Update the number of anon and file isolated pages in the zone */
static void acct_isolated(struct zone *zone, bool locked, struct compact_control *cc)
{
	struct page *page;
	unsigned int count[2] = { 0, };

	list_for_each_entry(page, &cc->migratepages, lru)
		count[!!page_is_file_cache(page)]++;

	/* If locked we can use the interrupt unsafe versions */
	if (locked) {
		__mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
		__mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
	} else {
		mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
		mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
	}
}

/* Similar to reclaim, but different enough that they don't share logic */
static bool too_many_isolated(struct zone *zone)
{
	unsigned long active, inactive, isolated;

	inactive = zone_page_state(zone, NR_INACTIVE_FILE) +
					zone_page_state(zone, NR_INACTIVE_ANON);
	active = zone_page_state(zone, NR_ACTIVE_FILE) +
					zone_page_state(zone, NR_ACTIVE_ANON);
	isolated = zone_page_state(zone, NR_ISOLATED_FILE) +
					zone_page_state(zone, NR_ISOLATED_ANON);

	return isolated > (inactive + active) / 2;
}

/**
 * isolate_migratepages_range() - isolate all migrate-able pages in range.
 * @zone:	Zone pages are in.
 * @cc:		Compaction control structure.
 * @low_pfn:	The first PFN of the range.
 * @end_pfn:	The one-past-the-last PFN of the range.
 * @unevictable: true if it allows to isolate unevictable pages
 *
 * Isolate all pages that can be migrated from the range specified by
 * [low_pfn, end_pfn).  Returns zero if there is a fatal signal
 * pending), otherwise PFN of the first page that was not scanned
 * (which may be both less, equal to or more then end_pfn).
 *
 * Assumes that cc->migratepages is empty and cc->nr_migratepages is
 * zero.
 *
 * Apart from cc->migratepages and cc->nr_migratetypes this function
 * does not modify any cc's fields, in particular it does not modify
 * (or read for that matter) cc->migrate_pfn.
 */
unsigned long
isolate_migratepages_range(struct zone *zone, struct compact_control *cc,
		unsigned long low_pfn, unsigned long end_pfn, bool unevictable)
{
	unsigned long last_pageblock_nr = 0, pageblock_nr;
	unsigned long nr_scanned = 0, nr_isolated = 0;
	struct list_head *migratelist = &cc->migratepages;
	isolate_mode_t mode = 0;
	struct lruvec *lruvec;
	unsigned long flags;
	bool locked = false;
	struct page *page = NULL, *valid_page = NULL;

	/*
	 * Ensure that there are not too many pages isolated from the LRU
	 * list by either parallel reclaimers or compaction. If there are,
	 * delay for some time until fewer pages are isolated
	 */
	while (unlikely(too_many_isolated(zone))) {
		/* async migration should just abort */
		if (!cc->sync)
			return 0;

		congestion_wait(BLK_RW_ASYNC, HZ/10);

		if (fatal_signal_pending(current))
			return 0;
	}

	/* Time to isolate some pages for migration */
	cond_resched();
	for (; low_pfn < end_pfn; low_pfn++) {
		/* give a chance to irqs before checking need_resched() */
		if (locked && !((low_pfn+1) % SWAP_CLUSTER_MAX)) {
			if (should_release_lock(&zone->lru_lock)) {
				spin_unlock_irqrestore(&zone->lru_lock, flags);
				locked = false;
			}
		}

		/*
		 * migrate_pfn does not necessarily start aligned to a
		 * pageblock. Ensure that pfn_valid is called when moving
		 * into a new MAX_ORDER_NR_PAGES range in case of large
		 * memory holes within the zone
		 */
		if ((low_pfn & (MAX_ORDER_NR_PAGES - 1)) == 0) {
			if (!pfn_valid(low_pfn)) {
				low_pfn += MAX_ORDER_NR_PAGES - 1;
				continue;
			}
		}

		if (!pfn_valid_within(low_pfn))
			continue;
		nr_scanned++;

		/*
		 * Get the page and ensure the page is within the same zone.
		 * See the comment in isolate_freepages about overlapping
		 * nodes. It is deliberate that the new zone lock is not taken
		 * as memory compaction should not move pages between nodes.
		 */
		page = pfn_to_page(low_pfn);
		if (page_zone(page) != zone)
			continue;

		if (!valid_page)
			valid_page = page;

		/* If isolation recently failed, do not retry */
		pageblock_nr = low_pfn >> pageblock_order;
		if (!isolation_suitable(cc, page))
			goto next_pageblock;

		/* Skip if free */
		if (PageBuddy(page))
			continue;

		/*
		 * For async migration, also only scan in MOVABLE blocks. Async
		 * migration is optimistic to see if the minimum amount of work
		 * satisfies the allocation
		 */
		if (!cc->sync && last_pageblock_nr != pageblock_nr &&
		    !migrate_async_suitable(get_pageblock_migratetype(page))) {
			cc->finished_update_migrate = true;
			goto next_pageblock;
		}

		/*
		 * Check may be lockless but that's ok as we recheck later.
		 * It's possible to migrate LRU pages and balloon pages
		 * Skip any other type of page
		 */
		if (!PageLRU(page)) {
			if (unlikely(balloon_page_movable(page))) {
				if (locked && balloon_page_isolate(page)) {
					/* Successfully isolated */
					cc->finished_update_migrate = true;
					list_add(&page->lru, migratelist);
					cc->nr_migratepages++;
					nr_isolated++;
					goto check_compact_cluster;
				}
			}
			continue;
		}

		/*
		 * PageLRU is set. lru_lock normally excludes isolation
		 * splitting and collapsing (collapsing has already happened
		 * if PageLRU is set) but the lock is not necessarily taken
		 * here and it is wasteful to take it just to check transhuge.
		 * Check TransHuge without lock and skip the whole pageblock if
		 * it's either a transhuge or hugetlbfs page, as calling
		 * compound_order() without preventing THP from splitting the
		 * page underneath us may return surprising results.
		 */
		if (PageTransHuge(page)) {
			if (!locked)
				goto next_pageblock;
			low_pfn += (1 << compound_order(page)) - 1;
			continue;
		}

		/* Check if it is ok to still hold the lock */
		locked = compact_checklock_irqsave(&zone->lru_lock, &flags,
								locked, cc);
		if (!locked || fatal_signal_pending(current))
			break;

		/* Recheck PageLRU and PageTransHuge under lock */
		if (!PageLRU(page))
			continue;
		if (PageTransHuge(page)) {
			low_pfn += (1 << compound_order(page)) - 1;
			continue;
		}

		if (!cc->sync)
			mode |= ISOLATE_ASYNC_MIGRATE;

		if (unevictable)
			mode |= ISOLATE_UNEVICTABLE;

		lruvec = mem_cgroup_page_lruvec(page, zone);

		/* Try isolate the page */
		if (__isolate_lru_page(page, mode) != 0)
			continue;

		VM_BUG_ON(PageTransCompound(page));

		/* Successfully isolated */
		cc->finished_update_migrate = true;
		del_page_from_lru_list(page, lruvec, page_lru(page));
		list_add(&page->lru, migratelist);
		cc->nr_migratepages++;
		nr_isolated++;

check_compact_cluster:
		/* Avoid isolating too much */
		if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
			++low_pfn;
			break;
		}

		continue;

next_pageblock:
		low_pfn = ALIGN(low_pfn + 1, pageblock_nr_pages) - 1;
		last_pageblock_nr = pageblock_nr;
	}

	acct_isolated(zone, locked, cc);

	if (locked)
		spin_unlock_irqrestore(&zone->lru_lock, flags);

	/* Update the pageblock-skip if the whole pageblock was scanned */
	if (low_pfn == end_pfn)
		update_pageblock_skip(cc, valid_page, nr_isolated, true);

	trace_mm_compaction_isolate_migratepages(nr_scanned, nr_isolated);

	count_compact_events(COMPACTMIGRATE_SCANNED, nr_scanned);
	if (nr_isolated)
		count_compact_events(COMPACTISOLATED, nr_isolated);

	return low_pfn;
}

#endif /* CONFIG_COMPACTION || CONFIG_CMA */
#ifdef CONFIG_COMPACTION
/*
 * Based on information in the current compact_control, find blocks
 * suitable for isolating free pages from and then isolate them.
 */
static void isolate_freepages(struct zone *zone,
				struct compact_control *cc)
{
	struct page *page;
	unsigned long high_pfn, low_pfn, pfn, z_end_pfn;
	int nr_freepages = cc->nr_freepages;
	struct list_head *freelist = &cc->freepages;

	/*
	 * Initialise the free scanner. The starting point is where we last
	 * successfully isolated from, zone-cached value, or the end of the
	 * zone when isolating for the first time. We need this aligned to
	 * the pageblock boundary, because we do pfn -= pageblock_nr_pages
	 * in the for loop.
	 * The low boundary is the end of the pageblock the migration scanner
	 * is using.
	 */
	pfn = cc->free_pfn & ~(pageblock_nr_pages-1);
	low_pfn = ALIGN(cc->migrate_pfn + 1, pageblock_nr_pages);

	/*
	 * Take care that if the migration scanner is at the end of the zone
	 * that the free scanner does not accidentally move to the next zone
	 * in the next isolation cycle.
	 */
	high_pfn = min(low_pfn, pfn);

	z_end_pfn = zone_end_pfn(zone);

	/*
	 * Isolate free pages until enough are available to migrate the
	 * pages on cc->migratepages. We stop searching if the migrate
	 * and free page scanners meet or enough free pages are isolated.
	 */
	for (; pfn >= low_pfn && cc->nr_migratepages > nr_freepages;
					pfn -= pageblock_nr_pages) {
		unsigned long isolated;
		unsigned long end_pfn;

		if (!pfn_valid(pfn))
			continue;

		/*
		 * Check for overlapping nodes/zones. It's possible on some
		 * configurations to have a setup like
		 * node0 node1 node0
		 * i.e. it's possible that all pages within a zones range of
		 * pages do not belong to a single zone.
		 */
		page = pfn_to_page(pfn);
		if (page_zone(page) != zone)
			continue;

		/* Check the block is suitable for migration */
		if (!suitable_migration_target(page))
			continue;

		/* If isolation recently failed, do not retry */
		if (!isolation_suitable(cc, page))
			continue;

		/* Found a block suitable for isolating free pages from */
		isolated = 0;

		/*
		 * Take care when isolating in last pageblock of a zone which
		 * ends in the middle of a pageblock.
		 */
		end_pfn = min(pfn + pageblock_nr_pages, z_end_pfn);
		isolated = isolate_freepages_block(cc, pfn, end_pfn,
						   freelist, false);
		nr_freepages += isolated;

		/*
		 * Record the highest PFN we isolated pages from. When next
		 * looking for free pages, the search will restart here as
		 * page migration may have returned some pages to the allocator
		 */
		if (isolated) {
			cc->finished_update_free = true;
			high_pfn = max(high_pfn, pfn);
		}
	}

	/* split_free_page does not map the pages */
	map_pages(freelist);

	/*
	 * If we crossed the migrate scanner, we want to keep it that way
	 * so that compact_finished() may detect this
	 */
	if (pfn < low_pfn)
		cc->free_pfn = max(pfn, zone->zone_start_pfn);
	else
		cc->free_pfn = high_pfn;
	cc->nr_freepages = nr_freepages;
}

/*
 * This is a migrate-callback that "allocates" freepages by taking pages
 * from the isolated freelists in the block we are migrating to.
 */
static struct page *compaction_alloc(struct page *migratepage,
					unsigned long data,
					int **result)
{
	struct compact_control *cc = (struct compact_control *)data;
	struct page *freepage;

	/* Isolate free pages if necessary */
	if (list_empty(&cc->freepages)) {
		isolate_freepages(cc->zone, cc);

		if (list_empty(&cc->freepages))
			return NULL;
	}

	freepage = list_entry(cc->freepages.next, struct page, lru);
	list_del(&freepage->lru);
	cc->nr_freepages--;

	return freepage;
}

/*
 * We cannot control nr_migratepages and nr_freepages fully when migration is
 * running as migrate_pages() has no knowledge of compact_control. When
 * migration is complete, we count the number of pages on the lists by hand.
 */
static void update_nr_listpages(struct compact_control *cc)
{
	int nr_migratepages = 0;
	int nr_freepages = 0;
	struct page *page;

	list_for_each_entry(page, &cc->migratepages, lru)
		nr_migratepages++;
	list_for_each_entry(page, &cc->freepages, lru)
		nr_freepages++;

	cc->nr_migratepages = nr_migratepages;
	cc->nr_freepages = nr_freepages;
}

/* possible outcome of isolate_migratepages */
typedef enum {
	ISOLATE_ABORT,		/* Abort compaction now */
	ISOLATE_NONE,		/* No pages isolated, continue scanning */
	ISOLATE_SUCCESS,	/* Pages isolated, migrate */
} isolate_migrate_t;

/*
 * Isolate all pages that can be migrated from the block pointed to by
 * the migrate scanner within compact_control.
 */
static isolate_migrate_t isolate_migratepages(struct zone *zone,
					struct compact_control *cc)
{
	unsigned long low_pfn, end_pfn;

	/* Do not scan outside zone boundaries */
	low_pfn = max(cc->migrate_pfn, zone->zone_start_pfn);

	/* Only scan within a pageblock boundary */
	end_pfn = ALIGN(low_pfn + 1, pageblock_nr_pages);

	/* Do not cross the free scanner or scan within a memory hole */
	if (end_pfn > cc->free_pfn || !pfn_valid(low_pfn)) {
		cc->migrate_pfn = end_pfn;
		return ISOLATE_NONE;
	}

	/* Perform the isolation */
	low_pfn = isolate_migratepages_range(zone, cc, low_pfn, end_pfn, false);
	if (!low_pfn || cc->contended)
		return ISOLATE_ABORT;

	cc->migrate_pfn = low_pfn;

	return ISOLATE_SUCCESS;
}

static int compact_finished(struct zone *zone,
			    struct compact_control *cc)
{
	unsigned int order;
	unsigned long watermark;

	if (fatal_signal_pending(current))
		return COMPACT_PARTIAL;

	/* Compaction run completes if the migrate and free scanner meet */
	if (cc->free_pfn <= cc->migrate_pfn) {
		/*
		 * Mark that the PG_migrate_skip information should be cleared
		 * by kswapd when it goes to sleep. kswapd does not set the
		 * flag itself as the decision to be clear should be directly
		 * based on an allocation request.
		 */
		if (!current_is_kswapd())
			zone->compact_blockskip_flush = true;

		return COMPACT_COMPLETE;
	}

	/*
	 * order == -1 is expected when compacting via
	 * /proc/sys/vm/compact_memory
	 */
	if (cc->order == -1)
		return COMPACT_CONTINUE;

	/* Compaction run is not finished if the watermark is not met */
	watermark = low_wmark_pages(zone);
	watermark += (1 << cc->order);

	if (!zone_watermark_ok(zone, cc->order, watermark, 0, 0))
		return COMPACT_CONTINUE;

	/* Direct compactor: Is a suitable page free? */
	for (order = cc->order; order < MAX_ORDER; order++) {
		struct free_area *area = &zone->free_area[order];

		/* Job done if page is free of the right migratetype */
		if (!list_empty(&area->free_list[cc->migratetype]))
			return COMPACT_PARTIAL;

		/* Job done if allocation would set block type */
		if (cc->order >= pageblock_order && area->nr_free)
			return COMPACT_PARTIAL;
	}

	return COMPACT_CONTINUE;
}

/*
 * compaction_suitable: Is this suitable to run compaction on this zone now?
 * Returns
 *   COMPACT_SKIPPED  - If there are too few free pages for compaction
 *   COMPACT_PARTIAL  - If the allocation would succeed without compaction
 *   COMPACT_CONTINUE - If compaction should run now
 */
unsigned long compaction_suitable(struct zone *zone, int order)
{
	int fragindex;
	unsigned long watermark;

	/*
	 * order == -1 is expected when compacting via
	 * /proc/sys/vm/compact_memory
	 */
	if (order == -1)
		return COMPACT_CONTINUE;

	/*
	 * Watermarks for order-0 must be met for compaction. Note the 2UL.
	 * This is because during migration, copies of pages need to be
	 * allocated and for a short time, the footprint is higher
	 */
	watermark = low_wmark_pages(zone) + (2UL << order);
	if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
		return COMPACT_SKIPPED;

	/*
	 * fragmentation index determines if allocation failures are due to
	 * low memory or external fragmentation
	 *
	 * index of -1000 implies allocations might succeed depending on
	 * watermarks
	 * index towards 0 implies failure is due to lack of memory
	 * index towards 1000 implies failure is due to fragmentation
	 *
	 * Only compact if a failure would be due to fragmentation.
	 */
	fragindex = fragmentation_index(zone, order);
	if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
		return COMPACT_SKIPPED;

	if (fragindex == -1000 && zone_watermark_ok(zone, order, watermark,
	    0, 0))
		return COMPACT_PARTIAL;

	return COMPACT_CONTINUE;
}

static int compact_zone(struct zone *zone, struct compact_control *cc)
{
	int ret;
	unsigned long start_pfn = zone->zone_start_pfn;
	unsigned long end_pfn = zone_end_pfn(zone);

	ret = compaction_suitable(zone, cc->order);
	switch (ret) {
	case COMPACT_PARTIAL:
	case COMPACT_SKIPPED:
		/* Compaction is likely to fail */
		return ret;
	case COMPACT_CONTINUE:
		/* Fall through to compaction */
		;
	}

	/*
	 * Clear pageblock skip if there were failures recently and compaction
	 * is about to be retried after being deferred. kswapd does not do
	 * this reset as it'll reset the cached information when going to sleep.
	 */
	if (compaction_restarting(zone, cc->order) && !current_is_kswapd())
		__reset_isolation_suitable(zone);

	/*
	 * Setup to move all movable pages to the end of the zone. Used cached
	 * information on where the scanners should start but check that it
	 * is initialised by ensuring the values are within zone boundaries.
	 */
	cc->migrate_pfn = zone->compact_cached_migrate_pfn;
	cc->free_pfn = zone->compact_cached_free_pfn;
	if (cc->free_pfn < start_pfn || cc->free_pfn > end_pfn) {
		cc->free_pfn = end_pfn & ~(pageblock_nr_pages-1);
		zone->compact_cached_free_pfn = cc->free_pfn;
	}
	if (cc->migrate_pfn < start_pfn || cc->migrate_pfn > end_pfn) {
		cc->migrate_pfn = start_pfn;
		zone->compact_cached_migrate_pfn = cc->migrate_pfn;
	}

	migrate_prep_local();

	while ((ret = compact_finished(zone, cc)) == COMPACT_CONTINUE) {
		unsigned long nr_migrate, nr_remaining;
		int err;

		switch (isolate_migratepages(zone, cc)) {
		case ISOLATE_ABORT:
			ret = COMPACT_PARTIAL;
			putback_movable_pages(&cc->migratepages);
			cc->nr_migratepages = 0;
			goto out;
		case ISOLATE_NONE:
			continue;
		case ISOLATE_SUCCESS:
			;
		}

		nr_migrate = cc->nr_migratepages;
		err = migrate_pages(&cc->migratepages, compaction_alloc,
				(unsigned long)cc,
				cc->sync ? MIGRATE_SYNC_LIGHT : MIGRATE_ASYNC,
				MR_COMPACTION);
		update_nr_listpages(cc);
		nr_remaining = cc->nr_migratepages;

		trace_mm_compaction_migratepages(nr_migrate - nr_remaining,
						nr_remaining);

		/* Release isolated pages not migrated */
		if (err) {
			putback_movable_pages(&cc->migratepages);
			cc->nr_migratepages = 0;
			/*
			 * migrate_pages() may return -ENOMEM when scanners meet
			 * and we want compact_finished() to detect it
			 */
			if (err == -ENOMEM && cc->free_pfn > cc->migrate_pfn) {
				ret = COMPACT_PARTIAL;
				goto out;
			}
		}
	}

out:
	/* Release free pages and check accounting */
	cc->nr_freepages -= release_freepages(&cc->freepages);
	VM_BUG_ON(cc->nr_freepages != 0);

	return ret;
}

static unsigned long compact_zone_order(struct zone *zone,
				 int order, gfp_t gfp_mask,
				 bool sync, bool *contended)
{
	unsigned long ret;
	struct compact_control cc = {
		.nr_freepages = 0,
		.nr_migratepages = 0,
		.order = order,
		.migratetype = allocflags_to_migratetype(gfp_mask),
		.zone = zone,
		.sync = sync,
	};
	INIT_LIST_HEAD(&cc.freepages);
	INIT_LIST_HEAD(&cc.migratepages);

	ret = compact_zone(zone, &cc);

	VM_BUG_ON(!list_empty(&cc.freepages));
	VM_BUG_ON(!list_empty(&cc.migratepages));

	*contended = cc.contended;
	return ret;
}

int sysctl_extfrag_threshold = 500;

/**
 * try_to_compact_pages - Direct compact to satisfy a high-order allocation
 * @zonelist: The zonelist used for the current allocation
 * @order: The order of the current allocation
 * @gfp_mask: The GFP mask of the current allocation
 * @nodemask: The allowed nodes to allocate from
 * @sync: Whether migration is synchronous or not
 * @contended: Return value that is true if compaction was aborted due to lock contention
 * @page: Optionally capture a free page of the requested order during compaction
 *
 * This is the main entry point for direct page compaction.
 */
unsigned long try_to_compact_pages(struct zonelist *zonelist,
			int order, gfp_t gfp_mask, nodemask_t *nodemask,
			bool sync, bool *contended)
{
	enum zone_type high_zoneidx = gfp_zone(gfp_mask);
	int may_enter_fs = gfp_mask & __GFP_FS;
	int may_perform_io = gfp_mask & __GFP_IO;
	struct zoneref *z;
	struct zone *zone;
	int rc = COMPACT_SKIPPED;
	int alloc_flags = 0;

	/* Check if the GFP flags allow compaction */
	if (!order || !may_enter_fs || !may_perform_io)
		return rc;

	count_compact_event(COMPACTSTALL);

#ifdef CONFIG_CMA
	if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
		alloc_flags |= ALLOC_CMA;
#endif
	/* Compact each zone in the list */
	for_each_zone_zonelist_nodemask(zone, z, zonelist, high_zoneidx,
								nodemask) {
		int status;

		status = compact_zone_order(zone, order, gfp_mask, sync,
						contended);
		rc = max(status, rc);

		/* If a normal allocation would succeed, stop compacting */
		if (zone_watermark_ok(zone, order, low_wmark_pages(zone), 0,
				      alloc_flags))
			break;
	}

	return rc;
}

/* Compact all zones within a node */
static void __compact_pgdat(pg_data_t *pgdat, struct compact_control *cc)
{
	int zoneid;
	struct zone *zone;

	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {

		zone = &pgdat->node_zones[zoneid];
		if (!populated_zone(zone))
			continue;

		cc->nr_freepages = 0;
		cc->nr_migratepages = 0;
		cc->zone = zone;
		INIT_LIST_HEAD(&cc->freepages);
		INIT_LIST_HEAD(&cc->migratepages);

		if (cc->order == -1 || !compaction_deferred(zone, cc->order))
			compact_zone(zone, cc);

		if (cc->order > 0) {
			int ok = zone_watermark_ok(zone, cc->order,
						low_wmark_pages(zone), 0, 0);
			if (ok && cc->order >= zone->compact_order_failed)
				zone->compact_order_failed = cc->order + 1;
			/* Currently async compaction is never deferred. */
			else if (!ok && cc->sync)
				defer_compaction(zone, cc->order);
		}

		VM_BUG_ON(!list_empty(&cc->freepages));
		VM_BUG_ON(!list_empty(&cc->migratepages));
	}
}

void compact_pgdat(pg_data_t *pgdat, int order)
{
	struct compact_control cc = {
		.order = order,
		.sync = false,
	};

	__compact_pgdat(pgdat, &cc);
}

static void compact_node(int nid)
{
	struct compact_control cc = {
		.order = -1,
		.sync = true,
	};

	__compact_pgdat(NODE_DATA(nid), &cc);
}

/* Compact all nodes in the system */
static void compact_nodes(void)
{
	int nid;

	/* Flush pending updates to the LRU lists */
	lru_add_drain_all();

	for_each_online_node(nid)
		compact_node(nid);
}

/* The written value is actually unused, all memory is compacted */
int sysctl_compact_memory;

/* This is the entry point for compacting all nodes via /proc/sys/vm */
int sysctl_compaction_handler(struct ctl_table *table, int write,
			void __user *buffer, size_t *length, loff_t *ppos)
{
	if (write)
		compact_nodes();

	return 0;
}

int sysctl_extfrag_handler(struct ctl_table *table, int write,
			void __user *buffer, size_t *length, loff_t *ppos)
{
	proc_dointvec_minmax(table, write, buffer, length, ppos);

	return 0;
}

#if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
ssize_t sysfs_compact_node(struct device *dev,
			struct device_attribute *attr,
			const char *buf, size_t count)
{
	int nid = dev->id;

	if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
		/* Flush pending updates to the LRU lists */
		lru_add_drain_all();

		compact_node(nid);
	}

	return count;
}
static DEVICE_ATTR(compact, S_IWUSR, NULL, sysfs_compact_node);

int compaction_register_node(struct node *node)
{
	return device_create_file(&node->dev, &dev_attr_compact);
}

void compaction_unregister_node(struct node *node)
{
	return device_remove_file(&node->dev, &dev_attr_compact);
}
#endif /* CONFIG_SYSFS && CONFIG_NUMA */

#endif /* CONFIG_COMPACTION */


text:
<ShipDesign>
  <Name>Centurion Mk581</Name>
  <Hull>Centurion Class</Hull>
  <Deleted>false</Deleted>
  <ForeModules>
    <DesignModule>
      <Module>MissileHeavy_4x3</Module>
      <Rotation>0</Rotation>
      <Position>9</Position>
    </DesignModule>
    <DesignModule>
      <Module>MissileHeavy_4x3</Module>
      <Rotation>0</Rotation>
      <Position>6</Position>
    </DesignModule>
    <DesignModule>
      <Module>PlasmaCannon_2x6</Module>
      <Rotation>0</Rotation>
      <Position>86</Position>
    </DesignModule>
    <DesignModule>
      <Module>LaserCannonLightRed_2x3</Module>
      <Rotation>0</Rotation>
      <Position>3</Position>
    </DesignModule>
    <DesignModule>
      <Module>LaserCannonLightRed_2x3</Module>
      <Rotation>0</Rotation>
      <Position>35</Position>
    </DesignModule>
    <DesignModule>
      <Module>LaserCannonBlue_1x6</Module>
      <Rotation>0</Rotation>
      <Position>70</Position>
    </DesignModule>
    <DesignModule>
      <Module>LaserCannonBlue_1x6</Module>
      <Rotation>0</Rotation>
      <Position>92</Position>
    </DesignModule>
    <DesignModule>
      <Module>ShieldClassI_4x4</Module>
      <Rotation>0</Rotation>
      <Position>15</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_2x2</Module>
      <Rotation>0</Rotation>
      <Position>68</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>0</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>1</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>2</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_3x3</Module>
      <Rotation>0</Rotation>
      <Position>12</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_2x2</Module>
      <Rotation>0</Rotation>
      <Position>60</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>62</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>78</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>79</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>80</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>81</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>82</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>83</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>67</Position>
    </DesignModule>
  </ForeModules>
  <AftModules>
    <DesignModule>
      <Module>EnginesClassI_4x4</Module>
      <Rotation>0</Rotation>
      <Position>0</Position>
    </DesignModule>
    <DesignModule>
      <Module>EnginesClassI_4x4</Module>
      <Rotation>0</Rotation>
      <Position>11</Position>
    </DesignModule>
    <DesignModule>
      <Module>EnginesClassI_3x3</Module>
      <Rotation>0</Rotation>
      <Position>33</Position>
    </DesignModule>
    <DesignModule>
      <Module>ShieldClassI_2x2</Module>
      <Rotation>0</Rotation>
      <Position>36</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>28</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>19</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>10</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>4</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>5</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>50</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>49</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>48</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>47</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>56</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>55</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>54</Position>
    </DesignModule>
  </AftModules>
  <PortModules>
    <DesignModule>
      <Module>CannonHeavyAP_2x6</Module>
      <Rotation>0</Rotation>
      <Position>25</Position>
    </DesignModule>
    <DesignModule>
      <Module>PlasmaCannon_2x6</Module>
      <Rotation>0</Rotation>
      <Position>3</Position>
    </DesignModule>
    <DesignModule>
      <Module>Missile_3x2</Module>
      <Rotation>270</Rotation>
      <Position>22</Position>
    </DesignModule>
    <DesignModule>
      <Module>ShieldClassI_2x2</Module>
      <Rotation>0</Rotation>
      <Position>1</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>19</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_2x2</Module>
      <Rotation>0</Rotation>
      <Position>20</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>9</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>10</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>0</Position>
    </DesignModule>
  </PortModules>
  <StarboardModules>
    <DesignModule>
      <Module>CannonHeavyAP_2x6</Module>
      <Rotation>0</Rotation>
      <Position>5</Position>
    </DesignModule>
    <DesignModule>
      <Module>PlasmaCannon_2x6</Module>
      <Rotation>0</Rotation>
      <Position>26</Position>
    </DesignModule>
    <DesignModule>
      <Module>Missile_3x2</Module>
      <Rotation>90</Rotation>
      <Position>2</Position>
    </DesignModule>
    <DesignModule>
      <Module>ShieldClassI_2x2</Module>
      <Rotation>0</Rotation>
      <Position>24</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelSmart_1x1</Module>
      <Rotation>0</Rotation>
      <Position>32</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_2x2</Module>
      <Rotation>0</Rotation>
      <Position>0</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>22</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>23</Position>
    </DesignModule>
    <DesignModule>
      <Module>ArmorSteelHardened_1x1</Module>
      <Rotation>0</Rotation>
      <Position>33</Position>
    </DesignModule>
  </StarboardModules>
  <CenterModules>
    <DesignModule>
      <Module>ShieldClassI_4x4</Module>
      <Rotation>0</Rotation>
      <Position>9</Position>
    </DesignModule>
    <DesignModule>
      <Module>ReactorFusion_4x4</Module>
      <Rotation>0</Rotation>
      <Position>5</Position>
    </DesignModule>
    <DesignModule>
      <Module>ReactorFusion_4x4</Module>
      <Rotation>0</Rotation>
      <Position>1</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>0</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>13</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>26</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>39</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>52</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>53</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>54</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>55</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>56</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>57</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>58</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>59</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>60</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>61</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>62</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>63</Position>
    </DesignModule>
    <DesignModule>
      <Module>AmmoStorage_1x1</Module>
      <Rotation>0</Rotation>
      <Position>64</Position>
    </DesignModule>
  </CenterModules>
  <AI_Profile>BestGuess</AI_Profile>
  <attackStyle>holdPosition</attackStyle>
  <attackDirection>Fore</attackDirection>
  <attackRange>20</attackRange>
</ShipDesign>

redpajama_set_name: RedPajamaGithub


text:
id: version-6.26.3-babel-helper-remap-async-to-generator
title: babel-helper-remap-async-to-generator
sidebar_label: babel-helper-remap-async-to-generator
original_id: babel-helper-remap-async-to-generator
---

TODO


text:
@interface VENCalculatorInputTextField : UITextField <VENCalculatorInputViewDelegate>

@end


text:
require File.expand_path('../../test_helper', __FILE__)

class CloneTicketSettingsTest < ActiveSupport::TestCase

  # Replace this with your real tests.
  def test_truth
    assert true
  end
end


text:
package org.apache.ambari.logsearch.converter;

import org.apache.ambari.logsearch.common.LogType;
import org.apache.ambari.logsearch.model.request.impl.AuditComponentRequest;
import org.springframework.data.solr.core.query.FacetOptions;

import javax.inject.Named;

import static org.apache.ambari.logsearch.solr.SolrConstants.AuditLogConstants.AUDIT_COMPONENT;
import static org.apache.ambari.logsearch.solr.SolrConstants.AuditLogConstants.AUDIT_EVTTIME;

@Named
public class AuditComponentsRequestQueryConverter extends AbstractLogRequestFacetQueryConverter<AuditComponentRequest> {

  @Override
  public FacetOptions.FacetSort getFacetSort() {
    return FacetOptions.FacetSort.INDEX;
  }

  @Override
  public String getDateTimeField() {
    return AUDIT_EVTTIME;
  }

  @Override
  public LogType getLogType() {
    return LogType.AUDIT;
  }

  @Override
  public void appendFacetOptions(FacetOptions facetOptions, AuditComponentRequest request) {
    facetOptions.addFacetOnField(AUDIT_COMPONENT);
    facetOptions.setFacetLimit(-1);
  }
}


text:
import {
  EditorState,
  convertFromRaw,
} from 'draft-js';

import { getSelectionText } from './DraftUtils';

describe('DraftUtils', () => {
  describe('#getSelectionText', () => {
    it('works', () => {
      const content = convertFromRaw({
        entityMap: {},
        blocks: [
          {
            key: 'a',
            text: 'test1234',
          },
        ],
      });
      let editorState = EditorState.createWithContent(content);

      let selection = editorState.getSelection();
      selection = selection.merge({
        anchorOffset: 0,
        focusOffset: 4,
      });

      editorState = EditorState.acceptSelection(editorState, selection);

      expect(getSelectionText(editorState)).toBe('test');
    });

    it('empty', () => {
      expect(getSelectionText(EditorState.createEmpty())).toBe('');
    });

    it('backwards', () => {
      const content = convertFromRaw({
        entityMap: {},
        blocks: [
          {
            key: 'a',
            text: 'test1234',
          },
        ],
      });
      let editorState = EditorState.createWithContent(content);

      let selection = editorState.getSelection();
      selection = selection.merge({
        anchorOffset: 8,
        focusOffset: 4,
        isBackward: true,
      });

      editorState = EditorState.acceptSelection(editorState, selection);

      expect(getSelectionText(editorState)).toBe('1234');
    });

    it('multiblock', () => {
      const content = convertFromRaw({
        entityMap: {},
        blocks: [
          {
            key: 'a',
            text: 'test1234',
          },
          {
            key: 'b',
            text: 'multiblock',
          }
        ],
      });
      let editorState = EditorState.createWithContent(content);

      let selection = editorState.getSelection();
      selection = selection.merge({
        anchorKey: 'a',
        focusKey: 'b',
        anchorOffset: 4,
        focusOffset: 5,
        isBackward: false,
      });

      editorState = EditorState.acceptSelection(editorState, selection);

      expect(getSelectionText(editorState)).toBe('1234multi');
    });

    it('multiblock-backwards', () => {
      const content = convertFromRaw({
        entityMap: {},
        blocks: [
          {
            key: 'a',
            text: 'test1234',
          },
          {
            key: 'b',
            text: 'multiblock',
          }
        ],
      });
      let editorState = EditorState.createWithContent(content);

      let selection = editorState.getSelection();
      selection = selection.merge({
        focusKey: 'a',
        anchorKey: 'b',
        anchorOffset: 5,
        focusOffset: 4,
        isBackward: true,
      });

      editorState = EditorState.acceptSelection(editorState, selection);

      expect(getSelectionText(editorState)).toBe('1234multi');
    });
  });
});


text:
'use strict';

var app = angular.module('tribbleApp', ['ui.router']);

/********************************************************************
* CONFIGURATION
*********************************************************************/
app.config(['$stateProvider', '$urlRouterProvider',
  function($stateProvider, $urlRouterProvider) {

  $stateProvider.state('home', {
    url: '',
    views: {
      'description': {
        controller: 'DescriptionCtrl as description',
        templateUrl: 'templates/description.html',
      },
      'container': {
        controller: 'HomeCtrl as home',
        templateUrl: 'templates/home.html'
      }
    },
  });

  $stateProvider.state('project', {
    url: '/project/:slug',
    views: {
      'description': {
        controller: 'DescriptionCtrl as description',
        templateUrl: 'templates/description.html',
      },
      'container': {
        controller: 'ProjectCtrl as project',
        templateUrl: 'templates/project.html'
      }
    }
  });

  $urlRouterProvider.otherwise('');
}]);

/********************************************************************
* SERVICES
*********************************************************************/
app.service('projectSrv', ['$http', function ($http) {
  this.projects = $http.get('app/data/projects.json', {cache: true})
    .then(function(res) {
      return res.data;
    });

  this.getProjects = function(cb) {
    this.projects.then(function(data) {
      cb(data);
    });
  };

  this.getProject = function(projects, slug) {
    for (var i=0; i<projects.length; i++) {
      if (projects[i].slug === slug) {
        return projects[i];
      }
    }
  };
}]);

/********************************************************************
* CONTROLLERS
*********************************************************************/
app.controller('DescriptionCtrl', ['$scope', '$stateParams', 'projectSrv',
  function($scope, $stateParams, projectSrv) {
    $scope.slug = $stateParams.slug;
    if ($scope.slug) {
      projectSrv.getProjects(function(data) {
        $scope.projects = data;
        $scope.project = projectSrv.getProject($scope.projects, $scope.slug);
      });
    }
}]);

app.controller('HomeCtrl', ['$scope', 'projectSrv',
  function($scope, projectSrv) {
    projectSrv.getProjects(function(data) {
      var repository = 'https://github.com/codenameyau/tribble/';
      var source = 'blob/master/public/projects/demo/';
      $scope.github = repository + source;
      $scope.projects = data;
    });
}]);

app.controller('ProjectCtrl', ['$scope', '$filter', '$stateParams',
  function($scope, $filter, $stateParams) {
    $scope.slug = $stateParams.slug;
    var demoFunction = $filter('slugToCamel')($scope.slug) + 'Demo';
    window[demoFunction]();
}]);

/********************************************************************
* FILTERS
*********************************************************************/
app.filter('slugToCamel', function() {
  return function(input) {
    return input.replace(/-(.)?/g, function(match) {
      return match[1].toUpperCase();
    });
  };
});


text:
package com.zu.sweetalbum.swiftp.server;

import android.util.Log;

public class CmdSYST extends FtpCmd implements Runnable {
    private static final String TAG = CmdSYST.class.getSimpleName();

    // This is considered a safe response to the SYST command, see
    // http://cr.yp.to/ftp/syst.html
    public static final String response = "215 UNIX Type: L8\r\n";

    public CmdSYST(SessionThread sessionThread, String input) {
        super(sessionThread);
    }

    @Override
    public void run() {
        Log.d(TAG, "SYST executing");
        sessionThread.writeString(response);
        Log.d(TAG, "SYST finished");
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/button_close_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/button_close_normal"/>

</selector>


text:
import React from 'react';

class ProgressBar extends React.Component {
    render() {
        let value = this.props.children !== null
            ?
{this.props.children}

            : null;
        return <div className={`progress-bar${value === null ? ' progress-bar__small' : ''}`}>

{value}

;
    }
}

ProgressBar.propTypes = {
    children: React.PropTypes.node,
    percent: React.PropTypes.number.isRequired
};

ProgressBar.defaultProps = {
    children: null
};

export default ProgressBar;


text: <title>504: Gateway Timeout</title>504: Gateway Timeout


text:
package de.binarytree.plugins.qualitygates.result;

import hudson.model.Result;

import java.util.LinkedList;
import java.util.List;

import de.binarytree.plugins.qualitygates.Gate;
import de.binarytree.plugins.qualitygates.GateStep;

/**
 * This class is a report about the execution of a gate. It holds the reports of
 * the executed steps and the result of the gate itself.
 */
public class GateReport extends ListContainer<GateStepReport> {

    private String gateName;
    private Result result = Result.NOT_BUILT;
    private transient Gate gate;

    /**
     * Creates a new gate report for the given gate.
     *
     * @param gate
     *            the gate for which a report shall be created
     */
    public GateReport(Gate gate) {
        this.gateName = gate.getName();
        this.gate = gate;
    }

    private List<GateStepReport> steps() {
        return this.getItems();
    }

    /**
     * Returns the name of the corresponding gate.
     *
     * @return the name of the corresponding gate
     */
    public String getGateName() {
        return this.gateName;
    }

    /**
     * Returns the result of this report.
     *
     * @return the reusult of this report
     */
    public Result getResult() {
        return this.result;
    }

    /**
     * Returns the number of {@link GateStepReport}s in this gate report.
     *
     * @return the number of gate step reports
     */
    public int getNumberOfSteps() {
        return this.steps().size();
    }

    public void setResult(Result result) {
        this.result = result;
    }

    /**
     * Adds the given step report to this report. If there is already a step
     * report referencing the same gate, it is replaced.
     *
     * @param stepReport
     *            the stepReport to be added
     */
    public void addStepReport(GateStepReport stepReport) {
        this.addOrReplaceItem(stepReport);

    }

    /**
     * Returns a list of the {@link GateStepReport} of this gate report.
     *
     * @return a list of the contained gate step reports.
     */
    public List<GateStepReport> getStepReports() {
        return new LinkedList<GateStepReport>(this.steps());
    }

    /**
     * Whether or not this report belongs to the given gate.
     *
     * @param gate
     *            the gate to be tested
     * @return whether of
     */
    public boolean belongsTo(Gate gate) {
        return this.gate == gate;
    }

    /**
     * Whether or not this report references the same gate as the given report.
     *
     * @param gateReport
     *            the report to be compared
     * @return whether or not both reports reference the same gate
     */
    public boolean referencesSameGateAs(GateReport gateReport) {
        return this.gate == gateReport.gate;
    }

    @Override
    protected boolean isSameItem(GateStepReport a, GateStepReport b) {
        return a.referencesSameStepAs(b);
    }

    /**
     * Returns the reasons why the corresponding gate has failed. Returns an
     * empty list when the gate has not failed at all.
     *
     * @return the reasons for failure
     */
    public List<String> getReasonOfFailure() {
        LinkedList<String> reasons = new LinkedList<String>();
        for (GateStepReport report : this.steps()) {
            if (report.getResult().isWorseOrEqualTo(Result.FAILURE)) {
                reasons.add(report.getReason());
            }
        }
        return reasons;
    }

    /**
     * Returns the {@link GateStepReport} for the given {@link GateStep}
     *
     * @param step
     *            the step for which the report shall be returned
     * @return the corresponding report
     */
    public GateStepReport getReportFor(GateStep step) {
        for (GateStepReport report : this.getStepReports()) {
            if (report.references(step)) {
                return report;
            }
        }
        return null;
    }
}


text:
package com.learning.java.algorithm;

import java.util.LinkedHashMap;

public class RepeatedWord {
    public static void main(String args[]) {
        String s = "Ravi had been saying that he had been there";
        String[] stra = s.split(" ");
        LinkedHashMap<String, Integer> strMap = new LinkedHashMap<>();
        String word = null;
        for (String s1 : stra) {
            if (strMap.get(s1) == null) strMap.put(s1, 1);
            else {
                word = s1;
                break;
            }
        }
        System.out.print(word);
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Anggota */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'status')->radioList(['non' => 'Tidak Aktif','aktif' => 'Aktif'])?>

        <?= Html::submitButton($model->isNewRecord ? 'Ubah' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
		<?= Html::a('Batal', ['index'], ['class' => 'btn btn-danger']) ?>

    <?php ActiveForm::end(); ?>


text:
package com.vishnus1224.imagegallery.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.vishnus1224.imagegallery.R;
import com.vishnus1224.imagegallery.Utility.ImageLoader;

import java.util.List;

/**
 * Created by vishnu on 12/06/15.
 */
public class LazyImageAdapter extends BaseAdapter {

    private Context context;
    private List<String> imagePaths;
    private LayoutInflater layoutInflater;
    private ImageLoader imageLoader;

    public LazyImageAdapter(Context context, List<String> imagePaths){
        this.context = context;
        this.imagePaths = imagePaths;
        layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader = new ImageLoader(context);
    }

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

    @Override
    public Object getItem(int position) {
        return imagePaths.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null){
            convertView = layoutInflater.inflate(R.layout.gridview_image_gallery, parent, false);
        }

        ImageView imageView = (ImageView)convertView.findViewById(R.id.gridview_row_imageview);
        String path = imagePaths.get(position);

        imageLoader.fetchImage(context, path, imageView);

        return convertView;
    }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Description;
using Microsoft.Azure.WebJobs.Host.Bindings;
using Microsoft.Azure.WebJobs.Host.Config;
using Microsoft.Azure.WebJobs.Host.Protocols;
using Microsoft.Azure.WebJobs.Host.Queues.Triggers;
using Microsoft.Azure.Storage.Queue;
using Newtonsoft.Json.Linq;

namespace Microsoft.Azure.WebJobs.Host.Queues.Config
{
    [Extension("AzureStorageQueues", "Queues")]
    internal class QueuesExtensionConfigProvider : IExtensionConfigProvider
    {
        private readonly IContextGetter<IMessageEnqueuedWatcher> _contextGetter;
        private readonly StorageAccountProvider _storageAccountProvider;
        private readonly QueueTriggerAttributeBindingProvider _triggerProvider;

        public QueuesExtensionConfigProvider(StorageAccountProvider storageAccountProvider, IContextGetter<IMessageEnqueuedWatcher> contextGetter,
            QueueTriggerAttributeBindingProvider triggerProvider)
        {
            _contextGetter = contextGetter;
            _storageAccountProvider = storageAccountProvider;
            _triggerProvider = triggerProvider;
        }

        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            context.AddBindingRule<QueueTriggerAttribute>().BindToTrigger(_triggerProvider);

            var config = new PerHostConfig();
            config.Initialize(context, _storageAccountProvider, _contextGetter);
        }

        // $$$ Get rid of PerHostConfig part?
        // Multiple JobHost objects may share the same JobHostConfiguration.
        // But queues have per-host instance state (IMessageEnqueuedWatcher).
        // so capture that and create new binding rules per host instance.
        private class PerHostConfig : IConverter<QueueAttribute, IAsyncCollector<CloudQueueMessage>>
        {
            // Fields that the various binding funcs need to close over.
            private StorageAccountProvider _accountProvider;

            // Optimization where a queue output can directly trigger a queue input.
            // This is per-host (not per-config)
            private IContextGetter<IMessageEnqueuedWatcher> _messageEnqueuedWatcherGetter;

            public void Initialize(ExtensionConfigContext context, StorageAccountProvider storageAccountProvider, IContextGetter<IMessageEnqueuedWatcher> contextGetter)
            {
                _accountProvider = storageAccountProvider;
                _messageEnqueuedWatcherGetter = contextGetter;

                // TODO: FACAVAL replace this with queue options. This should no longer be needed.
                //context.ApplyConfig(context.Config.Queues, "queues");

                // IStorageQueueMessage is the core testing interface
                var binding = context.AddBindingRule<QueueAttribute>();
                binding
                    .AddConverter<byte[], CloudQueueMessage>(ConvertByteArrayToCloudQueueMessage)
                    .AddConverter<string, CloudQueueMessage>(ConvertStringToCloudQueueMessage)
                    .AddOpenConverter<OpenType.Poco, CloudQueueMessage>(ConvertPocoToCloudQueueMessage);

                context // global converters, apply to multiple attributes.
                     .AddConverter<CloudQueueMessage, byte[]>(ConvertCloudQueueMessageToByteArray)
                     .AddConverter<CloudQueueMessage, string>(ConvertCloudQueueMessageToString);

                var builder = new QueueBuilder(this);

                binding.AddValidator(ValidateQueueAttribute);

                binding.SetPostResolveHook(ToWriteParameterDescriptorForCollector)
                        .BindToCollector<CloudQueueMessage>(this);

                binding.SetPostResolveHook(ToReadWriteParameterDescriptorForCollector)
                        .BindToInput<CloudQueue>(builder);

                binding.SetPostResolveHook(ToReadWriteParameterDescriptorForCollector)
                        .BindToInput<CloudQueue>(builder);
            }

            private async Task<object> ConvertPocoToCloudQueueMessage(object arg, Attribute attrResolved, ValueBindingContext context)
            {
                var attr = (QueueAttribute)attrResolved;
                var jobj = await SerializeToJobject(arg, attr, context);
                var msg = ConvertJObjectToCloudQueueMessage(jobj, attr);
                return msg;
            }

            private CloudQueueMessage ConvertJObjectToCloudQueueMessage(JObject obj, QueueAttribute attrResolved)
            {
                var json = obj.ToString(); // convert to JSon
                return ConvertStringToCloudQueueMessage(json, attrResolved);
            }

            // Hook JObject serialization to so we can stamp the object with a causality marker.
            private static Task<JObject> SerializeToJobject(object input, Attribute attrResolved, ValueBindingContext context)
            {
                JObject objectToken = JObject.FromObject(input, JsonSerialization.Serializer);
                var functionInstanceId = context.FunctionInstanceId;
                QueueCausalityManager.SetOwner(functionInstanceId, objectToken);

                return Task.FromResult<JObject>(objectToken);
            }

            // ParameterDescriptor for binding to CloudQueue. Whereas the output bindings are FileAccess.Write; CloudQueue exposes Peek()
            // and so is technically Read/Write.
            // Preserves compat with older SDK.
            private ParameterDescriptor ToReadWriteParameterDescriptorForCollector(QueueAttribute attr, ParameterInfo parameter, INameResolver nameResolver)
            {
                return ToParameterDescriptorForCollector(attr, parameter, nameResolver, FileAccess.ReadWrite);
            }

            // Asyncollector version. Write-only
            private ParameterDescriptor ToWriteParameterDescriptorForCollector(QueueAttribute attr, ParameterInfo parameter, INameResolver nameResolver)
            {
                return ToParameterDescriptorForCollector(attr, parameter, nameResolver, FileAccess.Write);
            }

            private ParameterDescriptor ToParameterDescriptorForCollector(QueueAttribute attr, ParameterInfo parameter, INameResolver nameResolver, FileAccess access)
            {
                var account = _accountProvider.Get(attr.Connection, nameResolver);
                var accountName = account.Name;

                return new QueueParameterDescriptor
                {
                    Name = parameter.Name,
                    AccountName = accountName,
                    QueueName = NormalizeQueueName(attr, nameResolver),
                    Access = access
                };
            }

            private static string NormalizeQueueName(QueueAttribute attribute, INameResolver nameResolver)
            {
                string queueName = attribute.QueueName;
                if (nameResolver != null)
                {
                    queueName = nameResolver.ResolveWholeString(queueName);
                }
                queueName = queueName.ToLowerInvariant(); // must be lowercase. coerce here to be nice.
                return queueName;
            }

            // This is a static validation (so only %% are resolved; not {} )
            // For runtime validation, the regular builder functions can do the resolution.
            private void ValidateQueueAttribute(QueueAttribute attribute, Type parameterType)
            {
                string queueName = NormalizeQueueName(attribute, null);

                // Queue pre-existing  behavior: if there are { }in the path, then defer validation until runtime.
                if (!queueName.Contains("{"))
                {
                    QueueClient.ValidateQueueName(queueName);
                }
            }

            private byte[] ConvertCloudQueueMessageToByteArray(CloudQueueMessage arg)
            {
                return arg.AsBytes;
            }

            private string ConvertCloudQueueMessageToString(CloudQueueMessage arg)
            {
                return arg.AsString;
            }

            private CloudQueueMessage ConvertByteArrayToCloudQueueMessage(byte[] arg, QueueAttribute attrResolved)
            {
                return new CloudQueueMessage(arg);
            }

            private CloudQueueMessage ConvertStringToCloudQueueMessage(string arg, QueueAttribute attrResolved)
            {
                return new CloudQueueMessage(arg);
            }

            public IAsyncCollector<CloudQueueMessage> Convert(QueueAttribute attrResolved)
            {
                var queue = GetQueue(attrResolved);
                return new QueueAsyncCollector(queue, _messageEnqueuedWatcherGetter.Value);
            }

            internal CloudQueue GetQueue(QueueAttribute attrResolved)
            {
                var account = _accountProvider.Get(attrResolved.Connection);
                var client = account.CreateCloudQueueClient();

                string queueName = attrResolved.QueueName.ToLowerInvariant();
                QueueClient.ValidateQueueName(queueName);

                return client.GetQueueReference(queueName);
            }
        }

        private class QueueBuilder :
            IAsyncConverter<QueueAttribute, CloudQueue>
        {
            private readonly PerHostConfig _bindingProvider;

            public QueueBuilder(PerHostConfig bindingProvider)
            {
                _bindingProvider = bindingProvider;
            }

            async Task<CloudQueue> IAsyncConverter<QueueAttribute, CloudQueue>.ConvertAsync(
                QueueAttribute attrResolved,
                CancellationToken cancellation)
            {
                CloudQueue queue = _bindingProvider.GetQueue(attrResolved);
                await queue.CreateIfNotExistsAsync(cancellation);
                return queue;
            }
        }

        // The core Async Collector for queueing messages.
        internal class QueueAsyncCollector : IAsyncCollector<CloudQueueMessage>
        {
            private readonly CloudQueue _queue;
            private readonly IMessageEnqueuedWatcher _messageEnqueuedWatcher;

            public QueueAsyncCollector(CloudQueue queue, IMessageEnqueuedWatcher messageEnqueuedWatcher)
            {
                this._queue = queue;
                this._messageEnqueuedWatcher = messageEnqueuedWatcher;
            }

            public async Task AddAsync(CloudQueueMessage message, CancellationToken cancellationToken = default(CancellationToken))
            {
                if (message == null)
                {
                    throw new InvalidOperationException("Cannot enqueue a null queue message instance.");
                }

                await _queue.AddMessageAndCreateIfNotExistsAsync(message, cancellationToken);

                if (_messageEnqueuedWatcher != null)
                {
                    _messageEnqueuedWatcher.Notify(_queue.Name);
                }
            }

            public Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
            {
                // Batching not supported.
                return Task.FromResult(0);
            }
        }
    }
}


text:
<?php

namespace PHPMinds\Repository;

use PHPMinds\Model\Db;

class RepositoryAbstract
{
    /**
     * @var \PDO
     */
    protected $db;

    protected $table;

    protected $columns = [];

    public function __construct(Db $db)
    {
        $this->db = $db;
    }

    protected function getById($id)
    {
        $sql = "SELECT {$this->getColumns()} " .
                "FROM {$this->table} " .
                "WHERE id=:id";

        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(":id", $id, \PDO::PARAM_INT);

        $stmt->execute();
        $stmt->setFetchMode(\PDO::FETCH_ASSOC);

        return $stmt->fetch() ?: [];
    }

    protected function getColumns()
    {
        return implode(', ', $this->columns);
    }

    public function getAll($returnType = \PDO::FETCH_OBJ)
    {
        $sql = "SELECT {$this->getColumns()} ".
                "FROM {$this->table} ";

        $events = $this->db->query($sql)->fetchAll($returnType);

        $result = array_reduce($events, function($carry, $item){

            if (is_object($item)) {
                $carry[$item->id] = $item;
            } else {
                $carry[$item['id']] = $item;
            }
            return $carry;
        });

        return $result;
    }
}


text:
<workflow-app xmlns="uri:oozie:workflow:0.4" name="my_subworkflow">

    <global>
        <job-tracker>${jobTracker}</job-tracker>
        <name-node>${nameNode}</name-node>
        <configuration>
            <property>
                <name>mapreduce.job.queuename</name>
                <value>${queueName}</value>
            </property>
            <property>
                <name>oozie.launcher.mapred.job.queue.name</name>
                <value>${oozieLauncherQueueName}</value>
            </property>
        </configuration>
    </global>

    <start to="generate-schema" />

	<action name="generate-schema">
	    <java>
	        <main-class>eu.dnetlib.iis.common.javamapreduce.hack.AvroSchemaGenerator</main-class>
	        <arg>eu.dnetlib.iis.core.examples.schemas.documentandauthor.personwithdocuments.PersonWithDocuments</arg>
	        <capture-output />
	    </java>
	    <ok to="filter" />
	    <error to="fail" />
	</action>

    <action name="filter">
        <pig>
            <!-- Path to PIG script the workflow executes. -->
            <script>lib/scripts/filter/filter.pig</script>
            <!-- Input ports. -->
            <param>input_person_with_documents=${input_person_with_documents}</param>
            <!-- Output ports. -->
            <param>output_person_with_documents=${output_person_with_documents}</param>
            <!-- Input and output Avro schemas passed to the script must be given
                 as full URIs. -->
            <param>schema_input_person_with_documents=${wf:actionData('generate-schema')['eu.dnetlib.iis.core.examples.schemas.documentandauthor.personwithdocuments.PersonWithDocuments']}</param>
            <param>schema_output_person_with_documents=${wf:actionData('generate-schema')['eu.dnetlib.iis.core.examples.schemas.documentandauthor.personwithdocuments.PersonWithDocuments']}</param>
            <!-- Arguments passed to PIG script. -->
            <argument>-param</argument>
            <argument>min_document_number=2</argument>
        </pig>
        <ok to="end"/>
        <error to="fail"/>
    </action>
    <kill name="fail">
        <message>Unfortunately, the process failed -- error message: [${wf:errorMessage(wf:lastErrorNode())}]</message>
    </kill>
    <end name="end"/>
</workflow-app>


text:
package alexa.skills.backbase.model;

public class Holder {

    private String name;
    private Boolean isAlias;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Boolean getIsAlias() {
        return isAlias;
    }

    public void setIsAlias(Boolean isAlias) {
        this.isAlias = isAlias;
    }

}


text:
<?php

namespace Liquid;

use Liquid\FileSystem\Virtual;

class TestFileSystem extends Virtual
{
	/** @return TestFileSystem */
	public static function fromArray($array)
	{
		return new static(function ($path) use ($array) {
			if (isset($array[$path])) {
				return $array[$path];
			}

			return '';
		});
	}
}


text:
class Prawn::Svg::Parser::Text
  def parse(element)
    element.add_call_and_enter "text_group"
    internal_parse(element, [element.document.x(0)], [element.document.y(0)], false)
  end

  protected
  def internal_parse(element, x_positions, y_positions, relative)
    attrs = element.attributes

    if attrs['x'] || attrs['y']
      relative = false
      x_positions = attrs['x'].split(/[\s,]+/).collect {|n| element.document.x(n)} if attrs['x']
      y_positions = attrs['y'].split(/[\s,]+/).collect {|n| element.document.y(n)} if attrs['y']
    end

    if attrs['dx'] || attrs['dy']
      element.add_call_and_enter "translate", element.document.distance(attrs['dx'] || 0), -element.document.distance(attrs['dy'] || 0)
    end

    opts = {}
    if size = element.state[:font_size]
      opts[:size] = size
    end
    if style = element.state[:font_style]
      opts[:style] = style
    end

    # This is not a prawn option but we can't work out how to render it here -
    # it's handled by Svg#rewrite_call_arguments
    if anchor = attrs['text-anchor']
      opts[:text_anchor] = anchor
    end

    element.element.children.each do |child|
      if child.node_type == :text
        text = child.to_s.strip.gsub(/\s+/, " ")

        while text != ""
          opts[:at] = [x_positions.first, y_positions.first]

          if x_positions.length > 1 || y_positions.length > 1
            element.add_call 'draw_text', text[0..0], opts.dup
            text = text[1..-1]

            x_positions.shift if x_positions.length > 1
            y_positions.shift if y_positions.length > 1
          else
            element.add_call relative ? 'relative_draw_text' : 'draw_text', text, opts.dup
            relative = true
            break
          end
        end

      elsif child.name == "tspan"
        element.add_call 'save'
        child_element = Prawn::Svg::Element.new(element.document, child, element.calls, element.state.dup)
        internal_parse(child_element, x_positions, y_positions, relative)
        child_element.append_calls_to_parent
        element.add_call 'restore'

      else
        element.warnings << "Unknown tag '#{child.name}' inside text tag; ignoring"
      end
    end
  end
end


text:
namespace scratch::detail {

template<typename T, size_t Index>
class compressed_ref_element {
    static_assert(is_reference_v<T>);
    remove_reference_t<T> *t;
public:
    template<class U> compressed_ref_element(U&& u) : t(&u) {}
    T get() const { return static_cast<T>(*t); }
    T get_element(index_constant<Index>) const { return static_cast<T>(*t); }
};

} // namespace scratch::detail

namespace scratch {

template<class...> class reftuple;

template<size_t I, class... Ts> constexpr inline decltype(auto) get(const reftuple<Ts...>& t) { return t.get_element(index_constant<I>{}); }

template<class, class...> struct reftuple_impl;

template<class... Ts, size_t... Is>
struct reftuple_impl<index_sequence<Is...>, Ts...> :
    private detail::compressed_ref_element<Ts, Is>...
{
    using ISeq = index_sequence<Is...>;
    using detail::compressed_ref_element<Ts, Is>::get_element...;

    void get_element() {}  // make sure there's something for reftuple's "using" declaration even in the zero-Ts case

    template<class... Us>
    reftuple_impl(Us&&... args) : detail::compressed_ref_element<Ts, Is>(std::forward<Us>(args))... {}
};

template<class... Ts>
class reftuple : private reftuple_impl<make_index_sequence<sizeof...(Ts)>, Ts...>
{
    static_assert((is_reference_v<Ts> && ...), "reftuple can hold only reference types. For a tuple of object types, use tuple.");
    using TupleImpl = reftuple_impl<make_index_sequence<sizeof...(Ts)>, Ts...>;
public:
    using TupleImpl::get_element;  // public

    reftuple(reftuple&&) = default;
    reftuple(const reftuple&) = default;
    reftuple& operator=(reftuple&&) = delete;
    reftuple& operator=(const reftuple&) = delete;
    ~reftuple() = default;

    template<class... Us, class = enable_if_t<sizeof...(Us) == sizeof...(Ts)>>
    constexpr reftuple(Us&&... args) : TupleImpl(std::forward<Us>(args)...) {}
};

template<class... Ts>
struct tuple_size<reftuple<Ts...>> : index_constant<sizeof...(Ts)> {};

template<class... Ts, size_t I>
struct tuple_element<reftuple<Ts...>, I> {
    using type = decltype(scratch::get<I>(declval<reftuple<Ts...>>()));
};

} // namespace scratch


text:
package fr.xebia.management.jms;

import javax.jms.ConnectionFactory;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.jmx.export.naming.SelfNaming;

/**
 *
 * @author Cyrille Le Clerc
 */
public class SpringManagedConnectionFactory extends ManagedConnectionFactory implements ConnectionFactory, ManagedConnectionFactoryMBean,
        SelfNaming, BeanNameAware {

    private String beanName;

    public ObjectName getObjectName() throws MalformedObjectNameException {
        return ObjectName.getInstance("javax.jms:type=ConnectionFactory,name=" + beanName);
    }

    public void setBeanName(String name) {
        this.beanName = name;
    }

}


text:
package com.refinedmods.refinedstorage.network.grid;

import com.refinedmods.refinedstorage.api.network.grid.IGrid;
import com.refinedmods.refinedstorage.container.GridContainerMenu;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraftforge.network.NetworkEvent;

import java.util.UUID;
import java.util.function.Supplier;

public class GridFluidPullMessage {
    private final UUID id;
    private final boolean shift;

    public GridFluidPullMessage(UUID id, boolean shift) {
        this.id = id;
        this.shift = shift;
    }

    public static GridFluidPullMessage decode(FriendlyByteBuf buf) {
        return new GridFluidPullMessage(buf.readUUID(), buf.readBoolean());
    }

    public static void encode(GridFluidPullMessage message, FriendlyByteBuf buf) {
        buf.writeUUID(message.id);
        buf.writeBoolean(message.shift);
    }

    public static void handle(GridFluidPullMessage message, Supplier<NetworkEvent.Context> ctx) {
        ServerPlayer player = ctx.get().getSender();

        if (player != null) {
            ctx.get().enqueueWork(() -> {
                AbstractContainerMenu container = player.containerMenu;

                if (container instanceof GridContainerMenu) {
                    IGrid grid = ((GridContainerMenu) container).getGrid();

                    if (grid.getFluidHandler() != null) {
                        grid.getFluidHandler().onExtract(player, message.id, message.shift);
                    }
                }
            });
        }

        ctx.get().setPacketHandled(true);
    }
}


text:
package hu.akarnokd.rxjava2flow;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;

import java.util.concurrent.Flow.*;

import org.mockito.Mockito;

import hu.akarnokd.rxjava2flow.NbpObservable.NbpSubscriber;

/**
 * Common methods for helping with tests from 1.x mostly.
 */
public enum TestHelper {
    ;
    /**
     * Mocks a subscriber and prepares it to request Long.MAX_VALUE.
     * @return the mocked subscriber
     */
    @SuppressWarnings("unchecked")
    public static <T> Subscriber<T> mockSubscriber() {
        Subscriber<T> w = mock(Subscriber.class);

        Mockito.doAnswer(a -> {
            Subscription s = a.getArgumentAt(0, Subscription.class);
            s.request(Long.MAX_VALUE);
            return null;
        }).when(w).onSubscribe(any());

        return w;
    }

    @SuppressWarnings("unchecked")
    public static <T> NbpSubscriber<T> mockNbpSubscriber() {
        return mock(NbpSubscriber.class);
    }
}


text:
package org.wso2.carbon.registry.eventing;

import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.transport.mail.MailConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.event.core.Message;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.registry.eventing.events.DispatchEvent;
import org.wso2.carbon.registry.eventing.internal.EventingDataHolder;
import org.wso2.carbon.registry.eventing.template.NotificationTemplate;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MimeEmailMessageHandler {

    public static final int MIN_THREAD = 8;
    public static final int MAX_THREAD = 100;
    public static final String MIN_THREAD_NAME = "minThread";
    public static final String MAX_THREAD_NAME = "maxThread";
    public static final String DEFAULT_KEEP_ALIVE_TIME_NAME = "defaultKeepAliveTime";
    public static final long DEFAULT_KEEP_ALIVE_TIME = 20;
    private static final Log log = LogFactory.getLog(MimeEmailMessageHandler.class);
    private static Session session;
    private static ThreadPoolExecutor threadPoolExecutor;
    private InternetAddress smtpFromAddress = null;

    /**
     *
     * @param configContext ConfigurationContext
     * @param message Mail body
     * @param subject Mail Subject
     * @param toAddress email to address
     * @throws RegistryException Registry exception
     */
    public void sendMimeMessage(ConfigurationContext configContext, String message, String subject, String toAddress) throws  RegistryException {
        Properties props = new Properties();
        if (configContext != null && configContext.getAxisConfiguration().getTransportOut("mailto") != null) {
            List<Parameter> params = configContext.getAxisConfiguration().getTransportOut("mailto").getParameters();
            for (Parameter parm: params) {
                props.put(parm.getName(), parm.getValue());
            }
        }
        if (threadPoolExecutor == null) {
            threadPoolExecutor = new ThreadPoolExecutor(MIN_THREAD, MAX_THREAD, DEFAULT_KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1000));
        }
        String smtpFrom = props.getProperty(MailConstants.MAIL_SMTP_FROM);

        try {
            smtpFromAddress = new InternetAddress(smtpFrom);
        } catch (AddressException e) {
            log.error("Error in retrieving smtp address");
            throw new RegistryException("Error in transforming smtp address");
        }
        final String smtpUsername = props.getProperty(MailConstants.MAIL_SMTP_USERNAME);
        final String smtpPassword = props.getProperty(MailConstants.MAIL_SMTP_PASSWORD);
        if (smtpUsername != null && smtpPassword != null) {
            MimeEmailMessageHandler.session = Session.getInstance(props, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(smtpUsername, smtpPassword);
                }
            });
        } else {
            MimeEmailMessageHandler.session = Session.getInstance(props);
        }
        threadPoolExecutor.submit(new EmailSender(toAddress, subject, message.toString(), "text/html"));
    }

    /**
     *
     * @param message Message Object
     * @param path  Registry path
     * @param event Event name
     * @return  Mail Subject
     */
    public String getEmailSubject(Message message, String path,String event){
        String mailHeader = message.getProperty(MailConstants.MAIL_HEADER_SUBJECT);
        if (mailHeader == null && (path == null || path.length() == 0)) {
            mailHeader =  "[" + event + "]";
        } else if (mailHeader == null) {
            mailHeader ="[" + event + "] at path: " + path;
        }
        return mailHeader;
    }

    public String getEmailMessage(Message message){
        String emailMessage = null;
        DispatchEvent event = (DispatchEvent) message;
        String eventType = event.getEvent().getClass().getSimpleName();
        String resourcePath = event.getEvent().getOperationDetails().getPath();
        if (EventingDataHolder.getInstance().getRegistryService() != null) {
            try {
                UserRegistry registry = EventingDataHolder.getInstance().getRegistryService().getConfigSystemRegistry();
                String mesageContent = event.getEvent().getMessage().toString();
                String className = EventingDataHolder.getInstance().getNotificationConfig().getConfigurationClass();
                Class clazz = Class.forName(className);
                Object instance = clazz.newInstance();
                if (instance instanceof NotificationTemplate){
                    NotificationTemplate template = (NotificationTemplate) instance;
                    emailMessage = template.populateEmailMessage(registry,resourcePath,mesageContent,eventType);
                }
            } catch (InstantiationException e) {
                log.warn("Error while instantiating template");
            } catch (IllegalAccessException e) {
                log.warn("Error while instantiating template");
            } catch (ClassNotFoundException e) {
                log.warn("Error while instantiating template");
            } catch (RegistryException e) {
                log.warn("Error while instantiating template");
            }

        }
        return emailMessage;
    }

    class EmailSender implements Runnable {
        String to;
        String subject;
        String body;
        String type;

        EmailSender(String to, String subject, String body, String type) {
            this.to = to;
            this.subject = subject;
            this.body = body;
            this.type = type;
        }

        /**
         * Sending emails to the corresponding Email IDs'.
         */

        @Override
        public void run() {

            if (log.isDebugEnabled()) {
                log.debug("Format of the email:" + " " + to + "->" + type);
            }
            //Creating MIME object using initiated session.

            MimeMessage message = new MimeMessage(session);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(body);
            String finalString = stringBuilder.toString();
            //Setting up the Email attributes and Email payload.

            try {
                message.setFrom(smtpFromAddress);
                message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
                message.setSubject(subject);
                message.setSentDate(new Date());
                message.setContent(finalString, type);

                if (log.isDebugEnabled()) {
                    log.debug("Meta data of the email configured successfully");
                }
                Transport.send(message);

                if (log.isDebugEnabled()) {
                    log.debug("Mail sent to the EmailID" + " " + to + " " + "Successfully");
                }
            } catch (MessagingException e) {
                log.error("Error in sending the Email : " + smtpFromAddress.toString() + "::" +e.getMessage(), e);
            }
        }

    }
}