text:
// DefinitelyTyped: partial

// This file contains common part of defintions for rx.d.ts and rx.lite.d.ts
// Do not include the file separately.

declare module Rx {
	export module internals {
		function isEqual(left: any, right: any): boolean;
		function addRef<T>(xs: Observable<T>, r: { getDisposable(): IDisposable; }): Observable<T>;

		// Priority Queue for Scheduling
		export class PriorityQueue<TTime> {
			constructor(capacity: number);

			length: number;

			isHigherPriority(left: number, right: number): boolean;
			percolate(index: number): void;
			heapify(index: number): void;
			peek(): ScheduledItem<TTime>;
			removeAt(index: number): void;
			dequeue(): ScheduledItem<TTime>;
			enqueue(item: ScheduledItem<TTime>): void;
			remove(item: ScheduledItem<TTime>): boolean;

			static count: number;
		}

		export class ScheduledItem<TTime> {
			constructor(scheduler: IScheduler, state: any, action: (scheduler: IScheduler, state: any) => IDisposable, dueTime: TTime, comparer?: (x: TTime, y: TTime) => number);

			scheduler: IScheduler;
			state: TTime;
			action: (scheduler: IScheduler, state: any) => IDisposable;
			dueTime: TTime;
			comparer: (x: TTime, y: TTime) => number;
			disposable: SingleAssignmentDisposable;

			invoke(): void;
			compareTo(other: ScheduledItem<TTime>): number;
			isCancelled(): boolean;
			invokeCore(): IDisposable;
		}
	}

	export module config {
		export var Promise: { new <T>(resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise<T>; };
	}

	export module helpers {
		function noop(): void;
		function notDefined(value: any): boolean;
		function isScheduler(value: any): boolean;
		function identity<T>(value: T): T;
		function defaultNow(): number;
		function defaultComparer(left: any, right: any): boolean;
		function defaultSubComparer(left: any, right: any): number;
		function defaultKeySerializer(key: any): string;
		function defaultError(err: any): void;
		function isPromise(p: any): boolean;
		function asArray<T>(...args: T[]): T[];
		function not(value: any): boolean;
		function isFunction(value: any): boolean;
	}

	export interface IDisposable {
		dispose(): void;
	}

	export class CompositeDisposable implements IDisposable {
		constructor (...disposables: IDisposable[]);
		constructor (disposables: IDisposable[]);

		isDisposed: boolean;
		length: number;

		dispose(): void;
		add(item: IDisposable): void;
		remove(item: IDisposable): boolean;
		toArray(): IDisposable[];
	}

	export class Disposable implements IDisposable {
		constructor(action: () => void);

		static create(action: () => void): IDisposable;
		static empty: IDisposable;

		dispose(): void;
	}

	// Single assignment
	export class SingleAssignmentDisposable implements IDisposable {
		constructor();

		isDisposed: boolean;
		current: IDisposable;

		dispose(): void ;
		getDisposable(): IDisposable;
		setDisposable(value: IDisposable): void ;
	}

	// SerialDisposable it's an alias of SingleAssignmentDisposable
	export class SerialDisposable extends SingleAssignmentDisposable {
		constructor();
	}

	export class RefCountDisposable implements IDisposable {
		constructor(disposable: IDisposable);

		dispose(): void;

		isDisposed: boolean;
		getDisposable(): IDisposable;
	}

	export interface IScheduler {
		now(): number;

		schedule(action: () => void): IDisposable;
		scheduleWithState<TState>(state: TState, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable;
		scheduleWithAbsolute(dueTime: number, action: () => void): IDisposable;
		scheduleWithAbsoluteAndState<TState>(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) =>IDisposable): IDisposable;
		scheduleWithRelative(dueTime: number, action: () => void): IDisposable;
		scheduleWithRelativeAndState<TState>(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) =>IDisposable): IDisposable;

		scheduleRecursive(action: (action: () =>void ) =>void ): IDisposable;
		scheduleRecursiveWithState<TState>(state: TState, action: (state: TState, action: (state: TState) =>void ) =>void ): IDisposable;
		scheduleRecursiveWithAbsolute(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable;
		scheduleRecursiveWithAbsoluteAndState<TState>(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable;
		scheduleRecursiveWithRelative(dueTime: number, action: (action: (dueTime: number) =>void ) =>void ): IDisposable;
		scheduleRecursiveWithRelativeAndState<TState>(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) =>void ) =>void ): IDisposable;

		schedulePeriodic(period: number, action: () => void): IDisposable;
		schedulePeriodicWithState<TState>(state: TState, period: number, action: (state: TState) => TState): IDisposable;
	}

	export interface Scheduler extends IScheduler {
	}

	export interface SchedulerStatic {
		new (
			now: () => number,
			schedule: (state: any, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable,
			scheduleRelative: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable,
			scheduleAbsolute: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable): Scheduler;

		normalize(timeSpan: number): number;

		immediate: IScheduler;
		currentThread: ICurrentThreadScheduler;
                default: IScheduler; // alias for Scheduler.timeout
		timeout: IScheduler;
	}

	export var Scheduler: SchedulerStatic;

	// Current Thread IScheduler
	interface ICurrentThreadScheduler extends IScheduler {
		scheduleRequired(): boolean;
	}

	// Notifications
	export class Notification<T> {
		accept(observer: IObserver<T>): void;
		accept<TResult>(onNext: (value: T) => TResult, onError?: (exception: any) => TResult, onCompleted?: () => TResult): TResult;
		toObservable(scheduler?: IScheduler): Observable<T>;
		hasValue: boolean;
		equals(other: Notification<T>): boolean;
		kind: string;
		value: T;
		exception: any;

		static createOnNext<T>(value: T): Notification<T>;
		static createOnError<T>(exception: any): Notification<T>;
		static createOnCompleted<T>(): Notification<T>;
	}

	/**
	 * Promise A+
	 */
	export interface IPromise<T> {
		then<R>(onFulfilled: (value: T) => IPromise<R>, onRejected: (reason: any) => IPromise<R>): IPromise<R>;
		then<R>(onFulfilled: (value: T) => IPromise<R>, onRejected?: (reason: any) => R): IPromise<R>;
		then<R>(onFulfilled: (value: T) => R, onRejected: (reason: any) => IPromise<R>): IPromise<R>;
		then<R>(onFulfilled?: (value: T) => R, onRejected?: (reason: any) => R): IPromise<R>;
	}

	// Observer
	export interface IObserver<T> {
		onNext(value: T): void;
		onError(exception: any): void;
		onCompleted(): void;
	}

	export interface Observer<T> extends IObserver<T> {
		toNotifier(): (notification: Notification<T>) => void;
		asObserver(): Observer<T>;
	}

	interface ObserverStatic {
		create<T>(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observer<T>;
		fromNotifier<T>(handler: (notification: Notification<T>, thisArg?: any) => void): Observer<T>;
	}

	export var Observer: ObserverStatic;

	export interface IObservable<T> {
		subscribe(observer: Observer<T>): IDisposable;
		subscribe(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable;

		subscribeOnNext(onNext: (value: T) => void, thisArg?: any): IDisposable;
		subscribeOnError(onError: (exception: any) => void, thisArg?: any): IDisposable;
		subscribeOnCompleted(onCompleted: () => void, thisArg?: any): IDisposable;
	}

	export interface Observable<T> extends IObservable<T> {
		forEach(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable;	// alias for subscribe
		toArray(): Observable<T[]>;

		catch(handler: (exception: any) => Observable<T>): Observable<T>;
		catchException(handler: (exception: any) => Observable<T>): Observable<T>;	// alias for catch
		catch(handler: (exception: any) => IPromise<T>): Observable<T>;
		catchException(handler: (exception: any) => IPromise<T>): Observable<T>;	// alias for catch
		catch(second: Observable<T>): Observable<T>;
		catchException(second: Observable<T>): Observable<T>;	// alias for catch
		combineLatest<T2, TResult>(second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>;
		combineLatest<T2, TResult>(second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>;
		combineLatest<T2, T3, TResult>(second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T2, T3, TResult>(second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T2, T3, TResult>(second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T2, T3, TResult>(second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T2, T3, T4, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T2, T3, T4, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T2, T3, T4, TResult>(second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T2, T3, T4, TResult>(second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T2, T3, T4, TResult>(second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T2, T3, T4, TResult>(second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T2, T3, T4, TResult>(second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T2, T3, T4, TResult>(second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T2, T3, T4, T5, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, fifth: Observable<T5>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable<TResult>;
		combineLatest<TOther, TResult>(souces: Observable<TOther>[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable<TResult>;
		combineLatest<TOther, TResult>(souces: IPromise<TOther>[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable<TResult>;
		concat(...sources: Observable<T>[]): Observable<T>;
		concat(...sources: IPromise<T>[]): Observable<T>;
		concat(sources: Observable<T>[]): Observable<T>;
		concat(sources: IPromise<T>[]): Observable<T>;
		concatAll(): T;
		concatObservable(): T;	// alias for concatAll
		concatMap<T2, R>(selector: (value: T, index: number) => Observable<T2>, resultSelector: (value1: T, value2: T2, index: number) => R): Observable<R>;	// alias for selectConcat
		concatMap<T2, R>(selector: (value: T, index: number) => IPromise<T2>, resultSelector: (value1: T, value2: T2, index: number) => R): Observable<R>;	// alias for selectConcat
		concatMap<R>(selector: (value: T, index: number) => Observable<R>): Observable<R>;	// alias for selectConcat
		concatMap<R>(selector: (value: T, index: number) => IPromise<R>): Observable<R>;	// alias for selectConcat
		concatMap<R>(sequence: Observable<R>): Observable<R>;	// alias for selectConcat
		merge(maxConcurrent: number): T;
		merge(other: Observable<T>): Observable<T>;
		merge(other: IPromise<T>): Observable<T>;
		mergeAll(): T;
		mergeObservable(): T;	// alias for mergeAll
		skipUntil<T2>(other: Observable<T2>): Observable<T>;
		skipUntil<T2>(other: IPromise<T2>): Observable<T>;
		switch(): T;
		switchLatest(): T;	// alias for switch
		takeUntil<T2>(other: Observable<T2>): Observable<T>;
		takeUntil<T2>(other: IPromise<T2>): Observable<T>;
		zip<T2, TResult>(second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>;
		zip<T2, TResult>(second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>;
		zip<T2, T3, TResult>(second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		zip<T2, T3, TResult>(second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		zip<T2, T3, TResult>(second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		zip<T2, T3, TResult>(second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		zip<T2, T3, T4, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		zip<T2, T3, T4, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		zip<T2, T3, T4, TResult>(second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		zip<T2, T3, T4, TResult>(second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		zip<T2, T3, T4, TResult>(second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		zip<T2, T3, T4, TResult>(second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		zip<T2, T3, T4, TResult>(second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		zip<T2, T3, T4, TResult>(second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		zip<T2, T3, T4, T5, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, fifth: Observable<T5>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable<TResult>;
		zip<TOther, TResult>(second: Observable<TOther>[], resultSelector: (left: T, ...right: TOther[]) => TResult): Observable<TResult>;
		zip<TOther, TResult>(second: IPromise<TOther>[], resultSelector: (left: T, ...right: TOther[]) => TResult): Observable<TResult>;

		asObservable(): Observable<T>;
		dematerialize<TOrigin>(): Observable<TOrigin>;
		distinctUntilChanged(skipParameter: boolean, comparer: (x: T, y: T) => boolean): Observable<T>;
		distinctUntilChanged<TValue>(keySelector?: (value: T) => TValue, comparer?: (x: TValue, y: TValue) => boolean): Observable<T>;
		do(observer: Observer<T>): Observable<T>;
		doAction(observer: Observer<T>): Observable<T>;	// alias for do
		tap(observer: Observer<T>): Observable<T>;	// alias for do
		do(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable<T>;
		doAction(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable<T>;	// alias for do
		tap(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable<T>;	// alias for do

		doOnNext(onNext: (value: T) => void, thisArg?: any): Observable<T>;
		doOnError(onError: (exception: any) => void, thisArg?: any): Observable<T>;
		doOnCompleted(onCompleted: () => void, thisArg?: any): Observable<T>;
		tapOnNext(onNext: (value: T) => void, thisArg?: any): Observable<T>;
		tapOnError(onError: (exception: any) => void, thisArg?: any): Observable<T>;
		tapOnCompleted(onCompleted: () => void, thisArg?: any): Observable<T>;

		finally(action: () => void): Observable<T>;
		finallyAction(action: () => void): Observable<T>;	// alias for finally
		ignoreElements(): Observable<T>;
		materialize(): Observable<Notification<T>>;
		repeat(repeatCount?: number): Observable<T>;
		retry(retryCount?: number): Observable<T>;
		scan<TAcc>(seed: TAcc, accumulator: (acc: TAcc, value: T) => TAcc): Observable<TAcc>;
		scan(accumulator: (acc: T, value: T) => T): Observable<T>;
		skipLast(count: number): Observable<T>;
		startWith(...values: T[]): Observable<T>;
		startWith(scheduler: IScheduler, ...values: T[]): Observable<T>;
		takeLast(count: number): Observable<T>;
		takeLastBuffer(count: number): Observable<T[]>;

		select<TResult>(selector: (value: T, index: number, source: Observable<T>) => TResult, thisArg?: any): Observable<TResult>;
		map<TResult>(selector: (value: T, index: number, source: Observable<T>) => TResult, thisArg?: any): Observable<TResult>;	// alias for select
		pluck<TResult>(prop: string): Observable<TResult>;
		selectMany<TOther, TResult>(selector: (value: T) => Observable<TOther>, resultSelector: (item: T, other: TOther) => TResult): Observable<TResult>;
		selectMany<TOther, TResult>(selector: (value: T) => IPromise<TOther>, resultSelector: (item: T, other: TOther) => TResult): Observable<TResult>;
		selectMany<TResult>(selector: (value: T) => Observable<TResult>): Observable<TResult>;
		selectMany<TResult>(selector: (value: T) => IPromise<TResult>): Observable<TResult>;
		selectMany<TResult>(other: Observable<TResult>): Observable<TResult>;
		selectMany<TResult>(other: IPromise<TResult>): Observable<TResult>;
		flatMap<TOther, TResult>(selector: (value: T) => Observable<TOther>, resultSelector: (item: T, other: TOther) => TResult): Observable<TResult>;	// alias for selectMany
		flatMap<TOther, TResult>(selector: (value: T) => IPromise<TOther>, resultSelector: (item: T, other: TOther) => TResult): Observable<TResult>;	// alias for selectMany
		flatMap<TResult>(selector: (value: T) => Observable<TResult>): Observable<TResult>;	// alias for selectMany
		flatMap<TResult>(selector: (value: T) => IPromise<TResult>): Observable<TResult>;	// alias for selectMany
		flatMap<TResult>(other: Observable<TResult>): Observable<TResult>;	// alias for selectMany
		flatMap<TResult>(other: IPromise<TResult>): Observable<TResult>;	// alias for selectMany

		selectConcat<T2, R>(selector: (value: T, index: number) => Observable<T2>, resultSelector: (value1: T, value2: T2, index: number) => R): Observable<R>;
		selectConcat<T2, R>(selector: (value: T, index: number) => IPromise<T2>, resultSelector: (value1: T, value2: T2, index: number) => R): Observable<R>;
		selectConcat<R>(selector: (value: T, index: number) => Observable<R>): Observable<R>;
		selectConcat<R>(selector: (value: T, index: number) => IPromise<R>): Observable<R>;
		selectConcat<R>(sequence: Observable<R>): Observable<R>;

		/**
		*  Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
		*  transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
		* @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
		* @param [thisArg] Object to use as this when executing callback.
		* @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
		*  and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
		*/
		selectSwitch<TResult>(selector: (value: T, index: number, source: Observable<T>) => Observable<TResult>, thisArg?: any): Observable<TResult>;
		/**
		*  Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
		*  transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
		* @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
		* @param [thisArg] Object to use as this when executing callback.
		* @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
		*  and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
		*/
		flatMapLatest<TResult>(selector: (value: T, index: number, source: Observable<T>) => Observable<TResult>, thisArg?: any): Observable<TResult>;	// alias for selectSwitch
		/**
		*  Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
		*  transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
		* @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
		* @param [thisArg] Object to use as this when executing callback.
		* @since 2.2.28
		* @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
		*  and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
		*/
		switchMap<TResult>(selector: (value: T, index: number, source: Observable<T>) => TResult, thisArg?: any): Observable<TResult>;	// alias for selectSwitch

		skip(count: number): Observable<T>;
		skipWhile(predicate: (value: T, index: number, source: Observable<T>) => boolean, thisArg?: any): Observable<T>;
		take(count: number, scheduler?: IScheduler): Observable<T>;
		takeWhile(predicate: (value: T, index: number, source: Observable<T>) => boolean, thisArg?: any): Observable<T>;
		where(predicate: (value: T, index: number, source: Observable<T>) => boolean, thisArg?: any): Observable<T>;
		filter(predicate: (value: T, index: number, source: Observable<T>) => boolean, thisArg?: any): Observable<T>; // alias for where

		/**
		* Converts an existing observable sequence to an ES6 Compatible Promise
		* @example
		* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
		* @param promiseCtor The constructor of the promise.
		* @returns An ES6 compatible promise with the last value from the observable sequence.
		*/
		toPromise<TPromise extends IPromise<T>>(promiseCtor: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): TPromise; }): TPromise;
		/**
		* Converts an existing observable sequence to an ES6 Compatible Promise
		* @example
		* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
		*
		* // With config
		* Rx.config.Promise = RSVP.Promise;
		* var promise = Rx.Observable.return(42).toPromise();
		* @param [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
		* @returns An ES6 compatible promise with the last value from the observable sequence.
		*/
		toPromise(promiseCtor?: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise<T>; }): IPromise<T>;

		// Experimental Flattening

		/**
		* Performs a exclusive waiting for the first to finish before subscribing to another observable.
		* Observables that come in between subscriptions will be dropped on the floor.
		* Can be applied on `Observable<Observable<R>>` or `Observable<IPromise<R>>`.
		* @since 2.2.28
		* @returns A exclusive observable with only the results that happen when subscribed.
		*/
		exclusive<R>(): Observable<R>;

		/**
		* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
		* Observables that come in between subscriptions will be dropped on the floor.
		* Can be applied on `Observable<Observable<I>>` or `Observable<IPromise<I>>`.
		* @since 2.2.28
		* @param selector Selector to invoke for every item in the current subscription.
		* @param [thisArg] An optional context to invoke with the selector parameter.
		* @returns {An exclusive observable with only the results that happen when subscribed.
		*/
		exclusiveMap<I, R>(selector: (value: I, index: number, source: Observable<I>) => R, thisArg?: any): Observable<R>;
	}

    interface ObservableStatic {
        new<T>():Observable<T>;
		create<T>(subscribe: (observer: Observer<T>) => IDisposable): Observable<T>;
		create<T>(subscribe: (observer: Observer<T>) => () => void): Observable<T>;
		create<T>(subscribe: (observer: Observer<T>) => void): Observable<T>;
		createWithDisposable<T>(subscribe: (observer: Observer<T>) => IDisposable): Observable<T>;
		defer<T>(observableFactory: () => Observable<T>): Observable<T>;
		defer<T>(observableFactory: () => IPromise<T>): Observable<T>;
		empty<T>(scheduler?: IScheduler): Observable<T>;

		/**
		* This method creates a new Observable sequence from an array object.
		* @param array An array-like or iterable object to convert to an Observable sequence.
		* @param mapFn Map function to call on every element of the array.
		* @param [thisArg] The context to use calling the mapFn if provided.
		* @param [scheduler] Optional scheduler to use for scheduling.  If not provided, defaults to Scheduler.currentThread.
		*/
		from<T, TResult>(array: T[], mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler): Observable<TResult>;
		/**
		* This method creates a new Observable sequence from an array object.
		* @param array An array-like or iterable object to convert to an Observable sequence.
		* @param [mapFn] Map function to call on every element of the array.
		* @param [thisArg] The context to use calling the mapFn if provided.
		* @param [scheduler] Optional scheduler to use for scheduling.  If not provided, defaults to Scheduler.currentThread.
		*/
		from<T>(array: T[], mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable<T>;

		/**
		* This method creates a new Observable sequence from an array-like object.
		* @param array An array-like or iterable object to convert to an Observable sequence.
		* @param mapFn Map function to call on every element of the array.
		* @param [thisArg] The context to use calling the mapFn if provided.
		* @param [scheduler] Optional scheduler to use for scheduling.  If not provided, defaults to Scheduler.currentThread.
		*/
		from<T, TResult>(array: { length: number;[index: number]: T; }, mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler): Observable<TResult>;
		/**
		* This method creates a new Observable sequence from an array-like object.
		* @param array An array-like or iterable object to convert to an Observable sequence.
		* @param [mapFn] Map function to call on every element of the array.
		* @param [thisArg] The context to use calling the mapFn if provided.
		* @param [scheduler] Optional scheduler to use for scheduling.  If not provided, defaults to Scheduler.currentThread.
		*/
		from<T>(array: { length: number;[index: number]: T; }, mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable<T>;

		/**
		* This method creates a new Observable sequence from an array-like or iterable object.
		* @param array An array-like or iterable object to convert to an Observable sequence.
		* @param [mapFn] Map function to call on every element of the array.
		* @param [thisArg] The context to use calling the mapFn if provided.
		* @param [scheduler] Optional scheduler to use for scheduling.  If not provided, defaults to Scheduler.currentThread.
		*/
		from<T>(iterable: any, mapFn?: (value: any, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable<T>;

		fromArray<T>(array: T[], scheduler?: IScheduler): Observable<T>;
		fromArray<T>(array: { length: number;[index: number]: T; }, scheduler?: IScheduler): Observable<T>;

		/**
		*  Converts an iterable into an Observable sequence
		*
		* @example
		*  var res = Rx.Observable.fromIterable(new Map());
		*  var res = Rx.Observable.fromIterable(function* () { yield 42; });
		*  var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout);
		* @param generator Generator to convert from.
		* @param [scheduler] Scheduler to run the enumeration of the input sequence on.
		* @returns The observable sequence whose elements are pulled from the given generator sequence.
		*/
		fromIterable<T>(generator: () => { next(): { done: boolean; value?: T; }; }, scheduler?: IScheduler): Observable<T>;

		/**
		*  Converts an iterable into an Observable sequence
		*
		* @example
		*  var res = Rx.Observable.fromIterable(new Map());
		*  var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout);
		* @param iterable Iterable to convert from.
		* @param [scheduler] Scheduler to run the enumeration of the input sequence on.
		* @returns The observable sequence whose elements are pulled from the given generator sequence.
		*/
		fromIterable<T>(iterable: {}, scheduler?: IScheduler): Observable<T>;	// todo: can't describe ES6 Iterable via TypeScript type system
		generate<TState, TResult>(initialState: TState, condition: (state: TState) => boolean, iterate: (state: TState) => TState, resultSelector: (state: TState) => TResult, scheduler?: IScheduler): Observable<TResult>;
		never<T>(): Observable<T>;

		/**
		*  This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
		*
		* @example
		*  var res = Rx.Observable.of(1, 2, 3);
		* @since 2.2.28
		* @returns The observable sequence whose elements are pulled from the given arguments.
		*/
		of<T>(...values: T[]): Observable<T>;

		/**
		*  This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
		* @example
		*  var res = Rx.Observable.ofWithScheduler(Rx.Scheduler.timeout, 1, 2, 3);
		* @since 2.2.28
		* @param [scheduler] A scheduler to use for scheduling the arguments.
		* @returns The observable sequence whose elements are pulled from the given arguments.
		*/
		ofWithScheduler<T>(scheduler?: IScheduler, ...values: T[]): Observable<T>;
		range(start: number, count: number, scheduler?: IScheduler): Observable<number>;
		repeat<T>(value: T, repeatCount?: number, scheduler?: IScheduler): Observable<T>;
		return<T>(value: T, scheduler?: IScheduler): Observable<T>;
		/**
		 * @since 2.2.28
		 */
		just<T>(value: T, scheduler?: IScheduler): Observable<T>;	// alias for return
		returnValue<T>(value: T, scheduler?: IScheduler): Observable<T>;	// alias for return
		throw<T>(exception: Error, scheduler?: IScheduler): Observable<T>;
		throw<T>(exception: any, scheduler?: IScheduler): Observable<T>;
		throwException<T>(exception: Error, scheduler?: IScheduler): Observable<T>;	// alias for throw
		throwException<T>(exception: any, scheduler?: IScheduler): Observable<T>;	// alias for throw
		throwError<T>(error: Error, scheduler?: IScheduler): Observable<T>;	// alias for throw
		throwError<T>(error: any, scheduler?: IScheduler): Observable<T>;	// alias for throw

		catch<T>(sources: Observable<T>[]): Observable<T>;
		catch<T>(sources: IPromise<T>[]): Observable<T>;
		catchException<T>(sources: Observable<T>[]): Observable<T>;	// alias for catch
		catchException<T>(sources: IPromise<T>[]): Observable<T>;	// alias for catch
		catchError<T>(sources: Observable<T>[]): Observable<T>;	// alias for catch
		catchError<T>(sources: IPromise<T>[]): Observable<T>;	// alias for catch
		catch<T>(...sources: Observable<T>[]): Observable<T>;
		catch<T>(...sources: IPromise<T>[]): Observable<T>;
		catchException<T>(...sources: Observable<T>[]): Observable<T>;	// alias for catch
		catchException<T>(...sources: IPromise<T>[]): Observable<T>;	// alias for catch
		catchError<T>(...sources: Observable<T>[]): Observable<T>;	// alias for catch
		catchError<T>(...sources: IPromise<T>[]): Observable<T>;	// alias for catch

		combineLatest<T, T2, TResult>(first: Observable<T>, second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>;
		combineLatest<T, T2, TResult>(first: IPromise<T>, second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>;
		combineLatest<T, T2, TResult>(first: Observable<T>, second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>;
		combineLatest<T, T2, TResult>(first: IPromise<T>, second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, TResult>(first: Observable<T>, second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, TResult>(first: Observable<T>, second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, TResult>(first: Observable<T>, second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, TResult>(first: IPromise<T>, second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, TResult>(first: IPromise<T>, second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, TResult>(first: IPromise<T>, second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, TResult>(first: IPromise<T>, second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>;
		combineLatest<T, T2, T3, T4, T5, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, fifth: Observable<T5>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable<TResult>;
		combineLatest<TOther, TResult>(souces: Observable<TOther>[], resultSelector: (...otherValues: TOther[]) => TResult): Observable<TResult>;
		combineLatest<TOther, TResult>(souces: IPromise<TOther>[], resultSelector: (...otherValues: TOther[]) => TResult): Observable<TResult>;

		concat<T>(...sources: Observable<T>[]): Observable<T>;
		concat<T>(...sources: IPromise<T>[]): Observable<T>;
		concat<T>(sources: Observable<T>[]): Observable<T>;
		concat<T>(sources: IPromise<T>[]): Observable<T>;
		merge<T>(...sources: Observable<T>[]): Observable<T>;
		merge<T>(...sources: IPromise<T>[]): Observable<T>;
		merge<T>(sources: Observable<T>[]): Observable<T>;
		merge<T>(sources: IPromise<T>[]): Observable<T>;
		merge<T>(scheduler: IScheduler, ...sources: Observable<T>[]): Observable<T>;
		merge<T>(scheduler: IScheduler, ...sources: IPromise<T>[]): Observable<T>;
		merge<T>(scheduler: IScheduler, sources: Observable<T>[]): Observable<T>;
		merge<T>(scheduler: IScheduler, sources: IPromise<T>[]): Observable<T>;

		pairs<T>(obj: { [key: string]: T }, scheduler?: IScheduler): Observable<[string, T]>;

		zip<T1, T2, TResult>(first: Observable<T1>, sources: Observable<T2>[], resultSelector: (item1: T1, ...right: T2[]) => TResult): Observable<TResult>;
		zip<T1, T2, TResult>(first: Observable<T1>, sources: IPromise<T2>[], resultSelector: (item1: T1, ...right: T2[]) => TResult): Observable<TResult>;
		zip<T1, T2, TResult>(source1: Observable<T1>, source2: Observable<T2>, resultSelector: (item1: T1, item2: T2) => TResult): Observable<TResult>;
		zip<T1, T2, TResult>(source1: Observable<T1>, source2: IPromise<T2>, resultSelector: (item1: T1, item2: T2) => TResult): Observable<TResult>;
		zip<T1, T2, T3, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable<TResult>;
		zip<T1, T2, T3, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: IPromise<T3>, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable<TResult>;
		zip<T1, T2, T3, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: Observable<T3>, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable<TResult>;
		zip<T1, T2, T3, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: IPromise<T3>, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable<TResult>;
		zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>;
		zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: IPromise<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>;
		zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: IPromise<T3>, source4: Observable<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>;
		zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: IPromise<T3>, source4: IPromise<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>;
		zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: Observable<T3>, source4: Observable<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>;
		zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: Observable<T3>, source4: IPromise<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>;
		zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: IPromise<T3>, source4: Observable<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>;
		zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: IPromise<T3>, source4: IPromise<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>;
		zip<T1, T2, T3, T4, T5, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5) => TResult): Observable<TResult>;
		zipArray<T>(...sources: Observable<T>[]): Observable<T[]>;
		zipArray<T>(sources: Observable<T>[]): Observable<T[]>;

		/**
		* Converts a Promise to an Observable sequence
		* @param promise An ES6 Compliant promise.
		* @returns An Observable sequence which wraps the existing promise success and failure.
		*/
		fromPromise<T>(promise: IPromise<T>): Observable<T>;
	}

	export var Observable: ObservableStatic;

	interface ISubject<T> extends Observable<T>, Observer<T>, IDisposable {
		hasObservers(): boolean;
	}

	export interface Subject<T> extends ISubject<T> {
	}

	interface SubjectStatic {
		new <T>(): Subject<T>;
		create<T>(observer?: Observer<T>, observable?: Observable<T>): ISubject<T>;
	}

	export var Subject: SubjectStatic;

	export interface AsyncSubject<T> extends Subject<T> {
	}

	interface AsyncSubjectStatic {
		new <T>(): AsyncSubject<T>;
	}

	export var AsyncSubject: AsyncSubjectStatic;
}


text:
This is an [AngularJS](http://angularjs.org) application scaffold. It's inspired by [angular-app](https://github.com/angular-app/angular-app). So the JavaScript and other source code is **organized in modules** and not "by layer". It also provides a build, test and basic deployment process based on [Grunt](http://gruntjs.com/), [Bower](http://bower.io/) and [Karma](http://karma-runner.github.io/). You can use this skeleton as a starting point for frontend development with AngularJS.

In addition the ng-scaffold project is the groundwork for [generator-ng-scaffold](https://github.com/nosch/generator-ng-scaffold), a [yeoman](http://yeoman.io) generator for AngularJS.

## Installation

1. Install [node.js and npm](http://nodejs.org/download/ "Download node.js")
2. $ npm install -g grunt-cli
3. $ git clone git@github.com:nosch/ng-scaffold.git "ng-scaffold"
4. $ cd ng-scaffold
5. $ npm install

## How to use
### Develop and build process

Start to develop, to test (incl. code coverage with Istanbul and reports with Plato) and finally to build an AngularJS application with one of the following grunt tasks.

- $ grunt server (default)
- $ grunt test
- $ grunt coverage (generates test/coverage/)
- $ grunt report (generates reports/)
- $ grunt release

### End-To-End testing with protractor

Run e2e test with [protractor](https://github.com/angular/protractor):

1. $ npm install -g protractor
2. $ webdriver-manager update
3. $ grunt server
4. $ protractor test/config/protractor.conf.js

## Stack
### Application

- AngularJS v1.2.16
- UI-Router v0.2.10
- Twitter Bootstrap v3.1.1
- jQuery v2.1.1
- Underscore.js v1.6.0
- Moment.js v2.6.0
- Modernizr v2.8.2

### Build process

- Grunt v0.4.5
- Bower v1.3.3
- Karma v0.12.16

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Guidap\NumberBundle\Controller;

use Guidap\NumberBundle\Entity\Number;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Number controller.
 *
 */
class ApiNumberController extends Controller {

    /**
     * Finds the last number added in the database and compare him with the value sended
     *
     */
    public function CompareAction(Request $request, Int $valueSend) {

        //Check origin request
        $referer = $request->server->get('HTTP_REFERER');
        $origin = $this->generateUrl('number_index', [], UrlGeneratorInterface::ABSOLUTE_URL);
        if ($referer != $origin):
            return new JsonResponse(["error" => "You're not in the app"]);
        endif;
        if($request->server->get("REQUEST_METHOD") != "GET"):
            return new JsonResponse(["error" => "not GET Method, you are ".$request->server->get("REQUEST_METHOD")]);
        endif;
        if (!$request->isXmlHttpRequest()):
            return new JsonResponse(["error" => "Is not ajax"]);
        endif;

        $repository = $this->getDoctrine()->getRepository(Number::class);
        $number = $repository->findLastAdded();
        return new JsonResponse(["status" => $number->compareValue($valueSend), 'error' => FALSE]);
    }

}


text:
declare const require: any;
declare const __dirname: any;

namespace karoo.poacher
{
    export class ScreenshotApp
    {
        protected screenshotTool;
        protected win;
        protected tools     = [];
        protected inBrowser = false;
        protected testMode  = true;
        protected exportCanvas: HTMLCanvasElement;
        protected electron: any;
        protected isOSX: boolean;
        protected cloudUploadProvider: any;

        constructor()
        {
            this.inBrowser =
                !window || !window['process'] || !window['process'].versions || !window['process'].versions.electron;

            this.isOSX = /^darwin/.test(window['process'].platform);

            if (!this.inBrowser)
            {
                this.electron       = require('electron');
                this.screenshotTool = require('cli-fullscreen-screenshot');

                this.win = this.electron.remote.getCurrentWindow();

                this.electron.ipcRenderer.on('take-screenshot', () => this.takeScreenshot());

                Mousetrap.bind('esc', () => this.hideWindow());
            }

            this.bindHotkeys();

            //FIXME: get rid of ugly jquery usage
            jQuery(() => { this.setUpCanvas(); });

            if (this.inBrowser && this.testMode)
                jQuery(() => { this.fakeScreenshot(); });

            this.exportCanvas = document.createElement('CANVAS') as HTMLCanvasElement;

            this.loadCloudProviderSettings();
        }

        public takeScreenshot()
        {
            this.hideWindow(true);
            this.restart();
            const path             = require('path');
            let screenshotFilename = path.join(__dirname, '/tmp/screenshot_' + Math.random() + '.png');
            let screenshotConfig   = {
                outfile: screenshotFilename
            };

            new this.screenshotTool.Screenshot(screenshotConfig, (error/*, complete*/) =>
            {
                if (error)
                {
                    console.log('Screenshot failed', error);
                    return;
                }
                let $img = jQuery('#img');
                $img.one('load', () =>
                {
                    let raster      = new (window as any).paper.Raster('img');
                    raster.position = new (window as any).paper.Point(raster.size.width / 2, raster.size.height / 2);
                    toastr.remove();

                    this.showFullscreenWindow();
                    toastr.info('Start dragging to select')
                });
                $img.attr('src', screenshotFilename + '');
            });
        }

        public fakeScreenshot()
        {
            let screenshotFilename = 'tmp/demo.png';

            let $img = jQuery('#img');
            $img.attr('src', screenshotFilename + '');
            $img.on('load', () =>
            {
                let raster      = new (window as any).paper.Raster('img');
                raster.position = new (window as any).paper.Point(raster.size.width / 2, raster.size.height / 2);
                jQuery('#mainCanvas').css('display', 'block');
            });
        }

        public showFullscreenWindow()
        {
            let minX = Number.MAX_VALUE;
            let minY = Number.MAX_VALUE;
            let maxX = Number.MIN_VALUE;
            let maxY = Number.MIN_VALUE;

            let screens = this.electron.screen.getAllDisplays();
            for (let i = 0; i < screens.length; i++)
            {
                let bounds = screens[i].bounds;
                if (bounds.x < minX)
                    minX = bounds.x;
                if (bounds.y < minY)
                    minY = bounds.y;

                if (bounds.x + bounds.width > maxX)
                    maxX = bounds.x + bounds.width;
                if (bounds.y + bounds.height > maxY)
                    maxY = bounds.y + bounds.height;
            }
            this.win.setBounds({x: minX, y: minY, width: maxX - minX, height: maxY - minY});
            //leave half screen for test:
            //this.win.setBounds({x: minX, y: minY, width: maxX, height: maxY - minY});

            jQuery('#mainCanvas').fadeIn(50);

            if (this.isOSX)
            {
                this.win.setAlwaysOnTop(true, 'screen-saver');
                this.electron.remote.getGlobal('macOnTop')();
            }

            this.win.show();
        }

        private hideWindow(isImmediate = false)
        {
            if (this.inBrowser)
                return;

            //this.win.setBounds({x: 0, y: 0, width: 0, height: 0});
            if (isImmediate)
            {
                jQuery('#mainCanvas').fadeOut(50);
                (window as any).paper.project.activeLayer.removeChildren();
                if (this.win.isVisible())
                {
                    this.win.hide();
                    if (this.isOSX)
                        this.electron.remote.getGlobal('macOffTop')()
                }
            }
            else
            {
                jQuery('#mainCanvas').fadeOut(50, () =>
                {
                    (window as any).paper.project.activeLayer.removeChildren();
                    if (this.win.isVisible())
                    {
                        this.win.hide();
                        if (this.isOSX)
                            this.electron.remote.getGlobal('macOffTop')();
                    }
                });
            }

            //FIXME: this is very non-obvious thing right here. not immediate means it's not ensuring closing after open
            if (!isImmediate)
                this.runGarbageCollector();
        }

        private setUpCanvas()
        {
            let canvas = document.getElementById('mainCanvas');
            // Create an empty project and a view for the canvas:
            (window as any).paper.setup(canvas as HTMLCanvasElement);

            this.setUpDrawingTool();
            this.setUpArrowTool();
            this.setUpCropTool();
            this.tools['crop'].activate();
        }

        //FIXME: these need to be plugins
        private setUpDrawingTool()
        {
            this.tools['drawing'] = new karoo.poacher.tools.Drawing();
        }

        private setUpArrowTool()
        {
            this.tools['arrow'] = new karoo.poacher.tools.Arrow();
        }

        private setUpCropTool()
        {
            this.tools['crop'] = new karoo.poacher.tools.Crop();
            this.tools['crop'].onMouseUp.on(() => { this.tools['arrow'].activate(); });
        }

        //noinspection JSUnusedLocalSymbols
        private setUpTextTool()
        {
            //TODO
        }

        private resultToBuffer()
        {
            this.exportResult();
            this.hideWindow();

            //TODO: check if there's a workaround for browser
            if (this.inBrowser)
            {
                alert('Buffer not supported in browser');
                this.restart();
            }
            else
                this.electron.clipboard.writeImage(
                    this.electron.nativeImage.createFromDataURL(this.exportCanvas.toDataURL()), 'png');
        }

        private resultToCloud()
        {
            this.exportResult();
            this.hideWindow();

            this.loadCloudProviderSettings();

            if (!this.cloudUploadProvider)
                return;

            this.cloudUploadProvider.submit(this.exportCanvas.toDataURL()).done((o) =>
            {
                if (this.inBrowser)
                {
                    if (this.isOSX)
                        window.prompt('Press Command+C to copy', o.url);
                    else
                        window.prompt('Press Ctrl+C to copy', o.url);
                    this.restart();
                }
                else
                    this.electron.clipboard.writeText(o.url);
            });
        }

        private resultToFilesystem()
        {
            this.exportResult();

            this.hideWindow();

            this.exportCanvas.toBlob(function (blob)
            {
                let FileSaver = require('file-saver');
                FileSaver.saveAs(blob, 'screenshot.png');
            });
        }

        private undo()
        {

        }

        private redo()
        {

        }

        private restart()
        {
            this.tools['crop'].clear();
            this.tools['crop'].activate();

            this.tools['arrow'].clear();

            this.tools['drawing'].clear();
        }

        private exportResult()
        {
            let area = this.tools['crop'].area;
            this.tools['crop'].clear();
            (window as any).paper.view.draw();

            this.exportCanvas.width  = area[2];
            this.exportCanvas.height = area[3];
            let destinationContext   = this.exportCanvas.getContext('2d');
            destinationContext.drawImage(
                document.getElementById('mainCanvas') as HTMLCanvasElement,
                area[0], area[1], area[2], area[3],
                0, 0, area[2], area[3]
            );
        }

        private bindHotkeys()
        {
            //TODO: make this configurable
            let toBufferKey     = 'ctrl+c';
            let toCloudKey      = 'ctrl+d';
            let toFilesystemKey = 'ctrl+s';
            let undoKey         = 'ctrl+z';
            let redoKey         = ['ctrl+y', 'ctrl+shift+z'];
            let restartKey      = 'ctrl+r';
            let fakeKey         = 'ctrl+p';
            if (this.isOSX)
            {
                toBufferKey     = 'command+c';
                toCloudKey      = 'command+d';
                toFilesystemKey = 'command+s';
                undoKey         = 'command+z';
                redoKey         = ['command+y', 'command+shift+z'];
                restartKey      = 'command+r';
                fakeKey         = 'command+p';
            }

            Mousetrap.bind(toBufferKey, () =>
            {
                this.resultToBuffer();
                return false;
            });
            Mousetrap.bind(toCloudKey, () =>
            {
                this.resultToCloud();
                return false;
            });
            Mousetrap.bind(toFilesystemKey, () =>
            {
                this.resultToFilesystem();
                return false;
            });
            Mousetrap.bind(undoKey, () =>
            {
                this.undo();
                return false;
            });
            Mousetrap.bind(redoKey, () =>
            {
                this.redo();
                return false;
            });
            Mousetrap.bind(restartKey, () =>
            {
                this.restart();
                return false;
            });

            if (!this.inBrowser && this.testMode)
            {
                Mousetrap.bind(fakeKey, () =>
                {
                    this.takeScreenshot();
                    return false
                });
            }

            //TODO: do we also need to check for Command+Q on mac?
            Mousetrap.bind('alt+f4', function () { return false; });
        }

        private loadCloudProviderSettings()
        {
            let settings = (window as any).storageWrap.getItem('settings');
            if (settings === null)
            {
                settings = {cloudProvider: 'imgur'};
                settings['cloudProviderSettings'] = {};
                settings['cloudProviderSettings'][settings.cloudProvider] = {};
            }

            if ((settings.cloudProvider !== null) && (settings.cloudProvider !== "none"))
            {
                if (settings.cloudProvider === 'karoo')
                    this.cloudUploadProvider = new karoo.poacher.cloud_upload_providers.Karoo(
                        settings['cloudProviderSettings'][settings.cloudProvider].token,
                        settings['cloudProviderSettings'][settings.cloudProvider].url
                    );
                else if (settings.cloudProvider === 'imgur')
                    this.cloudUploadProvider = new karoo.poacher.cloud_upload_providers.Imgur(
                        settings['cloudProviderSettings'][settings.cloudProvider].token,
                        settings['cloudProviderSettings'][settings.cloudProvider].url
                    );
            }
        }

        //noinspection JSMethodCanBeStatic
        private runGarbageCollector()
        {
            const fs    = require('fs');
            const path  = require('path');
            const dirPath = path.join(__dirname, '/tmp/');
            let files   = [];
            try { files = fs.readdirSync(dirPath); }
            catch (e) { return; }

            for (let i = 0; i < files.length; i++)
            {
                if ((files[i] === '.gitignore') || (files[i] === 'demo.png'))
                    continue;
                let filePath = dirPath + '/' + files[i];
                if (fs.statSync(filePath).isFile())
                    fs.unlinkSync(filePath);
            }
        }
    }
}

//noinspection JSUnusedGlobalSymbols
let app = new karoo.poacher.ScreenshotApp();


text:
#include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"

namespace firebase {
namespace firestore {
namespace model {

SnapshotVersion::SnapshotVersion(const Timestamp& timestamp)
    : timestamp_(timestamp) {
}

const SnapshotVersion& SnapshotVersion::None() {
  static const SnapshotVersion kNone(Timestamp{});
  return kNone;
}

util::ComparisonResult SnapshotVersion::CompareTo(
    const SnapshotVersion& rhs) const {
  return util::Compare(timestamp(), rhs.timestamp());
}

size_t SnapshotVersion::Hash() const {
  return std::hash<Timestamp>{}(timestamp_);
}

}  // namespace model
}  // namespace firestore
}  // namespace firebase


text:
package org.fhcrc.cpl.viewer.align;

import org.apache.log4j.Logger;
import org.fhcrc.cpl.toolbox.ApplicationContext;
import org.fhcrc.cpl.toolbox.datastructure.Pair;
import org.fhcrc.cpl.toolbox.statistics.RegressionUtilities;
import org.fhcrc.cpl.viewer.amt.AmtDatabaseMatcher;

import java.io.*;

/**
 * Aligner using quantile regression
 */
public class QuantileRegressionAligner extends Aligner
{
    private static Logger _log = Logger.getLogger(QuantileRegressionAligner.class);

    protected int nonlinearMappingPolynomialDegree =
            AmtDatabaseMatcher.DEFAULT_NONLINEAR_MAPPING_DEGREE;

    protected double[] modalRegressionCoefficients = null;

    public QuantileRegressionAligner()
    {
    }

    /**
     * Cover method. In the absence of filename information, use a filename that's
     * likely to be unique
     * @param pairs
     * @param maxValueToWarp
     * @return
     */
    public double[] alignPairs(Pair<Double,Double>[] pairs, int maxValueToWarp)
    {
        return alignPairs(pairs, maxValueToWarp, "length" + pairs.length);
    }

    /**
     * Generic method for creating a warping based on pairs of values.
     * Create temp files with names based on tempFileNameStart, in case the user
     * wants to peruse them
     * @param pairs
     * @param maxValueToWarp
     * @return
     */
    public double[] alignPairs(Pair<Double,Double>[] pairs, double maxValueToWarp,
                               String tempFileNameStart)
    {
        PrintWriter pw = null;
        double[] result = null;
        if (pairs.length < 4)
            throw new RuntimeException("QuantileRegressionAligner.alignPairs: at least 4 pairs are necessary for " +
                    "alignment, only " + pairs.length + " were provided");
        _log.debug("alignPairs, #pairs=" + pairs.length);
        try
        {
            double[] baseTimes = new double[pairs.length];
            double[] toAlignTimes = new double[pairs.length];

            for (int j=0; j<pairs.length; j++)
            {
                Pair<Double,Double> matchedPair = pairs[j];
                baseTimes[j] = matchedPair.first;
                toAlignTimes[j] = matchedPair.second;
            }
            try
            {
                modalRegressionCoefficients = RegressionUtilities.modalRegression(baseTimes,
                        toAlignTimes, nonlinearMappingPolynomialDegree);
                _log.debug("Regression complete");

                result = new double[(int) (maxValueToWarp+1)];
                for (int j=0; j<=maxValueToWarp; j++)
                {
                    result[j] =
                        RegressionUtilities.mapValueUsingCoefficients(modalRegressionCoefficients, j);

                }

            }
            catch (IOException e)
            {
                e.printStackTrace(System.err);
                //if we failed, it could be because of timeout, or because of a missing
                //quantreg package, or...?
                //todo: move text to bundle
                throw new RuntimeException("Failure calling R for modal regression.  R may have timed out.\n" +
                        "This may also be because the required \"quantreg\" package is not installed.\n"+
                        "  To install this package, run the following lines in R:\n" +
                        "source(\"http://bioconductor.org/biocLite.R\")\n" +
                        "biocLite(c(\"quantreg\"))");
            }

        }
        catch (Exception x)
        {
            ApplicationContext.errorMessage("Failed alignment: " + x.getMessage(), x);
            return null;
        }
        finally
        {
            if (pw != null)
                pw.close();
        }

        return result;
    }

    public double[] getModalRegressionCoefficients()
    {
        return modalRegressionCoefficients;
    }

    public int getNonlinearMappingPolynomialDegree()
    {
        return nonlinearMappingPolynomialDegree;
    }

    public void setNonlinearMappingPolynomialDegree(int nonlinearMappingPolynomialDegree)
    {
        this.nonlinearMappingPolynomialDegree = nonlinearMappingPolynomialDegree;
    }
}


text:
//Returns true if all visible input dropdown boxes in divID have a selected value
//divID = the div element controlling the dropdown boxes; ID ONLY (no css selector)
function validateAllVisibleDropDownsHaveSelection(divID) {
    try {
        blAllHaveValue = true;
        //$("#" + divID + " .cboInput").each(function (index, element) {
        $("#" + divID).find(".cboinput").each(function (index, element) {
            ctlID = getCntlIndex($(this).attr('id'));
            if ($(this).is(":visible") && element.value == "") {
                {
                    giveErrorMessage("#lblError_" + ctlID, "Selection Required.", "#cbo_" + ctlID, "red", "black");
                    blAllHaveValue = false;
                }
            }
        });
        return blAllHaveValue;
    } catch (err) {
        alert("validateAllVisibleDropDownsHaveSelection: " + err.message);
    }
}

//Performs from validation.; Returns true if OK to submit form
//btnID; the ID of the button that was pressed
//divID: the ID of the div containing the controls you want to validate
function validateForm(btnID, divID) {
    try {
        formValid = true;
        switch (btnID) {
            case "btnOTSNewIn":
                //Ensure user selected a part type, even if it's undefined.
                formValid = validateAllVisibleDropDownsHaveSelection("divOTSNewIn")
                //MPN is required
                if ($("#txt_18").val() == "") {
                    formValid = false;
                    giveErrorMessage("#lblError_18", "You must provide a Vendor Part Number.", "#txt_18", "red", "black");
                }
                //...as is a vendor is required
                if ($("#txt_19").val() == "") {
                    formValid = false;
                    giveErrorMessage("#lblError_19", "You must provide a Vendor Name.", "#txt_19", "red", "black");
                }
                break;
            default:
                break;
        }
        return formValid;
    } catch (err) {
        alert("validateForm: " + err.message);
    }

}

function GetNewOTSPN() {
    try {
        //Validate
        if (!validateForm($(this).attr('id'), $(this).attr('id').replace("btn", "div"))) {
            return "";
        }
        //alert("passed validation");
        //encode the data in divOTSNewIn
        data = synthesizeData("#divOTSNewIn");
        //alert(data);
        var obj = new Object();
        obj.input = data;
        var strData = JSON.stringify(obj);
        //make an AJAX Call
        $.ajax({
            type: "POST",
            url: "OTSPN.aspx/getNewOTSPN",
            data: strData,
            contentType: "application/json; charset utf-8",
            dataType: "json",
            success: function (msg) {
                //The result goes in...
                $("#divOTSNewOut").html(msg.d);
            },
            error: function (xhr, textStatus, errorThrown) {
                alert("Error Thrown: " + errorThrown + "\nStatus: " + textStatus + "\nResponse: " + xhr.responseText);
            }
        }) //ajax
    } catch (err) {
        alert(err.message);
    }
}


text:
class Configuration
  def self.get(key)
    Figaro.env.send(key)
  end
end


text:
package com.jetbrains.python.console;

import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.ui.EditorTextField;
import com.intellij.util.ui.UIUtil;
import com.jetbrains.python.PythonFileType;
import com.jetbrains.python.psi.impl.PyExpressionCodeFragmentImpl;
import com.jetbrains.python.run.AbstractPyCommonOptionsForm;
import com.jetbrains.python.run.AbstractPythonRunConfiguration;
import com.jetbrains.python.run.PyCommonOptionsFormData;
import com.jetbrains.python.run.PyCommonOptionsFormFactory;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.List;

/**
 * @author traff
 */
public class PyConsoleSpecificOptionsPanel {
  private final Project myProject;
  private JPanel myWholePanel;
  private JPanel myStartingScriptPanel;
  private JPanel myInterpreterPanel;
  private PyConsoleOptions.PyConsoleSettings myConsoleSettings;
  private EditorTextField myEditorTextField;
  private AbstractPyCommonOptionsForm myCommonOptionsForm;

  public PyConsoleSpecificOptionsPanel(Project project) {
    myProject = project;
  }

  public JPanel createPanel(final PyConsoleOptions.PyConsoleSettings optionsProvider) {
    myInterpreterPanel.setLayout(new BorderLayout());
    myCommonOptionsForm = PyCommonOptionsFormFactory.getInstance().createForm(createCommonOptionsFormData());
    myCommonOptionsForm.subscribe();

    myInterpreterPanel.add(myCommonOptionsForm.getMainPanel(),
                           BorderLayout.CENTER);

    configureStartingScriptPanel(optionsProvider);

    return myWholePanel;
  }

  public void apply() {
    myConsoleSettings.myCustomStartScript = myEditorTextField.getText();
    myConsoleSettings.apply(myCommonOptionsForm);
  }

  public boolean isModified() {
    return !myEditorTextField.getText().equals(myConsoleSettings.myCustomStartScript) || myConsoleSettings.isModified(myCommonOptionsForm);
  }

  public void reset() {
    UIUtil.invokeLaterIfNeeded(() -> myEditorTextField.setText(myConsoleSettings.myCustomStartScript));

    myConsoleSettings.reset(myProject, myCommonOptionsForm);
  }

  private PyCommonOptionsFormData createCommonOptionsFormData() {
    return new PyCommonOptionsFormData() {
      @Override
      public Project getProject() {
        return myProject;
      }

      @Override
      public List<Module> getValidModules() {
        return AbstractPythonRunConfiguration.getValidModules(myProject);
      }

      @Override
      public boolean showConfigureInterpretersLink() {
        return true;
      }
    };
  }

  private void configureStartingScriptPanel(final PyConsoleOptions.PyConsoleSettings optionsProvider) {
    myEditorTextField =
      new EditorTextField(createDocument(myProject, optionsProvider.myCustomStartScript), myProject, PythonFileType.INSTANCE) {
        @Override
        protected EditorEx createEditor() {
          final EditorEx editor = super.createEditor();
          editor.setVerticalScrollbarVisible(true);
          return editor;
        }

        @Override
        protected boolean isOneLineMode() {
          return false;
        }
      };
    myStartingScriptPanel.setLayout(new BorderLayout());
    myStartingScriptPanel.add(myEditorTextField, BorderLayout.CENTER);
    myConsoleSettings = optionsProvider;
  }

  @NotNull
  public static Document createDocument(@NotNull final Project project,
                                        @NotNull String text) {
    text = text.trim();
    final PyExpressionCodeFragmentImpl fragment = new PyExpressionCodeFragmentImpl(project, "start_script.py", text, true);

    return PsiDocumentManager.getInstance(project).getDocument(fragment);
  }
}


text:
import SlackLoginPage from "../Pages/SlackLoginPage";

export default [
  {
    path: "/slack/login",
    name: "login",
    exact: true,
    component: SlackLoginPage,
  },
];


text:
"""
Implementation of hooks and APIs for outputting log messages.
"""

from __future__ import unicode_literals, absolute_import

import sys
import json as pyjson

from characteristic import attributes
from six import text_type as unicode, PY3
if PY3:
    from . import _py3json as fast_json
    slow_json = fast_json
else:
    try:
        # ujson has some issues, in particular it is far too lenient on bad
        # inputs... but on the other hand it's much faster than built-in
        # json module on CPython. So we use it until we come up with some
        # better. We import built-in module for use by the validation code
        # path, since we want to validate messages encode in all JSON
        # encoders.
        import ujson as fast_json
        import json as slow_json
    except ImportError:
        import json as fast_json
        slow_json = fast_json

from zope.interface import Interface, implementer

from ._traceback import writeTraceback, TRACEBACK_MESSAGE
from ._message import Message
from ._util import saferepr, safeunicode

class _DestinationsSendError(Exception):
    """
    An error occured sending to one or more destinations.

    @ivar errors: A list of tuples output from C{sys.exc_info()}.
    """
    def __init__(self, errors):
        self.errors = errors
        Exception.__init__(self)

class Destinations(object):
    """
    Manage a list of destinations for message dictionaries.

    The global instance of this class is where L{Logger} instances will
    send written messages.
    """
    def __init__(self):
        self._destinations = []
        self._globalFields = {}

    def addGlobalFields(self, **fields):
        """
        Add fields that will be included in all messages sent through this
        destination.

        @param fields: Keyword arguments mapping field names to values.
        """
        self._globalFields.update(fields)

    def send(self, message):
        """
        Deliver a message to all destinations.

        The passed in message might be mutated.

        @param message: A message dictionary that can be serialized to JSON.
        @type message: L{dict}
        """
        message.update(self._globalFields)
        errors = []
        for dest in self._destinations:
            try:
                dest(message)
            except:
                errors.append(sys.exc_info())
        if errors:
            raise _DestinationsSendError(errors)

    def add(self, destination):
        """
        Add a new destination.

        A destination should never ever throw an exception. Seriously.
        A destination should not mutate the dictionary it is given.

        @param destination: A callable that takes message dictionaries,
        """
        self._destinations.append(destination)

    def remove(self, destination):
        """
        Remove an existing destination.

        @param destination: A destination previously added with C{self.add}.

        @raises ValueError: If the destination is unknown.
        """
        self._destinations.remove(destination)

class ILogger(Interface):
    """
    Write out message dictionaries to some destination.
    """
    def write(dictionary, serializer=None):
        """
        Write a dictionary to the appropriate destination.

        @param serializer: Either C{None}, or a
            L{eliot._validation._MessageSerializer} which can be used to validate
            this message.

        @param dictionary: The message to write out. The given dictionary
             will not be mutated.
        @type dictionary: C{dict}
        """

@implementer(ILogger)
class Logger(object):
    """
    Write out messages to the globally configured destination(s).

    You will typically want to create one of these for every chunk of code
    whose messages you want to unit test in isolation, e.g. a class. The tests
    can then replace a specific L{Logger} with a L{MemoryLogger}.
    """
    _destinations = Destinations()

    def _safeUnicodeDictionary(self, dictionary):
        """
        Serialize a dictionary to a unicode string no matter what it contains.

        The resulting dictionary will loosely follow Python syntax but it is
        not expected to actually be a lossless encoding in all cases.

        @param dictionary: A L{dict} to serialize.

        @return: A L{unicode} string representing the input dictionary as
            faithfully as can be done without putting in too much effort.
        """
        try:
            return unicode(
                dict((saferepr(key), saferepr(value)) for (key, value)
                     in dictionary.items()))
        except:
            return saferepr(dictionary)

    def write(self, dictionary, serializer=None):
        """
        Serialize the dictionary, and write it to C{self._destinations}.
        """
        dictionary = dictionary.copy()
        try:
            if serializer is not None:
                serializer.serialize(dictionary)
        except:
            writeTraceback(self)
            msg = Message({"message_type": "eliot:serialization_failure",
                           "message": self._safeUnicodeDictionary(dictionary)})
            msg.write(self)
            return

        try:
            self._destinations.send(dictionary)
        except _DestinationsSendError as e:
            for (exc_type, exception, exc_traceback) in e.errors:
                try:
                    # Can't use same code path as serialization errors because
                    # if destination continues to error out we will get
                    # infinite recursion. So instead we have to manually
                    # construct a message.
                    msg = Message({
                        "message_type": "eliot:destination_failure",
                        "reason": safeunicode(exception),
                        "exception":
                        exc_type.__module__ + "." + exc_type.__name__,
                        "message": self._safeUnicodeDictionary(dictionary)})
                    self._destinations.send(dict(msg._freeze()))
                except:
                    # Nothing we can do here, raising exception to caller will
                    # break business logic, better to have that continue to
                    # work even if logging isn't.
                    pass

class UnflushedTracebacks(Exception):
    """
    The L{MemoryLogger} had some tracebacks logged which were not flushed.

    This means either your code has a bug and logged an unexpected traceback. If
    you expected the traceback then you will need to flush it using
    L{MemoryLogger.flushTracebacks}.
    """

@implementer(ILogger)
class MemoryLogger(object):
    """
    Store written messages in memory.

    When unit testing you don't want to create this directly but rather use
    the L{eliot.testing.validateLogging} decorator on a test method, which
    will provide additional testing integration.

    @ivar messages: A C{list} of the dictionaries passed to
        L{MemoryLogger.write}. Do not mutate this list.

    @ivar serializers: A C{list} of the serializers passed to
        L{MemoryLogger.write}, each corresponding to a message
        L{MemoryLogger.messages}. Do not mutate this list.

    @ivar tracebackMessages: A C{list} of messages written to this logger for
        tracebacks using L{eliot.writeTraceback} or L{eliot.writeFailure}. Do
        not mutate this list.
    """
    def __init__(self):
        self.reset()

    def flushTracebacks(self, exceptionType):
        """
        Flush all logged tracebacks whose exception is of the given type.

        This means they are expected tracebacks and should not cause the test to
        fail.

        @param exceptionType: A subclass of L{Exception}.

        @return: C{list} of flushed messages.
        """
        result = []
        remaining = []
        for message in self.tracebackMessages:
            if isinstance(message["reason"], exceptionType):
                result.append(message)
            else:
                remaining.append(message)
        self.tracebackMessages = remaining
        return result

    # PEP 8 variant:
    flush_tracebacks = flushTracebacks

    def write(self, dictionary, serializer=None):
        """
        Add the dictionary to list of messages.
        """
        self.messages.append(dictionary)
        self.serializers.append(serializer)
        if serializer is TRACEBACK_MESSAGE._serializer:
            self.tracebackMessages.append(dictionary)

    def validate(self):
        """
        Validate all written messages.

        Does minimal validation of types, and for messages with corresponding
        serializers use those to do additional validation.

        @raises TypeError: If a field name is not unicode.

        @raises eliot.ValidationError: If serializer was given and validation
            failed.
        """
        for dictionary, serializer in zip(self.messages, self.serializers):
            if serializer is not None:
                serializer.validate(dictionary)
            for key in dictionary:
                if not isinstance(key, unicode):
                    if isinstance(key, bytes):
                        key.decode("utf-8")
                    else:
                        raise TypeError(dictionary, "%r is not unicode" % (key,))
            if serializer is not None:
                serializer.serialize(dictionary)

            # Make sure we can be encoded with different JSON encoder, since
            # ujson has different behavior in some cases:
            fast_json.dumps(dictionary)
            slow_json.dumps(dictionary)

    def serialize(self):
        """
        Serialize all written messages.

        This is the Field-based serialization, not JSON.

        @return: A C{list} of C{dict}, the serialized messages.
        """
        result = []
        for dictionary, serializer in zip(self.messages, self.serializers):
            dictionary = dictionary.copy()
            serializer.serialize(dictionary)
            result.append(dictionary)
        return result

    def reset(self):
        """
        Clear all logged messages.

        Any logged tracebacks will also be cleared, and will therefore not cause
        a test failure.

        This is useful to ensure a logger is in a known state before testing
        logging of a specific code path.
        """
        self.messages = []
        self.serializers = []
        self.tracebackMessages = []

@attributes(["file"])
class FileDestination(object):
    """
    Callable that writes JSON messages to a file.

    On Python 3 the file may support either C{bytes} or C{unicode}.  On
    Python 2 only C{bytes} are supported since that is what all files expect
    in practice.

    @ivar file: The file to which messages will be written.

    @ivar _dumps: Function that serializes an object to JSON.

    @ivar _linebreak: C{"\n"} as either bytes or unicode.
    """

    def __init__(self):
        unicodeFile = False
        if PY3:
            try:
                self.file.write(b"")
            except TypeError:
                unicodeFile = True

        if unicodeFile:
            # On Python 3 native json module outputs unicode:
            self._dumps = pyjson.dumps
            self._linebreak = u"\n"
        else:
            self._dumps = fast_json.dumps
            self._linebreak = b"\n"

    def __call__(self, message):
        """
        @param message: A message dictionary.
        """
        self.file.write(self._dumps(message) + self._linebreak)
        self.file.flush()

def to_file(output_file):
    """
    Add a destination that writes a JSON message per line to the given file.

    @param output_file: A file-like object.
    """
    Logger._destinations.add(FileDestination(file=output_file))

# The default Logger, used when none is specified:
_DEFAULT_LOGGER = Logger()


text:
{% extends "kolibri/base.html" %}
{% load webpack_tags %}

{% block content %}
  {% webpack_asset 'kolibri.plugins.facility.app' %}
{% endblock %}


text:
[![](https://vsmarketplacebadge.apphb.com/version/bierner.markdown-yaml-preamble.svg)](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-yaml-premable)

Makes yaml front matter render as a table in VS Code's built-in markdown preview:

![](https://raw.githubusercontent.com/mjbvz/vscode-markdown-yaml-preamble/master/docs/example.png)

# Features
- Adds support for rendering yaml front matter as a table in VS Code's built-in markdown preview.


text:
package org.apache.metron.profiler.clock;

import java.io.Serializable;

/**
 * A clock that uses the system clock to provide wall clock time.
 */
public class WallClock implements Clock, Serializable {

  @Override
  public long currentTimeMillis() {
    return System.currentTimeMillis();
  }
}


text:
package tests

import (
	"fmt"
	"os"
)

func tempfile_generate() func() string {
	counter := 0
	return func() string {
		counter++
		return fmt.Sprintf("/tmp/gounittest.%d-%d",
			os.Getpid(), counter)
	}
}

var genname = tempfile_generate()

// Return a filename string in the form of
// /tmp/gounittest.<Process Id>-<Counter>
func Tempfile() string {
	return genname()
}

// We could use Fallocate, but some test CI systems
// do not support it, like Travis-ci.org.
func CreateFile(filename string, size int64) error {

	buf := make([]byte, size)

	// Create the file store some data
	fp, err := os.Create(filename)
	if err != nil {
		return err
	}

	// Write the buffer
	_, err = fp.Write(buf)

	// Cleanup
	fp.Close()

	return err
}


text:
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

d = generate_distutils_setup(
    packages = ['vigir_ltl_synthesizer'],
    package_dir = {'': 'src'}
)

setup(**d)


text:
var mplsIsAwesome04 = function(){
	var currentCardID = 0,
		cardListHeight,
		cardListContainerHeight,
		cardCount = cards.data.length - 1,
		headerHeight = $('header').height();

	$(document).ready(function(){
		var $cardList = $('#cardList'),
			$mainContent = $('#mainContent');

		for (x in cards.data){
			$cardList.append(constructMenuItem(x));
			$mainContent.append(constructCard(x));
		}

		bindEvents();

		$('.cardSelectItem').eq(0).addClass('active');
	});

	function highlightCurrentCard(){
		$('.cardSelectItem').removeClass('active').eq(currentCardID).addClass('active');
	};

	function bindEvents(callback){
		$(window).scroll(function(){
			var scrollPos = $(this).scrollTop(),
				prevCardID = currentCardID;

			$('.card').each(function(){
				var $this = $(this);
				if ($this.offset().top - 100 > scrollPos) return false;

				currentCardID = $this.index();
			});

			highlightCurrentCard();

			if (prevCardID != currentCardID){
				$('#cardListContainer').stop().animate({
					scrollTop: (cardListHeight - cardListContainerHeight) * (currentCardID / cardCount)
				});
			}
		}).keyup(function(e){
			if (e.which == 37) $('#upArrow').click();
			if (e.which == 39) $('#downArrow').click();
			if (e.which == 77) $('#toggleCardList').click();
		}).resize(function(){
			cardListHeight = $('#cardList').height();
			cardListContainerHeight = $('#cardListContainer').height();

			if ($('html').hasClass('no-touch')) {
				$('.cardImage').height($(this).height() - headerHeight);
			} else {
				$('.cardImage').height('auto');
			}
		}).resize();

		$('#cardList').on('click', '.cardSelectItem', function(){
			var $this = $(this);
			currentCardID = $this.index();

			$('body').stop().animate({
				scrollTop: $('.card').eq(currentCardID).position().top
			});
		});

		$('header').on('click', function(){
			$(this).toggleClass('active');
		});

		$('#upArrow').on('click', function(){
			if (--currentCardID < 0) currentCardID = cardCount;

			$('.cardSelectItem').eq(currentCardID).click();
		});

		$('#downArrow').on('click', function(){
			if (++currentCardID > cardCount) currentCardID = 0;

			$('.cardSelectItem').eq(currentCardID).click();
		});

		$('#toggleCardList').on('click', function(){
			$('body').toggleClass('active');
		});
		// callback
		if (callback) callback();
	}

	function constructMenuItem(cardNum){
		return '
' + cards.data[cardNum].title + '
'
	}
	function constructCard(cardNum){
		return '

'+cards.data[cardNum].title+'

'+cards.data[cardNum].copy+'

';
	}
}();


text:
let original: (fn: FrameRequestCallback) => number;

let requesters: any[] = [];

function fakeRaf(fn: FrameRequestCallback): number {
  requesters.push(fn);
  return requesters.length;
}

function use() {
  original = window.requestAnimationFrame;
  window.requestAnimationFrame = fakeRaf;
}

function restore() {
  setTimeout(() => {
    window.requestAnimationFrame = original;
  }, 2000);
}

function step() {
  let cur = requesters;
  requesters = [];
  cur.forEach(function(f) { return f(16); });
}

export default {
  use,
  restore,
  step,
};


text:
//
//  TriggerTerrainBlock.cpp
//  Created by Matt Kaufmann on 02/16/14.
//

#include "ExampleGame/Components/Grid/GameGrid.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Triggers/TriggerTerrainBlock.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "ExampleGame/Messages/Declarations.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/MessageHub/MessageHub.h"

TriggerTerrainBlock::TriggerTerrainBlock() : Triggerable() {
	this->init();
}

TriggerTerrainBlock::TriggerTerrainBlock(Object* object_) : Triggerable(object_) {
	this->init();
}

TriggerTerrainBlock::~TriggerTerrainBlock() {
	this->destroy();
}

void TriggerTerrainBlock::init() {
	this->changeVisibility  = true;
	this->changeWalkability = true;
	this->isPassable        = false;
}

void TriggerTerrainBlock::destroy() {

}

void TriggerTerrainBlock::SetTriggerType(std::string typeStr) {
	Triggerable::SetTriggerType(typeStr);
}

void TriggerTerrainBlock::HandleMessage(MessageChunk messageChunk) {
	Triggerable::HandleMessage(messageChunk);
}

void TriggerTerrainBlock::SubscribeToMySwitch() {
	Triggerable::SubscribeToMySwitch();
}

void TriggerTerrainBlock::SubscribeToParentSwitch() {
	Triggerable::SubscribeToParentSwitch();
}

void TriggerTerrainBlock::onSwitchToggled(bool /*switchState*/) {
	this->startTerrainChange();
	this->isPassable = !this->isPassable;
}

void TriggerTerrainBlock::onSwitchActivated() {

}

void TriggerTerrainBlock::onSwitchDeactivated() {

}

void TriggerTerrainBlock::startTerrainChange() {
	// Get the grid zone component on this object.
	GridZone* zone = this->GetObject()->GetComponent<GridZone>();
	ASSERT(zone != nullptr, "Object %d with TriggerElevationChange component also has GridZone component", this->GetObject()->GetId());

	if (zone != nullptr) {
		int west, east, south, north;
		zone->GetZoneBounds(west, east, south, north);

		GameGrid* grid = SINGLETONS->GetGridManager()->GetGrid();

		int elevation = grid->GetElevationFromWorldY(this->GetObject()->GetComponent<Transform>()->GetPositionWorld().y);
		for (int x = west; x <= east; ++x) {
			for (int z = south; z <= north; ++z) {
				if (this->changeWalkability) {
					grid->SetCellPassableAtElevation(x, z, elevation, this->isPassable);
				}
				if (this->changeVisibility) {
					grid->SetCellVisibleAtElevation(x, z, elevation, this->isPassable);
				}
			}
		}
	}

	// Navigators need to update their pathfinding
	MessageChunk gridNavMessage = ENGINE->GetMessageHub()->GetOneFreeMessage();
	gridNavMessage->SetMessageType(MESSAGE_TYPE_GRID_NAVIGATION_REFRESH);
	ENGINE->GetMessageHub()->SendMulticastMessage(gridNavMessage, SINGLETONS->GetGridManagerObject()->GetId());
}


text:
template <class T, class Compare = std::less<T>>
class ConditionallyBoundedArray {
protected:
	T* _store;
	size_t _size;
	size_t _boundSize;
	Compare _compare;
	bool _builded;

public:
	typedef T* iterator;
	typedef const T* const_iterator;

	explicit ConditionallyBoundedArray(size_t maxSize, const Compare& compare = Compare())
		: _store(nullptr), _size(0), _boundSize(maxSize), _compare(compare), _builded(false) {
		if (_boundSize)
			_store = new T[_boundSize];
	}

	~ConditionallyBoundedArray() {
		if (_boundSize && _store != nullptr)
			delete[] _store;
	}

	void heapify(size_t root) {
		while (root < _size) {
			size_t max = root, left = 2 * root + 1;
			if (left < _size) {
				if (_compare(_store[max], _store[left]))
					max = left;
				if (left + 1 < _size && _compare(_store[max], _store[left + 1]))
					max = left + 1;
			}
			if (max == root)
				break;
			std::swap(_store[root], _store[max]);
			root = max;
		}
	}

	void push(const T& elem) {
		if (_size < _boundSize) {
			_store[_size++] = elem;
		}
		else {
			if (!_builded) {
				for (size_t i = _boundSize / 2; i; i--)
					heapify(i - 1);
				_builded = true;
			}
			if (_compare(elem, _store[0])) {
				_store[0] = elem;
				heapify(0);
			}
		}
	}

	T& operator [](size_t n) { return _store[n]; }
	const T& operator[](size_t n) const { return _store[n]; }

	iterator begin() { return _store; }
	iterator end() { return _store + _size; }
	const_iterator begin() const { return _store; }
	const_iterator end() const { return _store + _size; }
	iterator rbegin() { return _store + _size; }
	iterator rend() { return _store; }
	const_iterator rbegin() const { return _store + _size; }
	const_iterator rend() const { return _store; }
	T& front() { return _store[0]; }
	T& back() { return _store[_size - 1]; }
	const T& front() const { return _store[0]; }
	const T& back() const { return _store[_size - 1]; }
	size_t size() const { return _size; }
	bool empty() const { return _size == 0; }
	void clear() { _size = 0; }
};


text:
package com.citrus.maravilhaspe.wonder.business;

import com.citrus.maravilhaspe.wonder.WonderFactory;
import com.citrus.maravilhaspe.wonder.domain.Wonder;
import com.citrus.maravilhaspe.wonder.persistence.IWonderDAO;

import java.util.ArrayList;

/**
 * Created by Erick on 30/04/2015.
 */
public class WonderServices implements IWonderServices {
    @Override
    public ArrayList<Wonder> getAllWonders(String type_wonder) {
        IWonderDAO dao = WonderFactory.getInstance().createWonderDAO();

        if(type_wonder == null) {
            return dao.getAll();
        }else{
            return dao.getByType(type_wonder);
        }
    }

    @Override
    public Wonder getWonderById(int id) {
        IWonderDAO dao = WonderFactory.getInstance().createWonderDAO();
        return dao.getById(id);
    }
}