text:
import { newWriteableBufferStream, VSBuffer, VSBufferReadableStream, VSBufferWriteableStream } from 'vs/base/common/buffer';
import { Emitter } from 'vs/base/common/event';
import { Lazy } from 'vs/base/common/lazy';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { localize } from 'vs/nls';
import { IComputedStateAccessor, refreshComputedState } from 'vs/workbench/contrib/testing/common/getComputedState';
import { IObservableValue, MutableObservableValue, staticObservableValue } from 'vs/workbench/contrib/testing/common/observableValue';
import { getMarkId, IRichLocation, ISerializedTestResults, ITestItem, ITestMessage, ITestOutputMessage, ITestRunTask, ITestTaskState, ResolvedTestRunRequest, TestItemExpandState, TestMessageType, TestResultItem, TestResultState } from 'vs/workbench/contrib/testing/common/testTypes';
import { TestCoverage } from 'vs/workbench/contrib/testing/common/testCoverage';
import { maxPriority, statesInOrder, terminalStatePriorities } from 'vs/workbench/contrib/testing/common/testingStates';
import { removeAnsiEscapeCodes } from 'vs/base/common/strings';
import { TestId } from 'vs/workbench/contrib/testing/common/testId';

export interface ITestRunTaskResults extends ITestRunTask {
	/**
	 * Contains test coverage for the result, if it's available.
	 */
	readonly coverage: IObservableValue<TestCoverage | undefined>;

	/**
	 * Messages from the task not associated with any specific test.
	 */
	readonly otherMessages: ITestOutputMessage[];
}

export interface ITestResult {
	/**
	 * Count of the number of tests in each run state.
	 */
	readonly counts: Readonly<TestStateCount>;

	/**
	 * Unique ID of this set of test results.
	 */
	readonly id: string;

	/**
	 * If the test is completed, the unix milliseconds time at which it was
	 * completed. If undefined, the test is still running.
	 */
	readonly completedAt: number | undefined;

	/**
	 * Whether this test result is triggered from an auto run.
	 */
	readonly request: ResolvedTestRunRequest;

	/**
	 * Human-readable name of the test result.
	 */
	readonly name: string;

	/**
	 * Gets all tests involved in the run.
	 */
	tests: IterableIterator<TestResultItem>;

	/**
	 * List of this result's subtasks.
	 */
	tasks: ReadonlyArray<ITestRunTaskResults>;

	/**
	 * Gets the state of the test by its extension-assigned ID.
	 */
	getStateById(testExtId: string): TestResultItem | undefined;

	/**
	 * Loads the output of the result as a stream.
	 */
	getOutput(): Promise<VSBufferReadableStream>;

	/**
	 * Loads an output of the result.
	 */
	getOutputRange(offset: number, length: number): Promise<VSBuffer>;

	/**
	 * Serializes the test result. Used to save and restore results
	 * in the workspace.
	 */
	toJSON(): ISerializedTestResults | undefined;
}

export const resultItemParents = function* (results: ITestResult, item: TestResultItem) {
	for (const id of TestId.fromString(item.item.extId).idsToRoot()) {
		yield results.getStateById(id.toString())!;
	}
};

/**
 * Count of the number of tests in each run state.
 */
export type TestStateCount = { [K in TestResultState]: number };

export const makeEmptyCounts = () => {
	const o: Partial<TestStateCount> = {};
	for (const state of statesInOrder) {
		o[state] = 0;
	}

	return o as TestStateCount;
};

export const sumCounts = (counts: Iterable<TestStateCount>) => {
	const total = makeEmptyCounts();
	for (const count of counts) {
		for (const state of statesInOrder) {
			total[state] += count[state];
		}
	}

	return total;
};

export const maxCountPriority = (counts: Readonly<TestStateCount>) => {
	for (const state of statesInOrder) {
		if (counts[state] > 0) {
			return state;
		}
	}

	return TestResultState.Unset;
};

const getMarkCode = (marker: number, start: boolean) => `\x1b]633;SetMark;Id=${getMarkId(marker, start)};Hidden\x07`;

/**
 * Deals with output of a {@link LiveTestResult}. By default we pass-through
 * data into the underlying write stream, but if a client requests to read it
 * we splice in the written data and then continue streaming incoming data.
 */
export class LiveOutputController {
	/** Set on close() to a promise that is resolved once closing is complete */
	private closed?: Promise<void>;
	/** Data written so far. This is available until the file closes. */
	private previouslyWritten: VSBuffer[] | undefined = [];

	private readonly dataEmitter = new Emitter<VSBuffer>();
	private readonly endEmitter = new Emitter<void>();
	private _offset = 0;

	/**
	 * Gets the number of written bytes.
	 */
	public get offset() {
		return this._offset;
	}

	constructor(
		private readonly writer: Lazy<[VSBufferWriteableStream, Promise<void>]>,
		private readonly reader: () => Promise<VSBufferReadableStream>,
		private readonly rangeReader: (offset: number, length: number) => Promise<VSBuffer>,
	) { }

	/**
	 * Appends data to the output.
	 */
	public append(data: VSBuffer, marker?: number): Promise<void> | void {
		if (this.closed) {
			return this.closed;
		}

		if (marker !== undefined) {
			data = VSBuffer.concat([
				VSBuffer.fromString(getMarkCode(marker, true)),
				data,
				VSBuffer.fromString(getMarkCode(marker, false)),
			]);
		}

		this.previouslyWritten?.push(data);
		this.dataEmitter.fire(data);
		this._offset += data.byteLength;

		return this.writer.getValue()[0].write(data);
	}

	/**
	 * Reads a range of data from the output.
	 */
	public getRange(offset: number, length: number) {
		if (!this.previouslyWritten) {
			return this.rangeReader(offset, length);
		}

		const buffer = VSBuffer.alloc(length);
		let pos = 0;
		for (const chunk of this.previouslyWritten) {
			if (pos + chunk.byteLength < offset) {
				// no-op
			} else if (pos > offset + length) {
				break;
			} else {
				const cs = Math.max(0, offset - pos);
				const bs = Math.max(0, pos - offset);
				buffer.set(chunk.slice(cs, cs + Math.min(length - bs, chunk.byteLength - cs)), bs);
			}

			pos += chunk.byteLength;
		}

		const trailing = (offset + length) - pos;
		return Promise.resolve(trailing > 0 ? buffer.slice(0, -trailing) : buffer);
	}

	/**
	 * Reads the value of the stream.
	 */
	public read() {
		if (!this.previouslyWritten) {
			return this.reader();
		}

		const stream = newWriteableBufferStream();
		for (const chunk of this.previouslyWritten) {
			stream.write(chunk);
		}

		const disposable = new DisposableStore();
		disposable.add(this.dataEmitter.event(d => stream.write(d)));
		disposable.add(this.endEmitter.event(() => stream.end()));
		stream.on('end', () => disposable.dispose());

		return Promise.resolve(stream);
	}

	/**
	 * Closes the output, signalling no more writes will be made.
	 * @returns a promise that resolves when the output is written
	 */
	public close(): Promise<void> {
		if (this.closed) {
			return this.closed;
		}

		if (!this.writer.hasValue()) {
			this.closed = Promise.resolve();
		} else {
			const [stream, ended] = this.writer.getValue();
			stream.end();
			this.closed = ended;
		}

		this.endEmitter.fire();
		this.closed.then(() => {
			this.previouslyWritten = undefined;
			this.dataEmitter.dispose();
			this.endEmitter.dispose();
		});

		return this.closed;
	}
}

interface TestResultItemWithChildren extends TestResultItem {
	/** Children in the run */
	children: TestResultItemWithChildren[];
}

const itemToNode = (controllerId: string, item: ITestItem, parent: string | null): TestResultItemWithChildren => ({
	controllerId,
	expand: TestItemExpandState.NotExpandable,
	item: { ...item },
	children: [],
	tasks: [],
	ownComputedState: TestResultState.Unset,
	computedState: TestResultState.Unset,
});

export const enum TestResultItemChangeReason {
	ComputedStateChange,
	OwnStateChange,
}

export type TestResultItemChange = { item: TestResultItem; result: ITestResult } & (
	| { reason: TestResultItemChangeReason.ComputedStateChange }
	| { reason: TestResultItemChangeReason.OwnStateChange; previousState: TestResultState; previousOwnDuration: number | undefined }
);

/**
 * Results of a test. These are created when the test initially started running
 * and marked as "complete" when the run finishes.
 */
export class LiveTestResult implements ITestResult {
	private readonly completeEmitter = new Emitter<void>();
	private readonly changeEmitter = new Emitter<TestResultItemChange>();
	private readonly testById = new Map<string, TestResultItemWithChildren>();
	private testMarkerCounter = 0;
	private _completedAt?: number;

	public readonly onChange = this.changeEmitter.event;
	public readonly onComplete = this.completeEmitter.event;
	public readonly tasks: ITestRunTaskResults[] = [];
	public readonly name = localize('runFinished', 'Test run at {0}', new Date().toLocaleString());

	/**
	 * @inheritdoc
	 */
	public get completedAt() {
		return this._completedAt;
	}

	/**
	 * @inheritdoc
	 */
	public readonly counts: { [K in TestResultState]: number } = makeEmptyCounts();

	/**
	 * @inheritdoc
	 */
	public get tests() {
		return this.testById.values();
	}

	private readonly computedStateAccessor: IComputedStateAccessor<TestResultItemWithChildren> = {
		getOwnState: i => i.ownComputedState,
		getCurrentComputedState: i => i.computedState,
		setComputedState: (i, s) => i.computedState = s,
		getChildren: i => i.children,
		getParents: i => {
			const { testById: testByExtId } = this;
			return (function* () {
				const parentId = TestId.fromString(i.item.extId).parentId;
				if (parentId) {
					for (const id of parentId.idsToRoot()) {
						yield testByExtId.get(id.toString())!;
					}
				}
			})();
		},
	};

	constructor(
		public readonly id: string,
		public readonly output: LiveOutputController,
		public readonly persist: boolean,
		public readonly request: ResolvedTestRunRequest,
	) {
	}

	/**
	 * @inheritdoc
	 */
	public getStateById(extTestId: string) {
		return this.testById.get(extTestId);
	}

	/**
	 * Appends output that occurred during the test run.
	 */
	public appendOutput(output: VSBuffer, taskId: string, location?: IRichLocation, testId?: string): void {
		const preview = output.byteLength > 100 ? output.slice(0, 100).toString() + '…' : output.toString();
		let marker: number | undefined;

		// currently, the UI only exposes jump-to-message from tests or locations,
		// so no need to mark outputs that don't come from either of those.
		if (testId || location) {
			marker = this.testMarkerCounter++;
		}

		const message: ITestOutputMessage = {
			location,
			message: removeAnsiEscapeCodes(preview),
			offset: this.output.offset,
			length: output.byteLength,
			marker: marker,
			type: TestMessageType.Output,
		};

		this.output.append(output, marker);

		const index = this.mustGetTaskIndex(taskId);
		if (testId) {
			this.testById.get(testId)?.tasks[index].messages.push(message);
		} else {
			this.tasks[index].otherMessages.push(message);
		}
	}

	/**
	 * Adds a new run task to the results.
	 */
	public addTask(task: ITestRunTask) {
		const index = this.tasks.length;
		this.tasks.push({ ...task, coverage: new MutableObservableValue(undefined), otherMessages: [] });

		for (const test of this.tests) {
			test.tasks.push({ duration: undefined, messages: [], state: TestResultState.Unset });
			this.fireUpdateAndRefresh(test, index, TestResultState.Queued);
		}
	}

	/**
	 * Add the chain of tests to the run. The first test in the chain should
	 * be either a test root, or a previously-known test.
	 */
	public addTestChainToRun(controllerId: string, chain: ReadonlyArray<ITestItem>) {
		let parent = this.testById.get(chain[0].extId);
		if (!parent) { // must be a test root
			parent = this.addTestToRun(controllerId, chain[0], null);
		}

		for (let i = 1; i < chain.length; i++) {
			parent = this.addTestToRun(controllerId, chain[i], parent.item.extId);
		}

		for (let i = 0; i < this.tasks.length; i++) {
			this.fireUpdateAndRefresh(parent, i, TestResultState.Queued);
		}

		return undefined;
	}

	/**
	 * Updates the state of the test by its internal ID.
	 */
	public updateState(testId: string, taskId: string, state: TestResultState, duration?: number) {
		const entry = this.testById.get(testId);
		if (!entry) {
			return;
		}

		const index = this.mustGetTaskIndex(taskId);

		const oldTerminalStatePrio = terminalStatePriorities[entry.tasks[index].state];
		const newTerminalStatePrio = terminalStatePriorities[state];

		// Ignore requests to set the state from one terminal state back to a
		// "lower" one, e.g. from failed back to passed:
		if (oldTerminalStatePrio !== undefined &&
			(newTerminalStatePrio === undefined || newTerminalStatePrio < oldTerminalStatePrio)) {
			return;
		}

		this.fireUpdateAndRefresh(entry, index, state, duration);
	}

	/**
	 * Appends a message for the test in the run.
	 */
	public appendMessage(testId: string, taskId: string, message: ITestMessage) {
		const entry = this.testById.get(testId);
		if (!entry) {
			return;
		}

		entry.tasks[this.mustGetTaskIndex(taskId)].messages.push(message);
		this.changeEmitter.fire({
			item: entry,
			result: this,
			reason: TestResultItemChangeReason.OwnStateChange,
			previousState: entry.ownComputedState,
			previousOwnDuration: entry.ownDuration,
		});
	}

	/**
	 * @inheritdoc
	 */
	public getOutput() {
		return this.output.read();
	}

	/**
	 * @inheritdoc
	 */
	public getOutputRange(offset: number, bytes: number) {
		return this.output.getRange(offset, bytes);
	}

	/**
	 * Marks the task in the test run complete.
	 */
	public markTaskComplete(taskId: string) {
		this.tasks[this.mustGetTaskIndex(taskId)].running = false;
		this.setAllToState(
			TestResultState.Unset,
			taskId,
			t => t.state === TestResultState.Queued || t.state === TestResultState.Running,
		);
	}

	/**
	 * Notifies the service that all tests are complete.
	 */
	public markComplete() {
		if (this._completedAt !== undefined) {
			throw new Error('cannot complete a test result multiple times');
		}

		for (const task of this.tasks) {
			if (task.running) {
				this.markTaskComplete(task.id);
			}
		}

		this._completedAt = Date.now();
		this.completeEmitter.fire();
	}

	/**
	 * @inheritdoc
	 */
	public toJSON(): ISerializedTestResults | undefined {
		return this.completedAt && this.persist ? this.doSerialize.getValue() : undefined;
	}

	/**
	 * Updates all tests in the collection to the given state.
	 */
	protected setAllToState(state: TestResultState, taskId: string, when: (task: ITestTaskState, item: TestResultItem) => boolean) {
		const index = this.mustGetTaskIndex(taskId);
		for (const test of this.testById.values()) {
			if (when(test.tasks[index], test)) {
				this.fireUpdateAndRefresh(test, index, state);
			}
		}
	}

	private fireUpdateAndRefresh(entry: TestResultItem, taskIndex: number, newState: TestResultState, newOwnDuration?: number) {
		const previousOwnComputed = entry.ownComputedState;
		const previousOwnDuration = entry.ownDuration;
		const changeEvent: TestResultItemChange = {
			item: entry,
			result: this,
			reason: TestResultItemChangeReason.OwnStateChange,
			previousState: previousOwnComputed,
			previousOwnDuration: previousOwnDuration,
		};

		entry.tasks[taskIndex].state = newState;
		if (newOwnDuration !== undefined) {
			entry.tasks[taskIndex].duration = newOwnDuration;
			entry.ownDuration = Math.max(entry.ownDuration || 0, newOwnDuration);
		}

		const newOwnComputed = maxPriority(...entry.tasks.map(t => t.state));
		if (newOwnComputed === previousOwnComputed) {
			if (newOwnDuration !== previousOwnDuration) {
				this.changeEmitter.fire(changeEvent); // fire manually since state change won't do it
			}
			return;
		}

		entry.ownComputedState = newOwnComputed;
		this.counts[previousOwnComputed]--;
		this.counts[newOwnComputed]++;
		refreshComputedState(this.computedStateAccessor, entry).forEach(t =>
			this.changeEmitter.fire(t === entry ? changeEvent : {
				item: t,
				result: this,
				reason: TestResultItemChangeReason.ComputedStateChange,
			}),
		);
	}

	private addTestToRun(controllerId: string, item: ITestItem, parent: string | null) {
		const node = itemToNode(controllerId, item, parent);
		this.testById.set(item.extId, node);
		this.counts[TestResultState.Unset]++;

		if (parent) {
			this.testById.get(parent)?.children.push(node);
		}

		if (this.tasks.length) {
			for (let i = 0; i < this.tasks.length; i++) {
				node.tasks.push({ duration: undefined, messages: [], state: TestResultState.Queued });
			}
		}

		return node;
	}

	private mustGetTaskIndex(taskId: string) {
		const index = this.tasks.findIndex(t => t.id === taskId);
		if (index === -1) {
			throw new Error(`Unknown task ${taskId} in updateState`);
		}

		return index;
	}

	private readonly doSerialize = new Lazy((): ISerializedTestResults => ({
		id: this.id,
		completedAt: this.completedAt!,
		tasks: this.tasks.map(t => ({ id: t.id, name: t.name })),
		name: this.name,
		request: this.request,
		items: [...this.testById.values()].map(TestResultItem.serializeWithoutMessages),
	}));
}

/**
 * Test results hydrated from a previously-serialized test run.
 */
export class HydratedTestResult implements ITestResult {
	/**
	 * @inheritdoc
	 */
	public readonly counts = makeEmptyCounts();

	/**
	 * @inheritdoc
	 */
	public readonly id: string;

	/**
	 * @inheritdoc
	 */
	public readonly completedAt: number;

	/**
	 * @inheritdoc
	 */
	public readonly tasks: ITestRunTaskResults[];

	/**
	 * @inheritdoc
	 */
	public get tests() {
		return this.testById.values();
	}

	/**
	 * @inheritdoc
	 */
	public readonly name: string;

	/**
	 * @inheritdoc
	 */
	public readonly request: ResolvedTestRunRequest;

	private readonly testById = new Map<string, TestResultItem>();

	constructor(
		private readonly serialized: ISerializedTestResults,
		private readonly outputLoader: () => Promise<VSBufferReadableStream>,
		private readonly outputRangeLoader: (offset: number, length: number) => Promise<VSBuffer>,
		private readonly persist = true,
	) {
		this.id = serialized.id;
		this.completedAt = serialized.completedAt;
		this.tasks = serialized.tasks.map((task, i) => ({
			id: task.id,
			name: task.name,
			running: false,
			coverage: staticObservableValue(undefined),
			otherMessages: []
		}));
		this.name = serialized.name;
		this.request = serialized.request;

		for (const item of serialized.items) {
			const de = TestResultItem.deserialize(item);
			this.counts[de.ownComputedState]++;
			this.testById.set(item.item.extId, de);
		}
	}

	/**
	 * @inheritdoc
	 */
	public getOutputRange(offset: number, bytes: number) {
		return this.outputRangeLoader(offset, bytes);
	}

	/**
	 * @inheritdoc
	 */
	public getStateById(extTestId: string) {
		return this.testById.get(extTestId);
	}

	/**
	 * @inheritdoc
	 */
	public getOutput() {
		return this.outputLoader();
	}

	/**
	 * @inheritdoc
	 */
	public toJSON(): ISerializedTestResults | undefined {
		return this.persist ? this.serialized : undefined;
	}
}


text:
[![Gem Version](https://badge.fury.io/rb/nameit.png)](http://badge.fury.io/rb/nameit)
[![Build Status](https://secure.travis-ci.org/fnichol/nameit.png)](http://travis-ci.org/fnichol/nameit)
[![Code Climate](https://codeclimate.com/github/fnichol/nameit.png)](https://codeclimate.com/github/fnichol/nameit)
[![Dependency Status](https://gemnasium.com/fnichol/nameit.png)](https://gemnasium.com/fnichol/nameit)

Nameit is a small zero-dependency library and tool that helps you generate a random name for a project, database, session--you decide. You get glorious **adjective-noun** style names such as **"pushy-clock"** and **"lovely-ducks"** or ask for a random number on the end to give you names like **"numberless-cactus-123"** and **"superb-shoes-915"**.

* No dependencies
* Runs on all the Ruby implementations
* Uses `SecureRandom`

##  Installation

Add this line to your application's Gemfile:

```ruby
gem 'nameit'
```

And then execute:

```sh
$ bundle
```

Or install it yourself as:

```sh
$ gem install nameit
```

##  Usage

###  nameit Command

Nameit ships with the `nameit` command so you can get a shiny new name right from the command line:

```sh
$ nameit
abhorrent-flowers
$ nameit 3
cowardly-pot
quickest-sleep
heartbreaking-lamp
```

###  Ruby Library

Use it with a class method for a quick one-offs:

```ruby
require 'nameit'

Nameit.generate
# => "sassy-clocks"
Nameit.generate
# => "dazzling-comb"

Nameit.generate(number: true)
# => "blushing-camera-632"
```

Or for peppier performance (to save on re-reading the data sources), use a `Nameit` instance:

```ruby
require 'nameit'

nameit = Nameit.new

3.times.map { nameit.generate }
# => ["ethereal-music", "historical-argument", "recondite-pear"]

nameit = Nameit.new(number: true)

2.times.map { nameit.generate }
# => ["peaceful-book-260", "synonymous-lizards-501"]
```

##  Development

* Source hosted at [GitHub][repo]
* Report issues/questions/feature requests on [GitHub Issues][issues]

Pull requests are very welcome! Make sure your patches are well tested.
Ideally create a topic branch for every separate change you make. For
example:

1. Fork the repo
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

##  Authors

Created and maintained by [Fletcher Nichol][fnichol] (<fnichol@nichol.ca>)

##  License

MIT (see [LICENSE][license])

[license]:      https://github.com/fnichol/nameit/blob/master/LICENSE.txt
[fnichol]:      https://github.com/fnichol
[repo]:         https://github.com/fnichol/nameit
[issues]:       https://github.com/fnichol/nameit/issues
[contributors]: https://github.com/fnichol/nameit/contributors

redpajama_set_name: RedPajamaGithub


text:
{% load humanize %}

Total reads (all samples)
    {{ overall_stats.total_reads|intword }} ({{ overall_stats.total_reads|intcomma }})

Read length
    {{ overall_stats.read_length_mean|floatformat }}
    {% if  overall_stats.read_length_stddev %}
    ± {{ overall_stats.read_length_stddev|floatformat }}
    {% endif %}

{% if overall_stats.gc_mean %}

    Mean % GC content
    {{ overall_stats.gc_mean|floatformat }}
    {% if overall_stats.gc_mean %}
    ± {{ overall_stats.gc_stddev|floatformat }}
    {% endif %}

{% endif %}

± values show one standard deviation.


text:
int main() {
    printf("Hello, world!\n");
    sixenseInit();
    sleep(2);
    int maxB = sixenseGetMaxBases();
    sixenseSetActiveBase(0);
    sixenseAutoEnableHemisphereTracking(0);
    sixenseSetActiveBase(0);
    int conn0 = sixenseIsBaseConnected(0);
    int conn1 = sixenseIsBaseConnected(1);
    sixenseSetActiveBase(0);
    int conn0b = sixenseIsBaseConnected(0);
    int maxCon = sixenseGetMaxControllers();
    int e0 = sixenseIsControllerEnabled(0);
    sixenseControllerData dat;
    printf("Active: %d, conn: %d %d %d, maxContr: %d, e0 enabled: %d, act: %d\n", maxB, conn0, conn0b, conn1, maxCon, e0, sixenseGetNumActiveControllers());

    while(1) {
        sixenseGetNewestData(0, &dat);
        printf("Pos: %f %f %f\n", dat.pos[0], dat.pos[1], dat.pos[2]);
        usleep(1000000 / 128.0f);
    }
    sixenseExit();
}


text:
package org.hisp.dhis.dataelementhistory;

import org.apache.commons.math3.util.MathUtils;
import org.apache.commons.math3.util.Precision;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.datavalue.DataValue;
import org.hisp.dhis.datavalue.DataValueService;
import org.hisp.dhis.minmax.MinMaxDataElement;
import org.hisp.dhis.minmax.MinMaxDataElementService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodService;

import java.util.List;

/**
 * @author Torgeir Lorange Ostby
 */
public class DefaultHistoryRetriever
    implements HistoryRetriever
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private MinMaxDataElementService minMaxDataElementService;

    public void setMinMaxDataElementService( MinMaxDataElementService minMaxDataElementService )
    {
        this.minMaxDataElementService = minMaxDataElementService;
    }

    private DataValueService dataValueService;

    public void setDataValueService( DataValueService dataValueService )
    {
        this.dataValueService = dataValueService;
    }

    private PeriodService periodService;

    public void setPeriodService( PeriodService periodService )
    {
        this.periodService = periodService;
    }

    // -------------------------------------------------------------------------
    // HistoryRetriever implementation
    // -------------------------------------------------------------------------

    @Override
    public DataElementHistory getHistory( DataElement dataElement, DataElementCategoryOptionCombo optionCombo,
        OrganisationUnit organisationUnit, Period lastPeriod, int historyLength )
    {
        if ( !dataElement.getValueType().isNumeric() )
        {
            return null; // TODO
        }

        // ---------------------------------------------------------------------
        // Initialise history
        // ---------------------------------------------------------------------

        DataElementHistory history = new DataElementHistory();
        history.setDataElement( dataElement );
        history.setOptionCombo( optionCombo );
        history.setOrganisationUnit( organisationUnit );
        history.setHistoryLength( historyLength );
        addMinMaxLimits( organisationUnit, dataElement, optionCombo, history );

        // ---------------------------------------------------------------------
        // Create history points
        // ---------------------------------------------------------------------

        List<Period> periods = periodService.getPeriods( lastPeriod, historyLength );

        double max = 1;
        double average = 0;
        double total = 0;
        int count = 0;

        if ( history.getMaxLimit() != null )
        {
            max = Math.max( max, history.getMaxLimit() );
        }

        for ( Period period : periods )
        {
            DataElementHistoryPoint historyPoint = new DataElementHistoryPoint();
            historyPoint.setPeriod( period );

            Double value = getValue( dataElement, optionCombo, organisationUnit, period );

            if ( value != null )
            {
                historyPoint.setValue( value );
            }

            if ( historyPoint.getValue() != null )
            {
                max = Math.max( max, historyPoint.getValue() );
                total += historyPoint.getValue();
                average = total / ++count;
                average = Precision.round( average, 1 );
            }

            historyPoint.setAverage( average );

            history.getHistoryPoints().add( historyPoint );
        }

        history.setMaxHistoryValue( max );

        double maxValue = getMaxValue( history );

        if ( !MathUtils.equals( maxValue, Double.NEGATIVE_INFINITY ) )
        {
            history.setMaxValue( maxValue );

            double minValue = getMinValue( history );
            history.setMinValue( minValue );
        }

        return history;
    }

    // -------------------------------------------------------------------------
    // Supportive methods
    // -------------------------------------------------------------------------

    private void addMinMaxLimits( OrganisationUnit organisationUnit, DataElement dataElement,
        DataElementCategoryOptionCombo optionCombo, DataElementHistory history )
    {
        MinMaxDataElement minMaxDataElement = minMaxDataElementService.getMinMaxDataElement( organisationUnit,
            dataElement, optionCombo );

        if ( minMaxDataElement != null )
        {
            history.setMaxLimit( minMaxDataElement.getMax() );
            history.setMinLimit( minMaxDataElement.getMin() );
        }
    }

    /**
     * Finds the lowest value entered in the periode given by
     * history.historyLenght.
     *
     * @param history DataElementHistory
     * @return the lowest Double value entred. If no values are entred,
     * Double.MAX_VALUE is returned
     */
    private Double getMinValue( DataElementHistory history )
    {
        double value = Double.MAX_VALUE;
        List<DataElementHistoryPoint> historyPoints = history.getHistoryPoints();

        for ( DataElementHistoryPoint point : historyPoints )
        {
            if ( point.getValue() != null )
            {
                if ( point.getValue() < value )
                {
                    value = point.getValue();
                }
            }
        }

        return value;
    }

    /**
     * Finds the highest value entered in the periode given by
     * history.historyLenght.
     *
     * @param history DataElementHistory
     * @return the highest entred value. If no value is entred
     * Double.NEGATIVE_INFINITY is returned
     */
    private Double getMaxValue( DataElementHistory history )
    {
        double value = Double.NEGATIVE_INFINITY;
        List<DataElementHistoryPoint> historyPoints = history.getHistoryPoints();

        for ( DataElementHistoryPoint point : historyPoints )
        {
            if ( point.getValue() != null )
            {
                if ( point.getValue() > value )
                {
                    value = point.getValue();
                }
            }
        }

        return value;
    }

    private Double getValue( DataElement dataElement, DataElementCategoryOptionCombo optionCombo,
        OrganisationUnit organisationUnit, Period period )
    {
        DataValue dataValue = dataValueService.getDataValue( dataElement, period, organisationUnit, optionCombo );

        if ( dataValue != null )
        {
            if ( dataValue.getValue() != null )
            {
                return parseValue( dataValue.getValue() );

            }
        }

        return null;
    }

    private Double parseValue( String value )
    {
        try
        {
            return Double.parseDouble( value );
        }
        catch ( NumberFormatException e )
        {
            throw new RuntimeException( "Failed to parse double: " + value, e );
        }
    }
}


text:
package problems.easy;

import problems.utils.TreeNode;

/**
 * Created by sherxon on 2016-12-24.
 */
public class SameTree {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null && q==null)return true;
        return q.val == p.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/explorer_vertical_margin"
    android:paddingLeft="@dimen/explorer_horizontal_margin"
    android:paddingRight="@dimen/explorer_horizontal_margin"
    android:paddingTop="@dimen/explorer_vertical_margin">

    <ImageView
        android:id="@id/android:icon"
        android:layout_width="@dimen/explorer_icon_size"
        android:layout_height="@dimen/explorer_icon_size"
        android:tint="?attr/colorControlNormal"/>

    <View
        android:layout_width="@dimen/explorer_horizontal_margin"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1">

        <TextView
            android:id="@id/android:text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:ellipsize="end"
            android:maxLines="1"/>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@id/android:text2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="?android:textColorHint"/>

            <View
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_weight="1"/>

            <TextView
                android:id="@+id/last_modified"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="?android:textColorHint"
                android:gravity="end"/>

        </LinearLayout>

    </LinearLayout>

    <View
        android:id="@+id/spacer"
        android:layout_width="@dimen/explorer_horizontal_margin"
        android:layout_height="wrap_content"/>

    <CheckBox
        android:id="@id/android:checkbox"
        android:focusable="false"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</LinearLayout>


text:
/**
 * Created by 李 on 2017/3/27.
 */
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {ProjectIndexComponent} from "./project-index.component";
import {ProjectTaskComponent} from "./project-task.component";
import {ProjectCountComponent} from "./project-count.component";

const routes: Routes = [
  {
    path:'',
    component:ProjectIndexComponent,
    children:[
      {
        path:'',
        redirectTo:"project-task",
        pathMatch:'full'
      },
      {
        path:'project-task',
        component:ProjectTaskComponent
      },
      {
        path:"project-count",
        component:ProjectCountComponent
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class ProjectRoutingModule { }


text:
#include "NewRendererTest.h"

static int sceneIdx = -1;

Layer* nextSpriteTestAction();
Layer* backSpriteTestAction();
Layer* restartSpriteTestAction();

static std::function<Layer*()> createFunctions[] =
{
    CL(NewSpriteTest),
    CL(NewSpriteBatchTest),
    CL(GroupCommandTest),
    CL(NewClippingNodeTest),
    CL(NewDrawNodeTest),
    CL(NewCullingTest),
    CL(VBOFullTest),
    CL(CaptureScreenTest)
};

#define MAX_LAYER    (sizeof(createFunctions) / sizeof(createFunctions[0]))

Layer* nextTest()
{
    sceneIdx++;
    sceneIdx = sceneIdx % MAX_LAYER;

    auto layer = (createFunctions[sceneIdx])();
    return layer;
}

Layer* prevTest()
{
    sceneIdx--;
    int total = MAX_LAYER;
    if( sceneIdx < 0 )
        sceneIdx += total;

    auto layer = (createFunctions[sceneIdx])();

    return layer;
}

Layer* restartTest()
{
    auto layer = (createFunctions[sceneIdx])();

    return layer;
}

void NewRendererTestScene::runThisTest()
{
    auto layer = nextTest();
    addChild(layer);

    Director::getInstance()->replaceScene(this);
}

MultiSceneTest::MultiSceneTest()
{

}

MultiSceneTest::~MultiSceneTest()
{

}

std::string MultiSceneTest::title() const
{
    return "New Renderer";
}

std::string MultiSceneTest::subtitle() const
{
    return "MultiSceneTest";
}

void MultiSceneTest::onEnter()
{
    BaseTest::onEnter();
}

void MultiSceneTest::restartCallback(Ref *sender)
{
    auto s = new (std::nothrow) NewRendererTestScene();
    s->addChild(restartTest());

    Director::getInstance()->replaceScene(s);
    s->release();
}

void MultiSceneTest::nextCallback(Ref *sender)
{
    auto s = new (std::nothrow) NewRendererTestScene();
    s->addChild(nextTest());

    Director::getInstance()->replaceScene(s);
    s->release();
}

void MultiSceneTest::backCallback(Ref *sender)
{
    auto s = new (std::nothrow) NewRendererTestScene();
    s->addChild(prevTest());

    Director::getInstance()->replaceScene(s);
    s->release();
}

NewSpriteTest::NewSpriteTest()
{
    auto touchListener = EventListenerTouchAllAtOnce::create();
    touchListener->onTouchesEnded = CC_CALLBACK_2(NewSpriteTest::onTouchesEnded, this);

    createSpriteTest();
    createNewSpriteTest();
}

NewSpriteTest::~NewSpriteTest()
{

}

void NewSpriteTest::createSpriteTest()
{
    Size winSize = Director::getInstance()->getWinSize();

    Sprite* parent = Sprite::create("Images/grossini.png");
    parent->setPosition(winSize.width/4, winSize.height/2);
    Sprite* child1 = Sprite::create("Images/grossinis_sister1.png");
    child1->setPosition(0.0f, -20.0f);
    Sprite* child2 = Sprite::create("Images/grossinis_sister2.png");
    child2->setPosition(20.0f, -20.0f);
    Sprite* child3 = Sprite::create("Images/grossinis_sister1.png");
    child3->setPosition(40.0f, -20.0f);
    Sprite* child4 = Sprite::create("Images/grossinis_sister2.png");
    child4->setPosition(60.0f, -20.0f);
    Sprite* child5 = Sprite::create("Images/grossinis_sister2.png");
    child5->setPosition(80.0f, -20.0f);
    Sprite* child6 = Sprite::create("Images/grossinis_sister2.png");
    child6->setPosition(100.0f, -20.0f);
    Sprite* child7 = Sprite::create("Images/grossinis_sister2.png");
    child7->setPosition(120.0f, -20.0f);

    parent->addChild(child1);
    parent->addChild(child2);
    parent->addChild(child3);
    parent->addChild(child4);
    parent->addChild(child5);
    parent->addChild(child6);
    parent->addChild(child7);
    addChild(parent);
}

void NewSpriteTest::createNewSpriteTest()
{
    Size winSize = Director::getInstance()->getWinSize();

    Sprite* parent = Sprite::create("Images/grossini.png");
    parent->setPosition(winSize.width*2/3, winSize.height/2);
    Sprite* child1 = Sprite::create("Images/grossinis_sister1.png");
    child1->setPosition(0.0f, -20.0f);
    Sprite* child2 = Sprite::create("Images/grossinis_sister2.png");
    child2->setPosition(20.0f, -20.0f);
    Sprite* child3 = Sprite::create("Images/grossinis_sister1.png");
    child3->setPosition(40.0f, -20.0f);
    Sprite* child4 = Sprite::create("Images/grossinis_sister2.png");
    child4->setPosition(60.0f, -20.0f);
    Sprite* child5 = Sprite::create("Images/grossinis_sister2.png");
    child5->setPosition(80.0f, -20.0f);
    Sprite* child6 = Sprite::create("Images/grossinis_sister2.png");
    child6->setPosition(100.0f, -20.0f);
    Sprite* child7 = Sprite::create("Images/grossinis_sister2.png");
    child7->setPosition(120.0f, -20.0f);

    parent->addChild(child1);
    parent->addChild(child2);
    parent->addChild(child3);
    parent->addChild(child4);
    parent->addChild(child5);
    parent->addChild(child6);
    parent->addChild(child7);
    addChild(parent);
}

void NewSpriteTest::onTouchesEnded(const std::vector<Touch *> &touches, Event *event)
{

}

std::string NewSpriteTest::title() const
{
    return "Renderer";
}

std::string NewSpriteTest::subtitle() const
{
    return "SpriteTest";
}

class SpriteInGroupCommand : public Sprite
{
protected:
    GroupCommand _spriteWrapperCommand;
public:
    static SpriteInGroupCommand* create(const std::string& filename);

    virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override;
};

SpriteInGroupCommand* SpriteInGroupCommand::create(const std::string &filename)
{
    SpriteInGroupCommand* sprite = new (std::nothrow) SpriteInGroupCommand();
    sprite->initWithFile(filename);
    sprite->autorelease();
    return sprite;
}

void SpriteInGroupCommand::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{
    CCASSERT(renderer, "Render is null");
    _spriteWrapperCommand.init(_globalZOrder);
    renderer->addCommand(&_spriteWrapperCommand);
    renderer->pushGroup(_spriteWrapperCommand.getRenderQueueID());
    Sprite::draw(renderer, transform, flags);
    renderer->popGroup();
}

GroupCommandTest::GroupCommandTest()
{
    auto sprite = SpriteInGroupCommand::create("Images/grossini.png");
    Size winSize = Director::getInstance()->getWinSize();
    sprite->setPosition(winSize.width/2,winSize.height/2);
    addChild(sprite);
}

GroupCommandTest::~GroupCommandTest()
{
}

std::string GroupCommandTest::title() const
{
    return "Renderer";
}

std::string GroupCommandTest::subtitle() const
{
    return "GroupCommandTest: You should see a sprite";
}

//-------- New Sprite Batch Test

NewSpriteBatchTest::NewSpriteBatchTest()
{
    auto touchListener = EventListenerTouchAllAtOnce::create();
    touchListener->onTouchesEnded = CC_CALLBACK_2(NewSpriteBatchTest::onTouchesEnded, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);

    auto BatchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 50);
    addChild(BatchNode, 0, kTagSpriteBatchNode);
}

NewSpriteBatchTest::~NewSpriteBatchTest()
{

}

std::string NewSpriteBatchTest::title() const
{
    return "Renderer";
}

std::string NewSpriteBatchTest::subtitle() const
{
    return "SpriteBatchTest";
}

void NewSpriteBatchTest::onTouchesEnded(const std::vector<Touch *> &touches, Event *event)
{
    for (auto &touch : touches)
    {
        auto location = touch->getLocation();
        addNewSpriteWithCoords(location);
    }
}

void NewSpriteBatchTest::addNewSpriteWithCoords(Vec2 p)
{
    auto BatchNode = static_cast<SpriteBatchNode*>( getChildByTag(kTagSpriteBatchNode) );

    int idx = (int) (CCRANDOM_0_1() * 1400 / 100);
    int x = (idx%5) * 85;
    int y = (idx/5) * 121;

    auto sprite = Sprite::createWithTexture(BatchNode->getTexture(), Rect(x,y,85,121));
    BatchNode->addChild(sprite);

    sprite->setPosition( Vec2( p.x, p.y) );

    ActionInterval* action;
    float random = CCRANDOM_0_1();

    if( random < 0.20 )
        action = ScaleBy::create(3, 2);
    else if(random < 0.40)
        action = RotateBy::create(3, 360);
    else if( random < 0.60)
        action = Blink::create(1, 3);
    else if( random < 0.8 )
        action = TintBy::create(2, 0, -255, -255);
    else
        action = FadeOut::create(2);

    auto action_back = action->reverse();
    auto seq = Sequence::create(action, action_back, nullptr);

    sprite->runAction( RepeatForever::create(seq));
}

NewClippingNodeTest::NewClippingNodeTest()
{
    auto s = Director::getInstance()->getWinSize();

    auto clipper = ClippingNode::create();
    clipper->setTag( kTagClipperNode );
    clipper->setContentSize(  Size(200, 200) );
    clipper->setAnchorPoint(  Vec2(0.5, 0.5) );
    clipper->setPosition( Vec2(s.width / 2, s.height / 2) );

    clipper->runAction(RepeatForever::create(RotateBy::create(1, 45)));
    this->addChild(clipper);

    // TODO: Fix draw node as clip node
//    auto stencil = NewDrawNode::create();
//    Vec2 rectangle[4];
//    rectangle[0] = Vec2(0, 0);
//    rectangle[1] = Vec2(clipper->getContentSize().width, 0);
//    rectangle[2] = Vec2(clipper->getContentSize().width, clipper->getContentSize().height);
//    rectangle[3] = Vec2(0, clipper->getContentSize().height);
//
//    Color4F white(1, 1, 1, 1);
//    stencil->drawPolygon(rectangle, 4, white, 1, white);
//    clipper->setStencil(stencil);

    //Test with alpha Test
    clipper->setAlphaThreshold(0.05f);
    auto stencil = Sprite::create("Images/grossini.png");
    stencil->setPosition(s.width/2, s.height/2);
    clipper->setStencil(stencil);

    auto content = Sprite::create("Images/background2.png");
    content->setTag( kTagContentNode );
    content->setAnchorPoint(  Vec2(0.5, 0.5) );
    content->setPosition( Vec2(clipper->getContentSize().width / 2, clipper->getContentSize().height / 2) );
    clipper->addChild(content);

    _scrolling = false;

    auto listener = EventListenerTouchAllAtOnce::create();
    listener->onTouchesBegan = CC_CALLBACK_2(NewClippingNodeTest::onTouchesBegan, this);
    listener->onTouchesMoved = CC_CALLBACK_2(NewClippingNodeTest::onTouchesMoved, this);
    listener->onTouchesEnded = CC_CALLBACK_2(NewClippingNodeTest::onTouchesEnded, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}

NewClippingNodeTest::~NewClippingNodeTest()
{

}

std::string NewClippingNodeTest::title() const
{
    return "New Render";
}

std::string NewClippingNodeTest::subtitle() const
{
    return "ClipNode";
}

void NewClippingNodeTest::onTouchesBegan(const std::vector<Touch *> &touches, Event *event)
{
    Touch *touch = touches[0];
    auto clipper = this->getChildByTag(kTagClipperNode);
    Vec2 point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView()));
    auto rect = Rect(0, 0, clipper->getContentSize().width, clipper->getContentSize().height);
    _scrolling = rect.containsPoint(point);
    _lastPoint = point;
}

void NewClippingNodeTest::onTouchesMoved(const std::vector<Touch *> &touches, Event *event)
{
    if (!_scrolling) return;
    Touch *touch = touches[0];
    auto clipper = this->getChildByTag(kTagClipperNode);
    auto point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView()));
    Vec2 diff = point - _lastPoint;
    auto content = clipper->getChildByTag(kTagContentNode);
    content->setPosition(content->getPosition() + diff);
    _lastPoint = point;
}

void NewClippingNodeTest::onTouchesEnded(const std::vector<Touch *> &touches, Event *event)
{
    if (!_scrolling) return;
    _scrolling = false;
}

/**
* NewDrawNode
*/
NewDrawNodeTest::NewDrawNodeTest()
{
    auto s = Director::getInstance()->getWinSize();

    auto parent = Node::create();
    parent->setPosition(s.width/2, s.height/2);
    addChild(parent);

    auto rectNode = DrawNode::create();
    Vec2 rectangle[4];
    rectangle[0] = Vec2(-50, -50);
    rectangle[1] = Vec2(50, -50);
    rectangle[2] = Vec2(50, 50);
    rectangle[3] = Vec2(-50, 50);

    Color4F white(1, 1, 1, 1);
    rectNode->drawPolygon(rectangle, 4, white, 1, white);
    parent->addChild(rectNode);
}

NewDrawNodeTest::~NewDrawNodeTest()
{

}

std::string NewDrawNodeTest::title() const
{
    return "New Render";
}

std::string NewDrawNodeTest::subtitle() const
{
    return "DrawNode";
}

NewCullingTest::NewCullingTest()
{
    Size size = Director::getInstance()->getWinSize();
    auto sprite = Sprite::create("Images/btn-about-normal-vertical.png");
    sprite->setRotation(5);
    sprite->setPosition(Vec2(size.width/2,size.height/3));
    sprite->setScale(2);
    addChild(sprite);

    auto sprite2 = Sprite::create("Images/btn-about-normal-vertical.png");
    sprite2->setRotation(-85);
    sprite2->setPosition(Vec2(size.width/2,size.height * 2/3));
    sprite2->setScale(2);
    addChild(sprite2);

    auto listener = EventListenerTouchOneByOne::create();
    listener->setSwallowTouches(true);

    listener->onTouchBegan = CC_CALLBACK_2(NewCullingTest::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(NewCullingTest::onTouchMoved, this);

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

}

bool NewCullingTest::onTouchBegan(Touch* touch, Event  *event)
{
    auto pos = touch->getLocation();
    _lastPos = pos;
    return true;
}

void NewCullingTest::onTouchMoved(Touch* touch, Event  *event)
{
    auto pos = touch->getLocation();

    auto offset = pos - _lastPos;

    auto layerPos = getPosition();
    auto newPos = layerPos + offset;

    setPosition(newPos);
    _lastPos = pos;
}

NewCullingTest::~NewCullingTest()
{

}

std::string NewCullingTest::title() const
{
    return "New Render";
}

std::string NewCullingTest::subtitle() const
{
    return "Drag the layer to test the result of culling";
}

VBOFullTest::VBOFullTest()
{
    Size s = Director::getInstance()->getWinSize();
    Node* parent = Node::create();
    parent->setPosition(0,0);
    addChild(parent);

    for (int i=0; i< Renderer::VBO_SIZE / 3.9; ++i)
    {
        Sprite* sprite = Sprite::create("Images/grossini_dance_01.png");
        sprite->setScale(0.1, 0.1);
        float x = ((float)std::rand()) /RAND_MAX;
        float y = ((float)std::rand()) /RAND_MAX;
        sprite->setPosition(Vec2(x * s.width, y * s.height));
        parent->addChild(sprite);
    }
}

VBOFullTest::~VBOFullTest()
{

}

std::string VBOFullTest::title() const
{
    return "New Renderer";
}

std::string VBOFullTest::subtitle() const
{
    return "VBO full Test, everthing should render normally";
}

CaptureScreenTest::CaptureScreenTest()
{
    Size s = Director::getInstance()->getWinSize();
    Vec2 left(s.width / 4, s.height / 2);
    Vec2 right(s.width / 4 * 3, s.height / 2);

    auto sp1 = Sprite::create("Images/grossini.png");
    sp1->setPosition(left);
    auto move1 = MoveBy::create(1, Vec2(s.width/2, 0));
    auto seq1 = RepeatForever::create(Sequence::create(move1, move1->reverse(), nullptr));
    addChild(sp1);
    sp1->runAction(seq1);
    auto sp2 = Sprite::create("Images/grossinis_sister1.png");
    sp2->setPosition(right);
    auto move2 = MoveBy::create(1, Vec2(-s.width/2, 0));
    auto seq2 = RepeatForever::create(Sequence::create(move2, move2->reverse(), nullptr));
    addChild(sp2);
    sp2->runAction(seq2);

    auto label1 = Label::createWithTTF(TTFConfig("fonts/arial.ttf"), "capture all");
    auto mi1 = MenuItemLabel::create(label1, CC_CALLBACK_1(CaptureScreenTest::onCaptured, this));
    auto menu = Menu::create(mi1, nullptr);
    addChild(menu);
    menu->setPosition(s.width / 2, s.height / 4);

    _filename = "";
}

CaptureScreenTest::~CaptureScreenTest()
{
    Director::getInstance()->getTextureCache()->removeTextureForKey(_filename);
}

std::string CaptureScreenTest::title() const
{
    return "New Renderer";
}

std::string CaptureScreenTest::subtitle() const
{
    return "Capture screen test, press the menu items to capture the screen";
}

void CaptureScreenTest::onCaptured(Ref*)
{
    Director::getInstance()->getTextureCache()->removeTextureForKey(_filename);
    removeChildByTag(childTag);
    _filename = "CaptureScreenTest.png";
    utils::captureScreen(CC_CALLBACK_2(CaptureScreenTest::afterCaptured, this), _filename);
}

void CaptureScreenTest::afterCaptured(bool succeed, const std::string& outputFile)
{
    if (succeed)
    {
        auto sp = Sprite::create(outputFile);
        addChild(sp, 0, childTag);
        Size s = Director::getInstance()->getWinSize();
        sp->setPosition(s.width / 2, s.height / 2);
        sp->setScale(0.25);
        _filename = outputFile;
    }
    else
    {
        log("Capture screen failed.");
    }
}


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

<!DOCTYPE meta PUBLIC
		"Meta Data"
		"http://www.devocative.org/dtd/devolcano-metadata.dtd">

<meta>
	<filterClass>targetClass.entity</filterClass>
	<classes>
		<class fqn="org.devocative.demeter.entity.DPageInfo">
			<cinfo ignore="true"/>
			<id ref="id"/>
			<fields>
				<field name="id">
					<finfo/>
				</field>
				<field name="type">
					<finfo/>
				</field>
				<field name="typeAlt">
					<finfo/>
				</field>
				<field name="module">
					<finfo/>
				</field>
				<field name="baseUri">
					<finfo/>
				</field>
				<field name="enabled">
					<finfo/>
				</field>
				<field name="creationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="modificationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="version">
					<finfo hasForm="false" hasFVO="false"/>
				</field>
			</fields>
		</class>
		<class fqn="org.devocative.demeter.entity.DPageInstance">
			<cinfo hasAdd="false"/>
			<id ref="id"/>
			<fields>
				<field name="id">
					<finfo/>
				</field>
				<field name="title">
					<finfo/>
				</field>
				<field name="uri">
					<finfo/>
				</field>
				<field name="inMenu">
					<finfo/>
				</field>
				<field name="refId">
					<finfo/>
				</field>
				<field name="pageInfo">
					<finfo/>
				</field>
				<field name="roles">
					<finfo/>
				</field>
				<field name="creationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="creatorUser">
					<finfo hasForm="false"/>
				</field>
				<field name="creatorUserId">
					<finfo ignore="true"/>
				</field>
				<field name="modificationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="modifierUser">
					<finfo hasForm="false"/>
				</field>
				<field name="modifierUserId">
					<finfo ignore="true"/>
				</field>
				<field name="version">
					<finfo hasForm="false" hasFVO="false"/>
				</field>
			</fields>
		</class>
		<class fqn="org.devocative.demeter.entity.DTaskInfo">
			<cinfo hasAdd="false"/>
			<id ref="id"/>
			<fields>
				<field name="id">
					<finfo/>
				</field>
				<field name="type">
					<finfo/>
				</field>
				<field name="module">
					<finfo/>
				</field>
				<field name="enabled">
					<finfo/>
				</field>
				<field name="creationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="creatorUser">
					<finfo hasForm="false"/>
				</field>
				<field name="creatorUserId">
					<finfo ignore="true"/>
				</field>
				<field name="modificationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="modifierUser">
					<finfo hasForm="false"/>
				</field>
				<field name="modifierUserId">
					<finfo ignore="true"/>
				</field>
				<field name="version">
					<finfo hasForm="false" hasFVO="false"/>
				</field>
			</fields>
		</class>
		<class fqn="org.devocative.demeter.entity.DTaskLog">
			<cinfo hasAdd="false"/>
			<id ref="id"/>
			<fields>
				<field name="id">
					<finfo/>
				</field>
				<field name="key">
					<finfo/>
				</field>
				<field name="start">
					<finfo hasTimePart="true"/>
				</field>
				<field name="end">
					<finfo hasTimePart="true"/>
				</field>
				<field name="state">
					<finfo/>
				</field>
				<field name="task">
					<finfo/>
				</field>
			</fields>
		</class>
		<class fqn="org.devocative.demeter.entity.DTaskSchedule">
			<cinfo/>
			<id ref="id"/>
			<fields>
				<field name="id">
					<finfo/>
				</field>
				<field name="refId">
					<finfo/>
				</field>
				<field name="enabled">
					<finfo/>
				</field>
				<field name="cronExpression">
					<finfo/>
				</field>
				<field name="task">
					<finfo/>
				</field>
				<field name="creationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="creatorUser">
					<finfo hasForm="false"/>
				</field>
				<field name="creatorUserId">
					<finfo ignore="true"/>
				</field>
				<field name="modificationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="modifierUser">
					<finfo hasForm="false"/>
				</field>
				<field name="modifierUserId">
					<finfo ignore="true"/>
				</field>
				<field name="version">
					<finfo hasForm="false" hasFVO="false"/>
				</field>
			</fields>
		</class>
		<class fqn="org.devocative.demeter.entity.FileStore">
			<cinfo/>
			<id ref="id"/>
			<fields>
				<field name="id">
					<finfo/>
				</field>
				<field name="name">
					<finfo/>
				</field>
				<field name="status">
					<finfo/>
				</field>
				<field name="storage">
					<finfo hasForm="false"/>
				</field>
				<field name="mimeType">
					<finfo/>
				</field>
				<field name="fileId">
					<finfo hasForm="false"/>
				</field>
				<field name="expiration">
					<finfo hasTimePart="true"/>
				</field>
				<field name="tag">
					<finfo/>
				</field>
				<field name="creationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="creatorUser">
					<finfo hasForm="false"/>
				</field>
				<field name="creatorUserId">
					<finfo ignore="true"/>
				</field>
				<field name="modificationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="modifierUser">
					<finfo hasForm="false"/>
				</field>
				<field name="modifierUserId">
					<finfo ignore="true"/>
				</field>
				<field name="version">
					<finfo hasForm="false" hasFVO="false"/>
				</field>
			</fields>
		</class>
		<class fqn="org.devocative.demeter.entity.Person">
			<cinfo/>
			<id ref="id"/>
			<fields>
				<field name="serialVersionUID">
					<finfo ignore="true"/>
				</field>
				<field name="id">
					<finfo/>
				</field>
				<field name="firstName">
					<finfo/>
				</field>
				<field name="lastName">
					<finfo/>
				</field>
				<field name="birthRegDate">
					<finfo hasTimePart="false"/>
				</field>
				<field name="email">
					<finfo/>
				</field>
				<field name="mobile">
					<finfo/>
				</field>
				<field name="systemNumber">
					<finfo/>
				</field>
				<field name="hasUser">
					<finfo hasForm="false"/>
				</field>
				<field name="user">
					<finfo hasForm="false" hasFVO="false"/>
				</field>
				<field name="rowMode">
					<finfo hasForm="false"/>
				</field>
				<field name="creationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="creatorUser">
					<finfo hasForm="false"/>
				</field>
				<field name="creatorUserId">
					<finfo ignore="true"/>
				</field>
				<field name="modificationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="modifierUser">
					<finfo hasForm="false"/>
				</field>
				<field name="modifierUserId">
					<finfo ignore="true"/>
				</field>
				<field name="version">
					<finfo hasForm="false" hasFVO="false"/>
				</field>
			</fields>
		</class>
		<class fqn="org.devocative.demeter.entity.Privilege">
			<cinfo/>
			<id ref="id"/>
			<fields>
				<field name="id">
					<finfo/>
				</field>
				<field name="name">
					<finfo/>
				</field>
				<field name="creationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
			</fields>
		</class>
		<class fqn="org.devocative.demeter.entity.Role">
			<cinfo/>
			<id ref="id"/>
			<fields>
				<field name="id">
					<finfo/>
				</field>
				<field name="name">
					<finfo/>
				</field>
				<field name="roleMode">
					<finfo/>
				</field>
				<field name="permissions">
					<finfo/>
				</field>
				<field name="denials">
					<finfo/>
				</field>
				<field name="rowMode">
					<finfo hasForm="false"/>
				</field>
				<field name="creationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="creatorUser">
					<finfo hasForm="false"/>
				</field>
				<field name="creatorUserId">
					<finfo ignore="true"/>
				</field>
				<field name="modificationDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="modifierUser">
					<finfo hasForm="false"/>
				</field>
				<field name="modifierUserId">
					<finfo ignore="true"/>
				</field>
				<field name="version">
					<finfo hasForm="false" hasFVO="false"/>
				</field>
			</fields>
		</class>
		<class fqn="org.devocative.demeter.entity.User">
			<cinfo/>
			<id ref="id"/>
			<fields>
				<field name="serialVersionUID">
					<finfo ignore="true"/>
				</field>
				<field name="id">
					<finfo/>
				</field>
				<field name="username">
					<finfo/>
				</field>
				<field name="password">
					<finfo hasList="false" hasFVO="false"/>
				</field>
				<field name="authMechanism">
					<finfo/>
				</field>
				<field name="status">
					<finfo/>
				</field>
				<field name="locale">
					<finfo/>
				</field>
				<field name="calendarType">
					<finfo/>
				</field>
				<field name="layoutDirectionType">
					<finfo/>
				</field>
				<field name="datePatternType">
					<finfo/>
				</field>
				<field name="dateTimePatternType">
					<finfo/>
				</field>
				<field name="lastLoginDate">
					<finfo hasForm="false" hasTimePart="true"/>
				</field>
				<field name="admin">
					<finfo/>
				</field>
				<field name="sessionTimeout">
					<finfo/>
				</field>
				<field name="person">
					<finfo ignore="true"/>
				</field>
				<field name="roles">
					<finfo/>
				</field>
				<field name="permissions">
					<finfo/>
				</field>
				<field name="denials">
					<finfo/>
				</field>
			</fields>
		</class>
		<class fqn="org.devocative.demeter.entity.ZSqlApply">
			<cinfo ignore="true"/>
			<id ref=""/>
			<fields>
				<field name="id">
					<finfo/>
				</field>
				<field name="file">
					<finfo/>
				</field>
				<field name="apply">
					<finfo hasTimePart="true"/>
				</field>
			</fields>
		</class>
	</classes>
</meta>


text:
angular.module('ualib', ['ualib'])

.controller('ModalDemoCtrl', function ($scope, $modal) {

  $scope.openModal = function () {
    $modal.open({
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl'
    });
  };
});

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

angular.module('ualib').controller('ModalInstanceCtrl', function ($scope, $modalInstance) {

  $scope.ok = function () {
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});


text:
#ifndef PLORTH_POSITION_HPP_GUARD
#define PLORTH_POSITION_HPP_GUARD

#include <plorth/unicode.hpp>

namespace plorth
{
  /**
   * Represents position in source code.
   */
  struct position
  {
    std::u32string filename;
    int line;
    int column;
  };

  std::ostream& operator<<(std::ostream&, const position&);
}

#endif /* !PLORTH_POSITION_HPP_GUARD */


text:
@org.osgi.annotation.versioning.Version("1.0.0")
package io.primeval.aspecio.examples.async;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.

Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.

Oracle and Java are registered trademarks of Oracle and/or its affiliates.
Other names may be trademarks of their respective owners.

The contents of this file are subject to the terms of either the GNU
General Public License Version 2 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with the
License. You can obtain a copy of the License at
http://www.netbeans.org/cddl-gplv2.html
or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
specific language governing permissions and limitations under the
License.  When distributing the software, include this License Header
Notice in each file and include the License file at
nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
particular file as subject to the "Classpath" exception as provided
by Oracle in the GPL Version 2 section of the License file that
accompanied this code. If applicable, add the following below the
License Header, with the fields enclosed by brackets [] replaced by
your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"

Contributor(s):

The Original Software is NetBeans. The Initial Developer of the Original
Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
Microsystems, Inc. All Rights Reserved.

If you wish your version of this file to be governed by only the CDDL
or only the GPL Version 2, indicate your decision by adding
"[Contributor] elects to include this software in this distribution
under the [CDDL or GPL Version 2] license." If you do not indicate a
single choice of license, a recipient has the option to distribute
your version of this file under either the CDDL, the GPL Version 2 or
to extend the choice of license to its licensees as provided above.
However, if you add GPL Version 2 code and therefore, elected the GPL
Version 2 license, then the option applies only if the new code is
made subject to such option by the copyright holder.
-->

<!DOCTYPE transformations PUBLIC "-//NetBeans//DTD Module Automatic Dependencies 1.0//EN" "http://www.netbeans.org/dtds/module-auto-deps-1_0.dtd">

<transformations version="1.0">

    <transformationgroup>
        <description>Xerces is now available only as an autoload module, not in classpath: http://libs.netbeans.org/#xerces</description>
        <transformation>
            <trigger-dependency type="cancel">
                <package-dependency name="org.apache.xerces"/>
            </trigger-dependency>
            <implies>
                <result>
                    <module-dependency codenamebase="org.netbeans.libs.xerces" major="1" spec="1.2"/>
                </result>
            </implies>
        </transformation>
        <transformation>
            <trigger-dependency type="cancel">
                <package-dependency name="org.apache.xerces.parsers"/>
            </trigger-dependency>
            <implies>
                <result>
                    <module-dependency codenamebase="org.netbeans.libs.xerces" major="1" spec="1.2"/>
                </result>
            </implies>
        </transformation>
        <transformation>
            <trigger-dependency type="cancel">
                <package-dependency name="org.apache.xerces.impl"/>
            </trigger-dependency>
            <implies>
                <result>
                    <module-dependency codenamebase="org.netbeans.libs.xerces" major="1" spec="1.2"/>
                </result>
            </implies>
        </transformation>
        <transformation>
            <trigger-dependency type="cancel">
                <package-dependency name="org.apache.xerces.dom"/>
            </trigger-dependency>
            <implies>
                <result>
                    <module-dependency codenamebase="org.netbeans.libs.xerces" major="1" spec="1.2"/>
                </result>
            </implies>
        </transformation>
        <transformation>
            <trigger-dependency type="cancel">
                <package-dependency name="org.apache.xerces.jaxp"/>
            </trigger-dependency>
            <implies>
                <result>
                    <module-dependency codenamebase="org.netbeans.libs.xerces" major="1" spec="1.2"/>
                </result>
            </implies>
        </transformation>
        <transformation>
            <trigger-dependency type="cancel">
                <package-dependency name="org.apache.xml.serialize"/>
            </trigger-dependency>
            <implies>
                <result>
                    <module-dependency codenamebase="org.netbeans.libs.xerces" major="1" spec="1.2"/>
                </result>
            </implies>
        </transformation>
        <transformation>
            <trigger-dependency type="cancel">
                <package-dependency name="org.w3c.dom.ranges"/>
            </trigger-dependency>
            <implies>
                <result>
                    <module-dependency codenamebase="org.netbeans.libs.xerces" major="1" spec="1.2"/>
                </result>
            </implies>
        </transformation>
    </transformationgroup>

    <transformationgroup>
        <description>Regexp is now available only as an autoload module compiled manually from libs/regexp in the release40 branch, not on classpath: http://libs.netbeans.org/#regexp</description>
        <transformation>
            <trigger-dependency type="cancel">
                <package-dependency name="org.apache.regexp"/>
            </trigger-dependency>
            <implies>
                <result>
                    <module-dependency codenamebase="org.netbeans.libs.regexp" spec="1.2"/>
                </result>
            </implies>
        </transformation>
    </transformationgroup>

</transformations>


text:
SceneGameMainResult::SceneGameMainResult(std::function<void(SceneInGameMainKind)> gameMainSceneChanger, std::function<void(SceneKind)> changer, int stage, ScoreResult result) : SceneInGameMainBase(gameMainSceneChanger) {
	this->count = 0;

	this->writeHighScore(stage, result);
	this->mouse_pointer = std::make_shared<MousePointer>();
	this->mes = std::make_shared<Message>(Point(150, 50), MessageType::RESULT);
	this->mes->setInvalid();

	this->box.push_back(std::make_shared<MapChip>(Point(32, 88), Size(32, 32), 18));
	this->box.push_back(std::make_shared<MapChip>(Point(928, 88), Size(32, 32), 19));
	this->box.push_back(std::make_shared<MapChip>(Point(32, 536), Size(32, 32), 17));
	this->box.push_back(std::make_shared<MapChip>(Point(928, 536), Size(32, 32), 16));
	for (int i = 1; i < 14; ++i) this->box.push_back(std::make_shared<MapChip>(Point(32 + 64 * i, 88), Size(32, 32), 2));
	for (int i = 1; i < 14; ++i) this->box.push_back(std::make_shared<MapChip>(Point(32 + 64 * i, 536), Size(32, 32), 0));
	for (int i = 1; i < 7; ++i) this->box.push_back(std::make_shared<MapChip>(Point(32, 88 + 64 * i), Size(32, 32), 1));
	for (int i = 1; i < 7; ++i) this->box.push_back(std::make_shared<MapChip>(Point(928, 88 + 64 * i), Size(32, 32), 3));

	this->ranks.push_back(std::make_shared<Rank>(Point(400, 180), result.goal_time));
	this->ranks.push_back(std::make_shared<Rank>(Point(750, 180), result.goal_speed));
	this->ranks.push_back(std::make_shared<Rank>(Point(400, 300), result.max_speed));
	this->ranks.push_back(std::make_shared<Rank>(Point(750, 300), result.swing_tech));
	this->ranks.push_back(std::make_shared<Rank>(Point(220, 420), result.total));
	for (auto it = this->ranks.begin(); it != this->ranks.end(); ++it) (*it)->setInvalid();

	this->button.push_back(std::make_shared<Button>(Point(500, 420), Size(200, 70), "ƒXƒe[ƒWƒZƒŒƒNƒg", 22, [gameMainSceneChanger]() {gameMainSceneChanger(SceneInGameMainKind::StageSelect); }));
	this->button.push_back(std::make_shared<Button>(Point(750, 420), Size(200, 70), "ƒ^ƒCƒgƒ‹", 22, [changer]() {changer(SceneKind::Opening); }));
	for (auto it = this->button.begin(); it != this->button.end(); ++it) (*it)->setInvalid();
	this->button.push_back(std::make_shared<ButtonMove>(Point(250, 190), Size(200, 70), "ƒ^ƒCƒ€", 22, []() {}));
	this->button.push_back(std::make_shared<ButtonMove>(Point(600, 190), Size(200, 70), "ƒXƒs[ƒh", 22, []() {}));
	this->button.push_back(std::make_shared<ButtonMove>(Point(250, 310), Size(200, 70), "ƒ}ƒbƒNƒX", 22, []() {}));
	this->button.push_back(std::make_shared<ButtonMove>(Point(600, 310), Size(200, 70), "ƒXƒCƒ"ƒO", 22, []() {}));

	Screen::initTargetPositionDeltaCenter(Point());
	Screen::setTargetWorldPosition(Point(Screen::getWindowSize().width / 2, Screen::getWindowSize().height * 3 / 2), 1);
	Screen::setZoomOut(1);
}

void SceneGameMainResult::initialize() {

}

void SceneGameMainResult::update() {
	this->count++;
	this->mouse_pointer->update();
	this->mes->update();
	for (auto it = this->box.begin(); it != this->box.end(); ++it) (*it)->update();
	for (auto it = this->ranks.begin(); it != this->ranks.end(); ++it) (*it)->update();
	for (auto it = this->button.begin(); it != this->button.end(); ++it) (*it)->update();

	if (this->count < 50) {
		Screen::setTargetWorldPosition(Point(Screen::getWindowSize().width / 2, Screen::getWindowSize().height * 3 / 2 - Screen::getWindowSize().height*this->count / 50), 1);
	}
	if (this->count == 50) this->mes->startShowing();
	for (int i = 0; i < 4; ++i) { if (this->count == 50 + 20 * i) this->ranks[i]->startShowing(3.0, 0.5, 30); }
	if (this->count == 150) this->ranks[4]->startShowing(4.0, 1.0, 60);

	if(this->count==240) { for (auto it = this->button.begin(); it != this->button.end(); ++it) (*it)->setValid(); }
}

void SceneGameMainResult::finalize() {

}

void SceneGameMainResult::writeHighScore(int stage, ScoreResult result) {
	std::ifstream ifs("asset\\highscore.dat");
	if (!ifs) return;

	std::string str;
	std::vector<int> highscore_list;

	for (int i = 0; i < 20; ++i) {
		std::getline(ifs, str);
		std::string score;
		std::istringstream stream(str);

		getline(stream, score, ',');
		highscore_list.push_back(std::stoi(score));
	}

	if (highscore_list[stage] > (int)result.total) highscore_list[stage] = (int)result.total;
	else if(highscore_list[stage]==-1) highscore_list[stage] = (int)result.total;

	std::ofstream ofs("asset\\highscore.dat");
	for (int i = 0; i < 20; ++i) {
		ofs << highscore_list[i] << std::endl;
	}
}


text:
package com.consol.citrus.mail.client;

import java.util.Properties;

import com.consol.citrus.endpoint.AbstractEndpointConfiguration;
import com.consol.citrus.mail.message.MailMessageConverter;
import com.consol.citrus.mail.model.MailMarshaller;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 * @author Christoph Deppisch
 * @since 1.4
 */
public class MailEndpointConfiguration extends AbstractEndpointConfiguration {

    /** SMTP host */
    private String host;

    /** SMTP port*/
    private int port = JavaMailSenderImpl.DEFAULT_PORT;

    /** User name */
    private String username;

    /** Password */
    private String password;

    /** Protocol */
    private String protocol = JavaMailSenderImpl.DEFAULT_PROTOCOL;

    /** Java mail properties */
    private Properties javaMailProperties;

    /** Mail sender implementation */
    private JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

    /** Mail message marshaller converts from XML to mail message object */
    private MailMarshaller marshaller = new MailMarshaller();

    /** Mail message converter */
    private MailMessageConverter messageConverter = new MailMessageConverter();

    /**
     * Gets the mail protocol.
     * @return the mail protocol.
     */
    public String getProtocol() {
        return protocol;
    }

    /**
     * Set the mail protocol. Default is "smtp".
     * @param protocol
     */
    public void setProtocol(String protocol) {
        this.protocol = protocol;
        javaMailSender.setProtocol(protocol);
    }

    /**
     * Gets the mail host.
     * @return the mail host.
     */
    public String getHost() {
        return host;
    }

    /**
     * Set the mail server host, typically an SMTP host.
     * @param host
     */
    public void setHost(String host) {
        this.host = host;
        javaMailSender.setHost(host);
    }

    /**
     * Gets the mail port.
     * @return the mail port.
     */
    public int getPort() {
        return port;
    }

    /**
     * Set the mail server port.
     * Default is the Java mail port for SMTP (25).
     * @param port
     */
    public void setPort(int port) {
        this.port = port;
        javaMailSender.setPort(port);
    }

    /**
     * Gets the mail username.
     * @return the mail username.
     */
    public String getUsername() {
        return username;
    }

    /**
     * Set the username for accessing the mail host. Underlying mail seesion
     * has to be configured with the property "mail.smtp.auth" set to
     * true.
     * @param username
     */
    public void setUsername(String username) {
        this.username = username;
        javaMailSender.setUsername(username);
    }

    /**
     * Gets the mail password.
     * @return the mail ppassword.
     */
    public String getPassword() {
        return password;
    }

    /**
     * Set the password for accessing the mail host. Underlying mail seesion
     * has to be configured with the property "mail.smtp.auth" set to
     * true.
     * @param password
     */
    public void setPassword(String password) {
        this.password = password;
        javaMailSender.setPassword(password);
    }

    /**
     * Gets the mail properties.
     * @return the mail properties.
     */
    public Properties getJavaMailProperties() {
        return javaMailProperties;
    }

    /**
     * Set JavaMail properties for the mail session such as "mail.smtp.auth"
     * when using username and password. New session is created when properties are set.
     * @param javaMailProperties
     */
    public void setJavaMailProperties(Properties javaMailProperties) {
        this.javaMailProperties = javaMailProperties;
        javaMailSender.setJavaMailProperties(javaMailProperties);
    }

    /**
     * Gets the mail message marshaller implementation.
     * @return
     */
    public MailMarshaller getMarshaller() {
        return marshaller;
    }

    /**
     * Sets the mail message marshaller implementation.
     * @param marshaller
     */
    public void setMarshaller(MailMarshaller marshaller) {
        this.marshaller = marshaller;
    }

    /**
     * Gets the Java mail sender implementation.
     * @return
     */
    public JavaMailSenderImpl getJavaMailSender() {
        return javaMailSender;
    }

    /**
     * Sets the Java mail sender implementation.
     * @param javaMailSender
     */
    public void setJavaMailSender(JavaMailSenderImpl javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    /**
     * Gets the mail message converter.
     * @return
     */
    public MailMessageConverter getMessageConverter() {
        return messageConverter;
    }

    /**
     * Sets the mail message converter.
     * @param messageConverter
     */
    public void setMessageConverter(MailMessageConverter messageConverter) {
        this.messageConverter = messageConverter;
    }
}


text:
import * as t from 'babel-types';

let find = require('lodash/collection/find');

let isResolvable = node => t.isObjectExpression(node) || t.isLiteral(node)

function resolveToValue(node, scope, resolve = isResolvable){

  if (resolve(node, scope)) {
    //console.log('resolved', node, scope)
    return node
  }
  else if( t.isAssignmentExpression(node)){
    return resolveToValue(node.right, scope, resolve)
  }
  else if ( t.isVariableDeclarator(node) ) {
    return resolveToValue(node.init, scope, resolve)
  }
  else if( t.isMemberExpression(node)) {
    while (node && t.isMemberExpression(node)) {
      node = node.object;
    }

    return resolveToValue(node, scope, resolve)
  }
  else if ( t.isIdentifier(node) ){
    var name = node.name
      , binding = scope.getBinding(name)

    if (!binding) {
      return node
    }

    node = binding.path.container[binding.path.key]

    if (t.isVariableDeclaration(node)) {
      node = find(node.declarations, d => d.id.name === name)
    }
    // destructuring
    if (t.isObjectPattern(node.id) ) {
      var prop = find(node.id.properties, p => p.value && p.value.name === name)

      node = t.memberExpression(node.init, t.identifier(prop.key.name))
    }

    //console.log('ident')
    return resolveToValue(node, binding.scope, resolve)
  }
  else {
    //console.log('not resolved', node.type, node._paths[0].parentPath)
  }
}

resolveToValue.isResolvable = isResolvable

module.exports = resolveToValue

//var isReactComponentClass = require('./isReactComponentClass')


text:
package org.otw.open.util

import com.badlogic.gdx.Gdx
import com.badlogic.gdx.audio.Music
import org.otw.open.controllers.GameState

/**
  * Created by deftimov on 23.02.2016.
  * Handles audio files
  */
case class AudioManager(fileName: String) {
  private val audioTrack: Music = Gdx.audio.newMusic(Gdx.files.internal("theme/" + GameState.getThemeName + "/" + fileName))

  def getAudio = audioTrack
}


text:
/* eslint-env mocha */
const expect = require('chai').expect;
const sinon = require('sinon');
const { Observable } = require('rxjs/Observable');
const { isFSA } = require('flux-standard-action');
require('../source/rxjs.js');
const { defaultDispatch } = require('../source/defaultDispatch.js');

describe('defaultDispatch', () => {
  it('should throw when passed non-Flux Standard Action', () => {
    expect(
      () => defaultDispatch({ procedures: {}, models: {}})('test')
    ).to.throw(/Dispatched actions must comply with Flux Standard Action syntax/);
  });
  it('should throw when passed procedure is not implemented', () => {
    expect(
      () => defaultDispatch({ procedures: {}, models: {}})({ type: 'test' })
    ).to.throw(/Procedure \"test\" not implemented/);
  });
  it('should invoke procedure', done => {
    const procedureSpy = sinon.spy();
    const dispatch = defaultDispatch({
      procedures: {
        test: procedureSpy
      },
      models: {}
    });
    dispatch({ type: 'test' }).subscribe(() => {
      expect(procedureSpy.calledOnce).to.be.true;
      done();
    });
  });

  it('should invoke nested procedures', done => {
    const procedureSpy = sinon.spy();
    const dispatch = defaultDispatch({
      procedures: {
        test: procedureSpy,
        testNested: (action, dispatch) => dispatch({ type: 'test' })
      },
      models: {}
    });
    dispatch({ type: 'testNested' }).subscribe(() => {
      expect(procedureSpy.calledOnce).to.be.true;
      done();
    });
  });

  it('should wrap procedure result in Flux standard action', done => {
    const dispatch = defaultDispatch({
      procedures: {
        test: () => 'G-man'
      },
      models: {}
    });
    dispatch({ type: 'test' }).subscribe(responseAction => {
      expect(isFSA(responseAction)).to.be.true;
      expect(responseAction.payload).to.equal('G-man');
      expect(responseAction.meta.protocol).to.equal('response');
      done();
    });
  });

  it('should respond to errors with an error action', done => {
    const dispatch = defaultDispatch({
      procedures: {
        test: () => { throw new Error('Headcrab'); }
      },
      models: {}
    });
    dispatch({ type: 'test' }).subscribe(responseAction => {
      expect(isFSA(responseAction)).to.be.true;
      expect(responseAction.error).to.be.true;
      expect(responseAction.payload).to.eql({ message: 'Headcrab' });
      expect(responseAction.meta.protocol).to.equal('response');
      done();
    });
  });

  it('should wrap procedure result in Observable', () => {
    const dispatch = defaultDispatch({
      procedures: {
        test: () => 'G-man',
        testPromise: () => Promise.resolve('G-man'),
        testObservable: () => Observable.of('G-man')
      },
      models: {}
    });
    expect(dispatch({ type: 'test' })).to.be.an.instanceof(Observable);
    expect(dispatch({ type: 'testPromise' })).to.be.an.instanceof(Observable);
    expect(dispatch({ type: 'testObservable' })).to.be.an.instanceof(Observable);
  });

  xit('should maintain trace UUID through nested procedure calls', done => { done(); });
});


text:
// Copyright (C) Ikkei Shimomura (tea) <Ikkei.Shimura@gmail.com>

var EventEmitter = require('events').EventEmitter;
var util = require('util');

/**
 * Base class for EventListener in Server/Client
 * Use example, ChatEventListener, AudioEventListener, VideoEventListener
 */

function EventListener(ev) {
  'use strict';

  if (!(this instanceof EventListener)) {
    return new EventListener(ev);
  }
  EventEmitter.call(this);

  this._initialize(ev);
}
util.inherits(EventListener, EventEmitter);

module.exports = EventListener;


text:
package org.openhome.net.controlpoint.proxies;

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

import org.openhome.net.controlpoint.*;
import org.openhome.net.controlpoint.proxies.CpProxyAvOpenhomeOrgDebug1.*;
import org.openhome.net.core.*;

interface ICpProxyAvOpenhomeOrgDebug1 extends ICpProxy
{
    public String syncGetLog();
    public void beginGetLog(ICpProxyListener aCallback);
    public String endGetLog(long aAsyncHandle);
    public void syncSendLog(String aData);
    public void beginSendLog(String aData, ICpProxyListener aCallback);
    public void endSendLog(long aAsyncHandle);
}

class SyncGetLogAvOpenhomeOrgDebug1 extends SyncProxyAction
{
    private CpProxyAvOpenhomeOrgDebug1 iService;
    private String iLog;

    public SyncGetLogAvOpenhomeOrgDebug1(CpProxyAvOpenhomeOrgDebug1 aProxy)
    {
        iService = aProxy;
    }
    public String getLog()
    {
        return iLog;
    }
    protected void completeRequest(long aAsyncHandle)
    {
        String result = iService.endGetLog(aAsyncHandle);

        iLog = result;
    }
}

class SyncSendLogAvOpenhomeOrgDebug1 extends SyncProxyAction
{
    private CpProxyAvOpenhomeOrgDebug1 iService;

    public SyncSendLogAvOpenhomeOrgDebug1(CpProxyAvOpenhomeOrgDebug1 aProxy)
    {
        iService = aProxy;
    }
    protected void completeRequest(long aAsyncHandle)
    {
        iService.endSendLog(aAsyncHandle);

    }
}

/**
 * Proxy for the av.openhome.org:Debug:1 UPnP service
 */
public class CpProxyAvOpenhomeOrgDebug1 extends CpProxy implements ICpProxyAvOpenhomeOrgDebug1
{

    private Action iActionGetLog;
    private Action iActionSendLog;

    /**
     * Constructor.
     * Use {@link #subscribe}/{@link #unsubscribe} to enable/disable querying of state variable and reporting of their changes.
     *
     * @param aDevice   the device to use.
     */

    public CpProxyAvOpenhomeOrgDebug1(CpDevice aDevice)
    {
        super("av-openhome-org", "Debug", 1, aDevice);
        Parameter param;
        List<String> allowedValues = new LinkedList<String>();

        iActionGetLog = new Action("GetLog");
        param = new ParameterString("Log", allowedValues);
        iActionGetLog.addOutputParameter(param);

        iActionSendLog = new Action("SendLog");
        param = new ParameterString("Data", allowedValues);
        iActionSendLog.addInputParameter(param);
    }
    /**
     * Invoke the action synchronously.
     * Blocks until the action has been processed on the device and sets any
     * output arguments.
     *
     * @return the result of the invoked action.
     */
    public String syncGetLog()
    {
        SyncGetLogAvOpenhomeOrgDebug1 sync = new SyncGetLogAvOpenhomeOrgDebug1(this);
        beginGetLog(sync.getListener());
        sync.waitToComplete();
        sync.reportError();

        return sync.getLog();
    }

    /**
     * Invoke the action asynchronously.
     * Returns immediately and will run the client-specified callback when the
     * action later completes.  Any output arguments can then be retrieved by
     * calling {@link #endGetLog}.
     *
     * @param aCallback listener to call back when action completes.
     *                  This is guaranteed to be run but may indicate an error.
     */
    public void beginGetLog(ICpProxyListener aCallback)
    {
        Invocation invocation = iService.getInvocation(iActionGetLog, aCallback);
        int outIndex = 0;
        invocation.addOutput(new ArgumentString((ParameterString)iActionGetLog.getOutputParameter(outIndex++)));
        iService.invokeAction(invocation);
    }

    /**
     * Retrieve the output arguments from an asynchronously invoked action.
     * This may only be called from the callback set in the
     * {@link #beginGetLog} method.
     *
     * @param aAsyncHandle  argument passed to the delegate set in the
     *          {@link #beginGetLog} method.
     * @return the result of the previously invoked action.
     */
    public String endGetLog(long aAsyncHandle)
    {
        ProxyError errObj = Invocation.error(aAsyncHandle);
        if (errObj != null)
        {
            throw errObj;
        }
        int index = 0;
        String log = Invocation.getOutputString(aAsyncHandle, index++);
        return log;
    }

    /**
     * Invoke the action synchronously.
     * Blocks until the action has been processed on the device and sets any
     * output arguments.
     */
    public void syncSendLog(String aData)
    {
        SyncSendLogAvOpenhomeOrgDebug1 sync = new SyncSendLogAvOpenhomeOrgDebug1(this);
        beginSendLog(aData, sync.getListener());
        sync.waitToComplete();
        sync.reportError();
    }

    /**
     * Invoke the action asynchronously.
     * Returns immediately and will run the client-specified callback when the
     * action later completes.  Any output arguments can then be retrieved by
     * calling {@link #endSendLog}.
     *
     * @param aData
     * @param aCallback listener to call back when action completes.
     *                  This is guaranteed to be run but may indicate an error.
     */
    public void beginSendLog(String aData, ICpProxyListener aCallback)
    {
        Invocation invocation = iService.getInvocation(iActionSendLog, aCallback);
        int inIndex = 0;
        invocation.addInput(new ArgumentString((ParameterString)iActionSendLog.getInputParameter(inIndex++), aData));
        iService.invokeAction(invocation);
    }

    /**
     * Retrieve the output arguments from an asynchronously invoked action.
     * This may only be called from the callback set in the
     * {@link #beginSendLog} method.
     *
     * @param aAsyncHandle  argument passed to the delegate set in the
     *          {@link #beginSendLog} method.
     */
    public void endSendLog(long aAsyncHandle)
    {
        ProxyError errObj = Invocation.error(aAsyncHandle);
        if (errObj != null)
        {
            throw errObj;
        }
    }

    /**
     * Dispose of this control point proxy.
     * Must be called for each class instance.
     * Must be called before <tt>Library.close()</tt>.
     */
    public void dispose()
    {
        synchronized (this)
        {
            if (iHandle == 0)
            {
                return;
            }
            disposeProxy();
            iHandle = 0;
            iActionGetLog.destroy();
            iActionSendLog.destroy();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Otter.Editor.Forms
{
    public partial class WelcomeForm : Form
    {
        public delegate void LoadRecentProjectDelegate(object sender, string path);
        public delegate void WelcomeActionDelegate(object sender);

        public event LoadRecentProjectDelegate OnLoadRecentProject;
        public event WelcomeActionDelegate OnLoadProject;
        public event WelcomeActionDelegate OnNewProject;

        /// <summary>
        /// Constructor
        /// </summary>
        public WelcomeForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Called when the form has loaded - sets up the recent projects list.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WelcomeForm_Load(object sender, EventArgs e)
        {
            RefreshRecentProjects();
        }

        /// <summary>
        /// Refreshes and repopulates recent projects list
        /// </summary>
        public void RefreshRecentProjects()
        {
            mRecentProjectsPanel.Controls.Clear();

            try
            {
                int count = 0;
                foreach (string str in Otter.Editor.Properties.Settings.Default.RecentProjects)
                {
                    string filename = System.IO.Path.GetFileName(str);

                    Button button = new Button();

                    button.FlatAppearance.BorderSize = 0;
                    button.FlatAppearance.MouseDownBackColor = System.Drawing.Color.LightSteelBlue;
                    button.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
                    button.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
                    button.ImageIndex = 2;
                    button.ImageList = this.imageList1;
                    button.Location = new System.Drawing.Point(0, count * 36);
                    button.Name = "button_" + filename;
                    button.Size = new System.Drawing.Size(159, 36);
                    button.TabIndex = 20;
                    button.Text = filename;
                    button.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                    button.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
                    button.UseVisualStyleBackColor = true;
                    button.Tag = str;

                    button.Click += new EventHandler(RecentButton_Click);

                    mRecentProjectsPanel.Controls.Add(button);

                    if (++count >= 3)
                        break;
                }
            }
            catch(Exception)
            {
                mRecentProjectsPanel.Controls.Clear();
            }
        }

        /// <summary>
        /// Called when the user clicked on any of the "recent" items.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void RecentButton_Click(object sender, EventArgs e)
        {
            if (OnLoadRecentProject != null)
                OnLoadRecentProject(this, ((Button)sender).Tag as string);
        }

        /// <summary>
        /// "Show Welcome" checkbox changed - save the user settings
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mShowWelcomeCheckbox_CheckedChanged(object sender, EventArgs e)
        {
            Otter.Editor.Properties.Settings.Default.ShowWelcome = mShowWelcomeCheckbox.Checked;
            Otter.Editor.Properties.Settings.Default.Save();
        }

        /// <summary>
        /// User clicked on the "New Project..." button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mNewProjectButton_Click(object sender, EventArgs e)
        {
            if (OnNewProject != null)
                OnNewProject(this);
        }

        /// <summary>
        /// User clicked on the "Load Project..." button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mLoadProjectButton_Click(object sender, EventArgs e)
        {
            if (OnLoadProject != null)
                OnLoadProject(this);
        }

    }
}


text:
var config = require('../lib/common/config');
var util = require('util');
var program = require("commander");

function configUser(callback){
  program.prompt('Input you taobao login user name: ', function(name){
    name = util.format("_nk_=%s;", escapeIt(name));
    var headers = config.getJSON('./config.json', __dirname);
    headers['headers']['Cookie'] = name;
    config.joyrc('upload', headers);
    console.log('config success');
    console.log(JSON.stringify(headers, null, 2));
    process.stdin.destroy();
    callback && callback.call && callback();
  });
}

function escapeIt(str){
  var len = str.length;
  var ret = '';
  for (var i = 0; i < len; i++) {
    var bit = str.charCodeAt(i);
    if (bit < 0 || bit > 255){
      ret += '\\u' + bit.toString(16);
    } else {
      ret += str[i];
    }
  }
  return ret;
}

exports.configUser = configUser;


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.Taiko.Replays;
using osu.Framework.Input;
using osu.Game.Configuration;
using osu.Game.Input.Handlers;
using osu.Game.Replays;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Timing;
using osu.Game.Rulesets.UI.Scrolling;
using osu.Game.Scoring;
using osu.Game.Skinning;
using osuTK;

namespace osu.Game.Rulesets.Taiko.UI
{
    public class DrawableTaikoRuleset : DrawableScrollingRuleset<TaikoHitObject>
    {
        public new BindableDouble TimeRange => base.TimeRange;

        public readonly BindableBool LockPlayfieldAspect = new BindableBool(true);

        protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Overlapping;

        protected override bool UserScrollSpeedAdjustment => false;

        private SkinnableDrawable scroller;

        public DrawableTaikoRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
            : base(ruleset, beatmap, mods)
        {
            Direction.Value = ScrollingDirection.Left;
            TimeRange.Value = 7000;
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            new BarLineGenerator<BarLine>(Beatmap).BarLines.ForEach(bar => Playfield.Add(bar));

            FrameStableComponents.Add(scroller = new SkinnableDrawable(new TaikoSkinComponent(TaikoSkinComponents.Scroller), _ => Empty())
            {
                RelativeSizeAxes = Axes.X,
                Depth = float.MaxValue
            });
        }

        protected override void UpdateAfterChildren()
        {
            base.UpdateAfterChildren();

            var playfieldScreen = Playfield.ScreenSpaceDrawQuad;
            scroller.Height = ToLocalSpace(playfieldScreen.TopLeft + new Vector2(0, playfieldScreen.Height / 20)).Y;
        }

        public MultiplierControlPoint ControlPointAt(double time)
        {
            int result = ControlPoints.BinarySearch(new MultiplierControlPoint(time));
            if (result < 0)
                result = Math.Clamp(~result - 1, 0, ControlPoints.Count);
            return ControlPoints[result];
        }

        public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new TaikoPlayfieldAdjustmentContainer
        {
            LockPlayfieldAspect = { BindTarget = LockPlayfieldAspect }
        };

        protected override PassThroughInputManager CreateInputManager() => new TaikoInputManager(Ruleset.RulesetInfo);

        protected override Playfield CreatePlayfield() => new TaikoPlayfield();

        public override DrawableHitObject<TaikoHitObject> CreateDrawableRepresentation(TaikoHitObject h) => null;

        protected override ReplayInputHandler CreateReplayInputHandler(Replay replay) => new TaikoFramedReplayInputHandler(replay);

        protected override ReplayRecorder CreateReplayRecorder(Score score) => new TaikoReplayRecorder(score);
    }
}


text:
package org.ausdigital.apecconnect.common.tests

import akka.actor.ActorSystem
import au.com.agiledigital.healthchecker.{ HealthCheckManager, HealthCheckerModule }
import au.com.agiledigital.kamon.play_extensions.{ KamonPlayExtensionsModule, Metrics }
import kamon.play.di.KamonModule
import play.api.Mode
import play.api.inject._
import play.api.inject.guice.GuiceApplicationBuilder

/**
  * Contains reusable test fixtures.
  */
object BaseApplications {

  /**
    * A Guice application builder that disables modules that should never be enabled.
    */
  def appBuilder: GuiceApplicationBuilder = {
    new GuiceApplicationBuilder().
      in(Mode.Test).
      disable[HealthCheckerModule].
      disable[KamonModule].
      disable[KamonPlayExtensionsModule].
      overrides(bind[Metrics].to(au.com.agiledigital.kamon.play_extensions.test.metrics)).
      overrides(bind[HealthCheckManager].to(emptyHealthCheckManager)).
      configure("kamon.show-aspectj-missing-warning" -> false)
  }

  /**
    * A do nothing health check manager.
    */
  val emptyHealthCheckManager: HealthCheckManager =
    new HealthCheckManager(Nil, ActorSystem.create("no-op-health-checks"))
}