async (tx) => {
        await bazStore.add(hash, 'VALUE', tx)
        const keys = await bazStore.getAllKeys(tx)
        expect(keys.length).toBe(1)
        expect(keys[0]?.equals(hash)).toBe(true)
      }


async () => {
      await db.open()
      await db.metaStore.clear()

      await db.transaction([db.metaStore], 'readwrite', async (tx) => {
        // a, db=1000, tx=undefined
        await db.metaStore.put('a', 1000)
        let values = await db.metaStore.getAllValues(tx)
        expect(values).toHaveLength(1)
        expect(values).toContain(1000)

        // a, db=1000, tx=1001
        await db.metaStore.put('a', 1001, tx)
        values = await db.metaStore.getAllValues(tx)
        expect(values).toHaveLength(1)
        expect(values).toContain(1001)

        // b, db=undefined, tx=1002
        await db.metaStore.put('b', 1002, tx)
        values = await db.metaStore.getAllValues(tx)
        expect(values).toHaveLength(2)
        expect(values).toContain(1001)
        expect(values).toContain(1002)
      })
    }


async (tx) => {
        // a, db=1000, tx=undefined
        await db.metaStore.put('a', 1000)
        let values = await db.metaStore.getAllValues(tx)
        expect(values).toHaveLength(1)
        expect(values).toContain(1000)

        // a, db=1000, tx=1001
        await db.metaStore.put('a', 1001, tx)
        values = await db.metaStore.getAllValues(tx)
        expect(values).toHaveLength(1)
        expect(values).toContain(1001)

        // b, db=undefined, tx=1002
        await db.metaStore.put('b', 1002, tx)
        values = await db.metaStore.getAllValues(tx)
        expect(values).toHaveLength(2)
        expect(values).toContain(1001)
        expect(values).toContain(1002)
      }


async () => {
      await db.open()
      await db.metaStore.clear()
      await db.metaStore.put('a', 1)

      await db.transaction([db.metaStore], 'readwrite', async (tx) => {
        expect(await db.metaStore.get('a', tx)).toBe(1)

        let values = await db.metaStore.getAllValues(tx)
        expect(values).toHaveLength(1)
        expect(values).toContain(1)

        // cache has undefined and should not yield
        await db.metaStore.del('a', tx)

        values = await db.metaStore.getAllValues(tx)
        expect(values).toHaveLength(0)
      })
    }


async (tx) => {
        expect(await db.metaStore.get('a', tx)).toBe(1)

        let values = await db.metaStore.getAllValues(tx)
        expect(values).toHaveLength(1)
        expect(values).toContain(1)

        // cache has undefined and should not yield
        await db.metaStore.del('a', tx)

        values = await db.metaStore.getAllValues(tx)
        expect(values).toHaveLength(0)
      }


async () => {
      await db.open()
      await bazStore.clear()

      await bazStore.put(Buffer.alloc(100, 0xff), '1')
      expect((await bazStore.getAllKeys()).length).toBe(1)
    }


async () => {
      await db.open()
      const keyStore = testPrefixKeyStore as LevelupStore<BazSchema>
      await keyStore.clear()

      // Increment the prefix buffer by one
      expect(keyStore.prefixBuffer).toEqual(Buffer.from([92, 188, 18, 188]))
      keyStore.prefixBuffer[keyStore.prefixBuffer.length - 1]++

      // Add an entry with an empty buffer for the key
      expect(keyStore.prefixBuffer).toEqual(Buffer.from([92, 188, 18, 189]))
      await keyStore.put(Buffer.alloc(0), '1')
      expect(await keyStore.get(Buffer.alloc(0))).toEqual('1')

      // Decrement the prefix buffer
      keyStore.prefixBuffer[keyStore.prefixBuffer.length - 1]--
      expect(keyStore.prefixBuffer).toEqual(Buffer.from([92, 188, 18, 188]))

      // No keys should exist
      expect(await keyStore.getAllKeys()).toHaveLength(0)
    }


interface FooSchema extends DatabaseSchema {
  key: string
  value: FooValue
}


interface BarSchema extends DatabaseSchema {
  key: string
  value: Buffer
}


interface BazSchema extends DatabaseSchema {
  key: Buffer
  value: string
}


interface TestSchema extends DatabaseSchema {
  key: string
  value: IJsonSerializable
}


interface ArrayKeySchema extends DatabaseSchema {
  key: [string, number, boolean]
  value: boolean
}


interface KeypathSchema extends DatabaseSchema {
  key: [string, number, boolean]
  value: { a: string; b: number; c: boolean }
}


interface EmptySchema extends DatabaseSchema {
      key: string
      value: number
    }


interface NestedSchema extends DatabaseSchema {
      key: string
      value: {
        buffer: Buffer
      }
    }


type FooValue = {
  hash: string
  name: string
}


export function requireSearchRaw<T>(relativeTo: string, paths: string[]): T | null {
  const testPaths = paths
    .concat(paths.map((mapPath) => path.resolve(relativeTo, mapPath)))
    .concat(paths.map((mapPath) => path.resolve(relativeTo, 'node_modules', mapPath)));
  d('searching', testPaths, 'relative to', relativeTo);
  for (const testPath of testPaths) {
    try {
      d('testing', testPath);
      // eslint-disable-next-line global-require, import/no-dynamic-require
      return require(testPath);
    } catch (err) {
      // Ignore require-related errors
      if (err.code !== 'MODULE_NOT_FOUND' || ![undefined, testPath].includes(err.requestPath)) {
        throw err;
      }
    }
  }
  d('failed to find a module in', testPaths);
  return null;
}


(mapPath) => path.resolve(relativeTo, mapPath)


(mapPath) => path.resolve(relativeTo, 'node_modules', mapPath)


<T>(relativeTo: string, paths: string[]): T | null => {
  const result = requireSearchRaw<PossibleModule<T>>(relativeTo, paths);
  return typeof result === 'object' && result && result.default ? result.default : result as (T | null);
}


export type PossibleModule<T> = {
  default?: T;
} & T;


export interface Message {
    Version?: number;
    To: Address;
    From: Address;
    Nonce: Nonce;
    Value: BigNumber;
    GasLimit: number;
    GasFeeCap: BigNumber;
    GasPremium: BigNumber;
    Method: number;
    Params: string;
}


export interface Signature {
    Data: string;
    Type: number;
}


export interface SignedMessage {
    Message: Message;
    Signature: Signature;
}


export enum ProtocolIndicator {
    ID,
    SECP256K1,
    ACTOR,
    BLS,
}


export enum CodeCID {
    PaymentChannel = "fil/4/paymentchannel",
    Multisig = "fil/4/multisig",
}


export enum INIT_ACTOR {
    mainnet = "f01",
    testnet = "t01",
}


export enum InitMethod {
    None,
    Constructor,
    Exec,
}


export enum PaymentChannelMethod {
    None,
    Construtor,
    UpdateChannelState,
    Settle,
    Collect,
}


export enum MultisigMethod {
    None,
    Constructor,
    Propose,
    Approve,
    Cancel,
    AddSigner,
    RemoveSigner,
    SwapSigner,
    ChangeNumApprovalsThreshhold,
}


export type PrivateKey = string;


export type TokenAmount = BigNumber;


export type Nonce = number;


export type MsgParams = string;


export type CID =
    | string
    | {
          "/": string;
      };


export type MessageReceipt = {
    ExitCode: number;
    Return: any;
    GasUsed: number;
};


export type MsgLookup = {
    Message: CID;
    Receipt: MessageReceipt;
    ReturnDec: any;
    TipSet: CID[];
    Height: number;
};


export type MessageResponse = CID | MsgLookup;


export type Network = "mainnet" | "testnet";


export type SignedVoucherBase64 = string;


export type VoucherBase64 = string;


export type HashedSecret = string;


export type Voucher = string;


export type FilecoinNetwork = "f" | "t";


state => ({
  inferencer: Constants.useBackend
    ? new AchievementInferencer(state.achievement.achievements, state.achievement.goals)
    : new AchievementInferencer(mockAchievements, mockGoals)
})


(dispatch: Dispatch) =>
  bindActionCreators(
    {
      handleEditAchievement: editAchievement,
      handleEditGoal: editGoal,
      handleGetAchievements: getAchievements,
      handleGetOwnGoals: getOwnGoals,
      handleRemoveAchievement: removeAchievement,
      handleRemoveGoal: removeGoal,
      handleSaveAchievements: saveAchievements,
      handleSaveGoals: saveGoals
    },
    dispatch
  )


(map, jsonContentBlock) => {
      map[jsonContentBlock.content_path] = jsonContentBlock;
      return map;
    }


///<reference path="../models/content_block.ts"/>
///<reference path="../models/ajax_content_blocks.ts"/>
///<reference path="../models/ajax_content_block.ts"/>
///<reference path="../models/renuo_upload_credentials.ts"/>
///<reference path="../models/ajax_renuo_upload_credentials.ts"/>
class DataConverter {
  convertJson(originalContentBlock:ContentBlock, cb:AjaxContentBlock):ContentBlock {
    return new ContentBlock(cb.content, cb.content_path, cb.api_key, originalContentBlock.apiHost,
      cb.created_at, cb.updated_at, originalContentBlock.defaultContent, cb.version);
  }

  extractObjectFromHash(originalContentBlock:ContentBlock, rawAjaxArray:AjaxContentBlocksHash):ContentBlock {
    const rawData = rawAjaxArray[originalContentBlock.contentPath];
    return rawData ? this.convertJson(originalContentBlock, rawData) : originalContentBlock;
  }

  convertJsonObjectToHash(rawJsonObject:AjaxContentBlocks):AjaxContentBlocksHash {
    const hash:AjaxContentBlocksHash = {};

    return rawJsonObject.content_blocks.reduce((map, jsonContentBlock) => {
      map[jsonContentBlock.content_path] = jsonContentBlock;
      return map;
    }, hash);
  }

  convertJsonObjectToCredentials(credentials:AjaxRenuoUploadCredentials):RenuoUploadCredentials {
    const cred = credentials.renuo_upload_credentials;
    return new RenuoUploadCredentials(cred.api_key, cred.signing_url);
  }
}


convertJson(originalContentBlock:ContentBlock, cb:AjaxContentBlock):ContentBlock {
    return new ContentBlock(cb.content, cb.content_path, cb.api_key, originalContentBlock.apiHost,
      cb.created_at, cb.updated_at, originalContentBlock.defaultContent, cb.version);
  }


extractObjectFromHash(originalContentBlock:ContentBlock, rawAjaxArray:AjaxContentBlocksHash):ContentBlock {
    const rawData = rawAjaxArray[originalContentBlock.contentPath];
    return rawData ? this.convertJson(originalContentBlock, rawData) : originalContentBlock;
  }


convertJsonObjectToHash(rawJsonObject:AjaxContentBlocks):AjaxContentBlocksHash {
    const hash:AjaxContentBlocksHash = {};

    return rawJsonObject.content_blocks.reduce((map, jsonContentBlock) => {
      map[jsonContentBlock.content_path] = jsonContentBlock;
      return map;
    }, hash);
  }


convertJsonObjectToCredentials(credentials:AjaxRenuoUploadCredentials):RenuoUploadCredentials {
    const cred = credentials.renuo_upload_credentials;
    return new RenuoUploadCredentials(cred.api_key, cred.signing_url);
  }


(value, key) => {
			const webviewSelector = `.show-file-icons .webview-${key}-name-file-icon::before`;
			if (URI.isUri(value)) {
				cssRules.push(`${webviewSelector} { content: ""; background-image: url(${value.toString()}); }`);
			} else {
				cssRules.push(`.vs ${webviewSelector} { content: ""; background-image: url(${value.light.toString()}); }`);
				cssRules.push(`.vs-dark ${webviewSelector} { content: ""; background-image: url(${value.dark.toString()}); }`);
			}
		}


link => {
			if (this._events && this._events.onDidClickLink) {
				this._events.onDidClickLink(link, this._options);
			}
		}


message => {
			if (this._events && this._events.onMessage) {
				this._events.onMessage(message);
			}
		}


message => {
			this._scrollYPercentage = message.scrollYPercentage;
		}


newState => {
			this._state.state = newState;
		}


export class RevivedWebviewEditorInput extends WebviewEditorInput {
	private _revived: boolean = false;

	constructor(
		viewType: string,
		id: number | undefined,
		name: string,
		options: WebviewInputOptions,
		state: any,
		events: WebviewEvents,
		extension: undefined | {
			readonly location: URI;
			readonly id: ExtensionIdentifier
		},
		public readonly reviver: (input: WebviewEditorInput) => Promise<void>,
		@IWorkbenchLayoutService partService: IWorkbenchLayoutService,
	) {
		super(viewType, id, name, options, state, events, extension, partService);
	}

	public async resolve(): Promise<IEditorModel> {
		if (!this._revived) {
			this._revived = true;
			await this.reviver(this);
		}
		return super.resolve();
	}
}


private static updateStyleElement(
		id: number,
		iconPath: { light: URI, dark: URI } | undefined
	) {
		if (!this._styleElement) {
			this._styleElement = dom.createStyleSheet();
			this._styleElement.className = 'webview-icons';
		}

		if (!iconPath) {
			this._icons.delete(id);
		} else {
			this._icons.set(id, iconPath);
		}

		const cssRules: string[] = [];
		this._icons.forEach((value, key) => {
			const webviewSelector = `.show-file-icons .webview-${key}-name-file-icon::before`;
			if (URI.isUri(value)) {
				cssRules.push(`${webviewSelector} { content: ""; background-image: url(${value.toString()}); }`);
			} else {
				cssRules.push(`.vs ${webviewSelector} { content: ""; background-image: url(${value.light.toString()}); }`);
				cssRules.push(`.vs-dark ${webviewSelector} { content: ""; background-image: url(${value.dark.toString()}); }`);
			}
		});
		this._styleElement.innerHTML = cssRules.join('\n');
	}


public getTypeId(): string {
		return WebviewEditorInput.typeId;
	}


public getId(): number {
		return this._id;
	}


public dispose() {
		this.disposeWebview();

		if (this._container) {
			this._container.remove();
			this._container = undefined;
		}

		if (this._events && this._events.onDispose) {
			this._events.onDispose();
		}
		this._events = undefined;

		this._webview = undefined;
		super.dispose();
	}


public getResource(): URI {
		return URI.from({
			scheme: 'webview-panel',
			path: `webview-panel/webview-${this._id}`
		});
	}


public getName(): string {
		return this._name;
	}


public getTitle() {
		return this.getName();
	}


public getDescription() {
		return null;
	}


public setName(value: string): void {
		this._name = value;
		this._onDidChangeLabel.fire();
	}


public matches(other: IEditorInput): boolean {
		return other === this || (other instanceof WebviewEditorInput && other._id === this._id);
	}


public setOptions(value: WebviewOptions) {
		this._options = {
			...this._options,
			...value
		};

		if (this._webview) {
			this._webview.options = {
				allowScripts: this._options.enableScripts,
				localResourceRoots: this._options.localResourceRoots,
				portMappings: this._options.portMapping,
			};
		}
	}


public resolve(): Promise<IEditorModel> {
		return Promise.resolve(new EditorModel());
	}


public supportsSplitEditor() {
		return false;
	}


public claimWebview(owner: any) {
		this._webviewOwner = owner;
	}


public releaseWebview(owner: any) {
		if (this._webviewOwner === owner) {
			this._webviewOwner = undefined;
			if (this._options.retainContextWhenHidden && this._container) {
				this._container.style.visibility = 'hidden';
			} else {
				this.disposeWebview();
			}
		}
	}


public disposeWebview() {
		// The input owns the webview and its parent
		if (this._webview) {
			this._webview.dispose();
			this._webview = undefined;
		}

		this._webviewDisposables = dispose(this._webviewDisposables);

		this._webviewOwner = undefined;

		if (this._container) {
			this._container.style.visibility = 'hidden';
		}

		this._currentWebviewHtml = '';
	}


public updateGroup(group: GroupIdentifier): void {
		this._group = group;
	}


public async resolve(): Promise<IEditorModel> {
		if (!this._revived) {
			this._revived = true;
			await this.reviver(this);
		}
		return super.resolve();
	}


/**
     * Gets the sprite type
     */
//% blockHidden=1 shim=ENUM_GET
//% blockId=spritetype block="$kind" enumInitialMembers="Player,Projectile,Food,Enemy"
//% enumName=SpriteKind enumMemberName=kind enumPromptHint="e.g. Coin, Fireball, Asteroid..."
export function _spriteType(kind: number): number {
        return kind;
    }


/**
     * Run code when a certain kind of sprite is created
     * @param kind
     * @param sprite
     */
//% group="Lifecycle" draggableParameters="reporter" weight=97
//% blockId=spritesoncreated block="on created $sprite of kind $kind=spritetype"
//% help=sprites/on-created
export function onCreated(kind: number, handler: (sprite: Sprite) => void): void {
        if (!handler || kind == undefined) return;

        const scene = game.currentScene();
        scene.createdHandlers.push({
            kind: kind,
            handler: handler
        })
    }


/**
     * Run code when a certain kind of sprite is destroyed
     * @param kind
     * @param sprite
     */
//% group="Lifecycle"
//% weight=96 draggableParameters="reporter"
//% blockId=spritesondestroyed block="on destroyed $sprite of kind $kind=spritetype "
//% help=sprites/on-destroyed
export function onDestroyed(kind: number, handler: (sprite: Sprite) => void) {
        if (!handler || kind == undefined) return;

        const scene = game.currentScene();
        scene.destroyedHandlers.push({
            kind: kind,
            handler: handler
        })
    }


/**
     * Run code when two kinds of sprites overlap
     */
//% group="Overlaps"
//% weight=100 draggableParameters="reporter"
//% blockId=spritesoverlap block="on $sprite of kind $kind=spritetype overlaps $otherSprite of kind $otherKind=spritetype"
//% help=sprites/on-overlap
//% blockGap=8
export function onOverlap(kind: number, otherKind: number, handler: (sprite: Sprite, otherSprite: Sprite) => void) {
        if (kind == undefined || otherKind == undefined || !handler) return;

        const scene = game.currentScene();
        scene.overlapHandlers.push({
            kind: kind,
            otherKind: otherKind,
            handler: handler
        })
    }


/**
     * Run code when a certain kind of sprite hits a tile
     * @param direction
     * @param tile
     * @param handler
     */
//% group="Collisions"
//% weight=100 draggableParameters="reporter"
//% blockId=spritesollisions block="on $sprite of kind $kind=spritetype hits wall $tile=colorindexpicker"
//% help=scene/on-hit-tile
export function onHitTile(kind: number, tile: number, handler: (sprite: Sprite) => void) {
        if (kind == undefined || !handler) return;

        const scene = game.currentScene();
        scene.collisionHandlers.push({
            kind: kind,
            tile: tile,
            handler: handler
        })
    }


() => {
  it("fallback to index when avatar don't have `key`", () => {
    const avatar: AvatarProps = {
      name: 'test_user',
    };

    const key = composeUniqueKey(avatar, 0);
    expect(key).toEqual(0);
  });

  it('use key for the unique key', () => {
    const avatar: AvatarProps = {
      name: 'test_user',
      key: 'test@atlassian.com',
    };
    const key = composeUniqueKey(avatar, 0);
    expect(key).toEqual('test@atlassian.com');
  });
}


() => {
    const avatar: AvatarProps = {
      name: 'test_user',
    };

    const key = composeUniqueKey(avatar, 0);
    expect(key).toEqual(0);
  }


() => {
    const avatar: AvatarProps = {
      name: 'test_user',
      key: 'test@atlassian.com',
    };
    const key = composeUniqueKey(avatar, 0);
    expect(key).toEqual('test@atlassian.com');
  }


/**
 * Represents a Workspace definition.
 */
export class Workspace extends pulumi.CustomResource {
    /**
     * Get an existing Workspace resource's state with the given name, ID, and optional extra
     * properties used to qualify the lookup.
     *
     * @param name The _unique_ name of the resulting resource.
     * @param id The _unique_ provider ID of the resource to lookup.
     * @param opts Optional settings to control the behavior of the CustomResource.
     */
    public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): Workspace {
        return new Workspace(name, undefined as any, { ...opts, id: id });
    }

    /** @internal */
    public static readonly __pulumiType = 'azure-nextgen:desktopvirtualization/v20191210preview:Workspace';

    /**
     * Returns true if the given object is an instance of Workspace.  This is designed to work even
     * when multiple copies of the Pulumi SDK have been loaded into the same process.
     */
    public static isInstance(obj: any): obj is Workspace {
        if (obj === undefined || obj === null) {
            return false;
        }
        return obj['__pulumiType'] === Workspace.__pulumiType;
    }

    /**
     * List of applicationGroup resource Ids.
     */
    public readonly applicationGroupReferences!: pulumi.Output<string[] | undefined>;
    /**
     * Description of Workspace.
     */
    public readonly description!: pulumi.Output<string | undefined>;
    /**
     * Friendly name of Workspace.
     */
    public readonly friendlyName!: pulumi.Output<string | undefined>;
    /**
     * The geo-location where the resource lives
     */
    public readonly location!: pulumi.Output<string>;
    /**
     * The name of the resource
     */
    public /*out*/ readonly name!: pulumi.Output<string>;
    /**
     * Resource tags.
     */
    public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
    /**
     * The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
     */
    public /*out*/ readonly type!: pulumi.Output<string>;

    /**
     * Create a Workspace resource with the given unique name, arguments, and options.
     *
     * @param name The _unique_ name of the resource.
     * @param args The arguments to use to populate this resource's properties.
     * @param opts A bag of options that control this resource's behavior.
     */
    constructor(name: string, args: WorkspaceArgs, opts?: pulumi.CustomResourceOptions) {
        let inputs: pulumi.Inputs = {};
        if (!(opts && opts.id)) {
            if ((!args || args.resourceGroupName === undefined) && !(opts && opts.urn)) {
                throw new Error("Missing required property 'resourceGroupName'");
            }
            inputs["applicationGroupReferences"] = args ? args.applicationGroupReferences : undefined;
            inputs["description"] = args ? args.description : undefined;
            inputs["friendlyName"] = args ? args.friendlyName : undefined;
            inputs["location"] = args ? args.location : undefined;
            inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
            inputs["tags"] = args ? args.tags : undefined;
            inputs["workspaceName"] = args ? args.workspaceName : undefined;
            inputs["name"] = undefined /*out*/;
            inputs["type"] = undefined /*out*/;
        } else {
            inputs["applicationGroupReferences"] = undefined /*out*/;
            inputs["description"] = undefined /*out*/;
            inputs["friendlyName"] = undefined /*out*/;
            inputs["location"] = undefined /*out*/;
            inputs["name"] = undefined /*out*/;
            inputs["tags"] = undefined /*out*/;
            inputs["type"] = undefined /*out*/;
        }
        if (!opts) {
            opts = {}
        }

        if (!opts.version) {
            opts.version = utilities.getVersion();
        }
        const aliasOpts = { aliases: [{ type: "azure-nextgen:desktopvirtualization:Workspace" }, { type: "azure-nextgen:desktopvirtualization/v20190123preview:Workspace" }, { type: "azure-nextgen:desktopvirtualization/v20190924preview:Workspace" }, { type: "azure-nextgen:desktopvirtualization/v20200921preview:Workspace" }, { type: "azure-nextgen:desktopvirtualization/v20201019preview:Workspace" }, { type: "azure-nextgen:desktopvirtualization/v20201102preview:Workspace" }, { type: "azure-nextgen:desktopvirtualization/v20201110preview:Workspace" }, { type: "azure-nextgen:desktopvirtualization/v20210114preview:Workspace" }, { type: "azure-nextgen:desktopvirtualization/v20210201preview:Workspace" }] };
        opts = opts ? pulumi.mergeOptions(opts, aliasOpts) : aliasOpts;
        super(Workspace.__pulumiType, name, inputs, opts);
    }
}


/**
 * The set of arguments for constructing a Workspace resource.
 */
export interface WorkspaceArgs {
    /**
     * List of applicationGroup resource Ids.
     */
    readonly applicationGroupReferences?: pulumi.Input<pulumi.Input<string>[]>;
    /**
     * Description of Workspace.
     */
    readonly description?: pulumi.Input<string>;
    /**
     * Friendly name of Workspace.
     */
    readonly friendlyName?: pulumi.Input<string>;
    /**
     * The geo-location where the resource lives
     */
    readonly location?: pulumi.Input<string>;
    /**
     * The name of the resource group. The name is case insensitive.
     */
    readonly resourceGroupName: pulumi.Input<string>;
    /**
     * Resource tags.
     */
    readonly tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
    /**
     * The name of the workspace
     */
    readonly workspaceName?: pulumi.Input<string>;
}


/**
     * Get an existing Workspace resource's state with the given name, ID, and optional extra
     * properties used to qualify the lookup.
     *
     * @param name The _unique_ name of the resulting resource.
     * @param id The _unique_ provider ID of the resource to lookup.
     * @param opts Optional settings to control the behavior of the CustomResource.
     */
public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): Workspace {
        return new Workspace(name, undefined as any, { ...opts, id: id });
    }


/**
     * Returns true if the given object is an instance of Workspace.  This is designed to work even
     * when multiple copies of the Pulumi SDK have been loaded into the same process.
     */
public static isInstance(obj: any): obj is Workspace {
        if (obj === undefined || obj === null) {
            return false;
        }
        return obj['__pulumiType'] === Workspace.__pulumiType;
    }


@Component({
    selector: 'app-lessThan-fieldName-validator',
    templateUrl: './less-than-field-name.component.html'
})
export class LessThanFieldNameValidatorComponent implements OnInit {
    userFormGroup: FormGroup

	constructor(
        private formBuilder: FormBuilder )
	{ }

    ngOnInit() {
        this.userFormGroup = this.formBuilder.group({
            obtainedMarks:['',],
            otherActivityMarks:['', RxwebValidators.lessThan({fieldName:'obtainedMarks' })],
        });
    }
}


ngOnInit() {
        this.userFormGroup = this.formBuilder.group({
            obtainedMarks:['',],
            otherActivityMarks:['', RxwebValidators.lessThan({fieldName:'obtainedMarks' })],
        });
    }


declare interface Menu {
  path: string;
  name?: string;
  meta: {
    icon?: string;
    title: string;
    show?: boolean;
  };
  children?: Array<Menu>;
}


function boldify(s: string): React.ReactNode {
    const fragments = s.split('**');
    return fragments.map((substr, index) => {
      return index % 2 === 0 ? substr : <b>{substr}</b>;
    });
}


(substr, index) => {
      return index % 2 === 0 ? substr : <b>{substr}</b>;
    }


() => {
        const worksheetUrl = getTablePublicUrl(tablesData[0].spreadsheetId, tablesData[0].sheetId);
        const email = 'cherebedov.sergey@gmail.com';
        const github = 'https://github.com/sonic16x/interslavic';
        const source = 'http://steen.free.fr/interslavic';
        let version = `v${VERSION}`;
        const trimmedBaseUrl = BASE_URL.replace('/', '');
        if (trimmedBaseUrl !== '') {
            version += `-${trimmedBaseUrl}`;
        }

        return (

{t('aboutSmallTitle')}

{t('aboutInterslavic')}

                        {t('aboutUsingFrom')} {source}.

{t('aboutJoinText')}

                        {t('aboutTranslationsTable')}

                        {t('nonCommercialDisclaimer')}

{t('aboutDeveloper')}

                            {t('aboutAuthorSergeyCherebedov')}:
                            GitHub
                            LinkedIn
                            Facebook
                            <a target={'_blank'} href={`email:${email}`}


t('aboutSmallTitle')


t('aboutInterslavic')


t('aboutJoinText')


t('aboutTranslationsTable')


t('nonCommercialDisclaimer')


t('aboutDeveloper')


t('aboutAuthorSergeyCherebedov')


t('aboutDeveloperCoauthors')


t('aboutAuthorDenisShabalin')


t('aboutAuthorJaroslavSerhieiev')


t('aboutTranslators')


t('aboutTranslatorsText')


t('aboutSourceCode')


t('aboutOurFriends')


export declare enum AuthenticationType {
    FINGERPRINT = 1,
    FACIAL_RECOGNITION = 2
}


export declare type LocalAuthenticationResult = {
    success: true;
} | {
    success: false;
    error: string;
};


export declare type AuthOptions = {
    promptMessage?: string;
    fallbackLabel?: string;
};


/** @doc_url https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-reroute.html#cluster-reroute-api-request-body */
export class Command {
  /**
   * Cancel allocation of a shard (or recovery). Accepts index and shard for index name and shard number, and node for the node to cancel the shard allocation on. This can be used to force resynchronization of existing replicas from the primary shard by cancelling them and allowing them to be reinitialized through the standard recovery process. By default only replica shard allocations can be cancelled. If it is necessary to cancel the allocation of a primary shard then the allow_primary flag must also be included in the request.
   */
  cancel?: CommandCancelAction
  /**
   * Move a started shard from one node to another node. Accepts index and shard for index name and shard number, from_node for the node to move the shard from, and to_node for the node to move the shard to.
   */
  move?: CommandMoveAction
  /**
   * Allocate an unassigned replica shard to a node. Accepts index and shard for index name and shard number, and node to allocate the shard to. Takes allocation deciders into account.
   */
  allocate_replica?: CommandAllocateReplicaAction
  /**
   * Allocate a primary shard to a node that holds a stale copy. Accepts the index and shard for index name and shard number, and node to allocate the shard to. Using this command may lead to data loss for the provided shard id. If a node which has the good copy of the data rejoins the cluster later on, that data will be deleted or overwritten with the data of the stale copy that was forcefully allocated with this command. To ensure that these implications are well-understood, this command requires the flag accept_data_loss to be explicitly set to true.
   */
  allocate_stale_primary?: CommandAllocatePrimaryAction
  /**
   * Allocate an empty primary shard to a node. Accepts the index and shard for index name and shard number, and node to allocate the shard to. Using this command leads to a complete loss of all data that was indexed into this shard, if it was previously started. If a node which has a copy of the data rejoins the cluster later on, that data will be deleted. To ensure that these implications are well-understood, this command requires the flag accept_data_loss to be explicitly set to true.
   */
  allocate_empty_primary?: CommandAllocatePrimaryAction
}


export class CommandCancelAction {
  index: IndexName
  shard: integer
  node: string
  allow_primary?: boolean
}


export class CommandAction {
  index: IndexName
  shard: integer
  node: string
  /** By default only replica shard allocations can be cancelled. If it is necessary to cancel the allocation of a primary shard then the allow_primary flag must also be included in the request. */
  allow_primary?: boolean
}


export class CommandMoveAction {
  index: IndexName
  shard: integer
  /** The node to move the shard from */
  from_node: string
  /** The node to move the shard to */
  to_node: string
}


/**
 * @doc_url https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-cluster.html
 */
export class CommandAllocateReplicaAction {
  index: IndexName
  shard: integer
  node: string
}


export class CommandAllocatePrimaryAction {
  index: IndexName
  shard: integer
  node: string
  /** If a node which has a copy of the data rejoins the cluster later on, that data will be deleted. To ensure that these implications are well-understood, this command requires the flag accept_data_loss to be explicitly set to true */
  accept_data_loss: boolean
}


export class RerouteDecision {
  decider: string
  decision: string
  explanation: string
}


export class RerouteExplanation {
  command: string
  decisions: RerouteDecision[]
  parameters: RerouteParameters
}


export class RerouteParameters {
  allow_primary: boolean
  index: IndexName
  node: NodeName
  shard: integer
  from_node?: NodeName
  to_node?: NodeName
}


@ApiTags('File Endpoint v15')
@Controller('file')
export class FileController {
  constructor(
    private fileService: FileService,
    @Inject(REQUEST) private requestCtx: IUserRequest & Request,
  ) {}

  @UseGuards(JwtAuthenticationGuard)
  @ApiOperation({ summary: 'Upload file production' })
  @UseInterceptors(FileInterceptor('file'))
  @Post()
  public async uploadFile(@UploadedFile() file, @Res() res) {
    const result = await this.fileService.uploadPrivateFile(
      file.buffer,
      file.originalname,
    );

    return res.status(HttpStatus.OK).json(result);
  }

  @UseGuards(JwtAuthenticationGuard)
  @ApiOperation({ summary: 'Delete upload file' })
  @UseInterceptors(FileInterceptor('file'))
  @Delete('/:id')
  public async deleteUploadFile(@Param('id') id: string, @Res() res) {
    await this.fileService.deletePrivateFile(id);
    return res.status(HttpStatus.OK).json(SUCCESS_MESSAGE.DELETED);
  }
}


@UseGuards(JwtAuthenticationGuard)
  @ApiOperation({ summary: 'Upload file production' })
  @UseInterceptors(FileInterceptor('file'))
  @Post()
  public async uploadFile(@UploadedFile() file, @Res() res) {
    const result = await this.fileService.uploadPrivateFile(
      file.buffer,
      file.originalname,
    );

    return res.status(HttpStatus.OK).json(result);
  }


@UseGuards(JwtAuthenticationGuard)
  @ApiOperation({ summary: 'Delete upload file' })
  @UseInterceptors(FileInterceptor('file'))
  @Delete('/:id')
  public async deleteUploadFile(@Param('id') id: string, @Res() res) {
    await this.fileService.deletePrivateFile(id);
    return res.status(HttpStatus.OK).json(SUCCESS_MESSAGE.DELETED);
  }


(): JSX.Element => (
	<Layout title="">
		<Stack align


export enum SteamLoginErrors {
    MissingDetails = "MissingDetails",
    IncorrectDetails = "Error: Uncaught Error: The account name or password that you have entered is incorrect.",
    SteamGuard = "SteamGuard",
    SteamGuardMobile = "SteamGuardMobile",
    Captcha = "CAPTCHA",
    OldSession = "Old Session"
}


export enum Steam2FAErrors {
    NoMobile = "Error 2"
}


content => {
                this.setContent(content);
                return super.load(credentials);
            }


err => {
                const { authFailure = false } = Layerr.info(err);
                if (!authFailure) {
                    throw new Layerr(err, "Failed fetching Google Drive vault");
                } else if (hasAuthed) {
                    throw new Layerr(err, "Re-authentication failed");
                }
                return this.authManager
                    .executeAuthHandlers(DATASOURCE_TYPE, this)
                    .then(() => this.load(credentials, true))
                    .catch(err2 => {
                        throw new Layerr(err2, "Failed fetching Google Drive vault");
                    });
            }


() => this.load(credentials, true)


err2 => {
                        throw new Layerr(err2, "Failed fetching Google Drive vault");
                    }


encryptedContent =>
                this.client.putFileContents({
                    id: this.fileID,
                    contents: encryptedContent
                })


err => {
                const { authFailure = false } = Layerr.info(err);
                if (!authFailure) {
                    throw new Layerr(err, "Failed saving Google Drive vault");
                } else if (hasAuthed) {
                    throw new Layerr(err, "Re-authentication failed");
                }
                return this.authManager
                    .executeAuthHandlers(DATASOURCE_TYPE, this)
                    .then(() => this.save(history, credentials, true))
                    .catch(err2 => {
                        throw new Layerr(err2, "Failed saving Google Drive vault");
                    });
            }


() => this.save(history, credentials, true)


err2 => {
                        throw new Layerr(err2, "Failed saving Google Drive vault");
                    }


/**
 * Datasource for Google Drive archives
 * @augments TextDatasource
 * @memberof module:Buttercup
 */
export default class GoogleDriveDatasource extends TextDatasource {
    authManager: DatasourceAuthManager;
    client: any;
    fileID: string;
    token: string;
    refreshToken: string;

    /**
     * Datasource for Google Drive connections
     * @param {Credentials} credentials The credentials instance with which to
     *  configure the datasource with
     */
    constructor(credentials: Credentials) {
        super(credentials);
        const { data: credentialData } = getCredentials(credentials.id);
        const { datasource: datasourceConfig } = credentialData;
        const { token, refreshToken, fileID } = datasourceConfig;
        this.fileID = fileID;
        this.token = token;
        this.refreshToken = refreshToken;
        this.client = createClient(token);
        this.authManager = DatasourceAuthManager.getSharedManager();
        this.type = DATASOURCE_TYPE;
        fireInstantiationHandlers(DATASOURCE_TYPE, this);
    }

    /**
     * Load an archive from the datasource
     * @param {Credentials} credentials The credentials for decryption
     * @returns {Promise.<LoadedVaultData>} A promise that resolves archive history
     * @memberof GoogleDriveDatasource
     */
    load(credentials, hasAuthed = false) {
        if (this.hasContent) {
            return super.load(credentials);
        }
        return this.client
            .getFileContents(this.fileID)
            .then(content => {
                this.setContent(content);
                return super.load(credentials);
            })
            .catch(err => {
                const { authFailure = false } = Layerr.info(err);
                if (!authFailure) {
                    throw new Layerr(err, "Failed fetching Google Drive vault");
                } else if (hasAuthed) {
                    throw new Layerr(err, "Re-authentication failed");
                }
                return this.authManager
                    .executeAuthHandlers(DATASOURCE_TYPE, this)
                    .then(() => this.load(credentials, true))
                    .catch(err2 => {
                        throw new Layerr(err2, "Failed fetching Google Drive vault");
                    });
            });
    }

    /**
     * Save an archive using the datasource
     * @param {Array.<String>} history The archive history to save
     * @param {Credentials} credentials The credentials to save with
     * @returns {Promise} A promise that resolves when saving has completed
     * @memberof GoogleDriveDatasource
     */
    save(history, credentials, hasAuthed = false) {
        return super
            .save(history, credentials)
            .then(encryptedContent =>
                this.client.putFileContents({
                    id: this.fileID,
                    contents: encryptedContent
                })
            )
            .catch(err => {
                const { authFailure = false } = Layerr.info(err);
                if (!authFailure) {
                    throw new Layerr(err, "Failed saving Google Drive vault");
                } else if (hasAuthed) {
                    throw new Layerr(err, "Re-authentication failed");
                }
                return this.authManager
                    .executeAuthHandlers(DATASOURCE_TYPE, this)
                    .then(() => this.save(history, credentials, true))
                    .catch(err2 => {
                        throw new Layerr(err2, "Failed saving Google Drive vault");
                    });
            });
    }

    /**
     * Whether or not the datasource supports bypassing remote fetch operations
     * @returns {Boolean} True if content can be set to bypass fetch operations,
     *  false otherwise
     * @memberof GoogleDriveDatasource
     */
    supportsRemoteBypass() {
        return true;
    }

    /**
     * Update the OAuth2 tokens
     * @param {String} accessToken The access token
     * @param {String=} refreshToken The refresh token
     * @memberof GoogleDriveDatasource
     */
    updateTokens(accessToken, refreshToken) {
        this.token = accessToken;
        this.refreshToken = refreshToken;
        this.client = createClient(accessToken);
        const { data: credentialData } = getCredentials(this.credentials.id);
        credentialData.datasource.token = accessToken;
        credentialData.datasource.refreshToken = refreshToken;
        this.emit("updated");
    }
}


/**
     * Load an archive from the datasource
     * @param {Credentials} credentials The credentials for decryption
     * @returns {Promise.<LoadedVaultData>} A promise that resolves archive history
     * @memberof GoogleDriveDatasource
     */
load(credentials, hasAuthed = false) {
        if (this.hasContent) {
            return super.load(credentials);
        }
        return this.client
            .getFileContents(this.fileID)
            .then(content => {
                this.setContent(content);
                return super.load(credentials);
            })
            .catch(err => {
                const { authFailure = false } = Layerr.info(err);
                if (!authFailure) {
                    throw new Layerr(err, "Failed fetching Google Drive vault");
                } else if (hasAuthed) {
                    throw new Layerr(err, "Re-authentication failed");
                }
                return this.authManager
                    .executeAuthHandlers(DATASOURCE_TYPE, this)
                    .then(() => this.load(credentials, true))
                    .catch(err2 => {
                        throw new Layerr(err2, "Failed fetching Google Drive vault");
                    });
            });
    }


/**
     * Save an archive using the datasource
     * @param {Array.<String>} history The archive history to save
     * @param {Credentials} credentials The credentials to save with
     * @returns {Promise} A promise that resolves when saving has completed
     * @memberof GoogleDriveDatasource
     */
save(history, credentials, hasAuthed = false) {
        return super
            .save(history, credentials)
            .then(encryptedContent =>
                this.client.putFileContents({
                    id: this.fileID,
                    contents: encryptedContent
                })
            )
            .catch(err => {
                const { authFailure = false } = Layerr.info(err);
                if (!authFailure) {
                    throw new Layerr(err, "Failed saving Google Drive vault");
                } else if (hasAuthed) {
                    throw new Layerr(err, "Re-authentication failed");
                }
                return this.authManager
                    .executeAuthHandlers(DATASOURCE_TYPE, this)
                    .then(() => this.save(history, credentials, true))
                    .catch(err2 => {
                        throw new Layerr(err2, "Failed saving Google Drive vault");
                    });
            });
    }


/**
     * Whether or not the datasource supports bypassing remote fetch operations
     * @returns {Boolean} True if content can be set to bypass fetch operations,
     *  false otherwise
     * @memberof GoogleDriveDatasource
     */
supportsRemoteBypass() {
        return true;
    }


/**
     * Update the OAuth2 tokens
     * @param {String} accessToken The access token
     * @param {String=} refreshToken The refresh token
     * @memberof GoogleDriveDatasource
     */
updateTokens(accessToken, refreshToken) {
        this.token = accessToken;
        this.refreshToken = refreshToken;
        this.client = createClient(accessToken);
        const { data: credentialData } = getCredentials(this.credentials.id);
        credentialData.datasource.token = accessToken;
        credentialData.datasource.refreshToken = refreshToken;
        this.emit("updated");
    }


export default class AssetOptions extends Struct {
  constructor(registry: Registry, value: any) {
    super(registry, {initialIssuance: 'Compact<Balance>', permissions: PermissionLatest}, value);
  }

  get initialIssuance(): Balance {
    return this.get('initialIssuance') as Balance;
  }

  get permissions(): PermissionLatest {
    return this.get('permissions') as PermissionLatest;
  }
}


@Component({
    selector: 'uxd-components-number-picker',
    templateUrl: './number-picker.component.html'
})
@DocumentationSectionComponent('ComponentsNumberPickerComponent')
export class ComponentsNumberPickerComponent extends BaseDocumentationSection implements IPlaygroundProvider {

    form: FormGroup;

    playground: IPlayground = {
        files: {
            'app.component.ts': this.snippets.raw.appTs,
            'app.component.html': this.snippets.raw.appHtml,
            'app.component.css': this.snippets.raw.appCss
        },
        modules: [{
            imports: ['NumberPickerModule'],
            library: '@ux-aspects/ux-aspects'
        }]
    };

    constructor(formBuilder: FormBuilder) {
        super(require.context('./snippets/', false, /\.(html|css|js|ts)$/));

        this.form = formBuilder.group({
            integer: [0, Validators.compose([Validators.required, Validators.min(-10), Validators.max(10)])],
            decimal: [0, Validators.compose([Validators.required, Validators.min(0), Validators.max(10)])]
        });
    }
}


() => {

  const converter: FsTimestampConverter = new FsTimestampConverter();

  describe('#fromJson()', () => {
    it('should convert timestamp to date', () => {
      const date: Date = converter.fromJson(Timestamp.fromDate(new Date(2020, 8)));
      expect(date.getMonth()).toEqual(8);
      expect(date.getFullYear()).toEqual(2020);
    });

    it('should not convert null', () => {
      expect(converter.fromJson(null)).toBeNull();
    });

    it('should not convert undefined', () => {
      expect(converter.fromJson(undefined)).toBeUndefined();
    });
  });

  describe('#toJson()', () => {
    it('should convert timestamp to date', () => {
      const timestamp: Timestamp = converter.toJson(new Date(2020, 8));
      expect(timestamp.toDate().getMonth()).toEqual(8);
      expect(timestamp.toDate().getFullYear()).toEqual(2020);
    });

    it('should not convert null', () => {
      expect(converter.toJson(null)).toBeNull();
    });

    it('should not convert undefined', () => {
      expect(converter.toJson(undefined)).toBeUndefined();
    });
  });
}


() => {
    it('should convert timestamp to date', () => {
      const date: Date = converter.fromJson(Timestamp.fromDate(new Date(2020, 8)));
      expect(date.getMonth()).toEqual(8);
      expect(date.getFullYear()).toEqual(2020);
    });

    it('should not convert null', () => {
      expect(converter.fromJson(null)).toBeNull();
    });

    it('should not convert undefined', () => {
      expect(converter.fromJson(undefined)).toBeUndefined();
    });
  }


() => {
      const date: Date = converter.fromJson(Timestamp.fromDate(new Date(2020, 8)));
      expect(date.getMonth()).toEqual(8);
      expect(date.getFullYear()).toEqual(2020);
    }


() => {
      expect(converter.fromJson(null)).toBeNull();
    }


() => {
      expect(converter.fromJson(undefined)).toBeUndefined();
    }


() => {
    it('should convert timestamp to date', () => {
      const timestamp: Timestamp = converter.toJson(new Date(2020, 8));
      expect(timestamp.toDate().getMonth()).toEqual(8);
      expect(timestamp.toDate().getFullYear()).toEqual(2020);
    });

    it('should not convert null', () => {
      expect(converter.toJson(null)).toBeNull();
    });

    it('should not convert undefined', () => {
      expect(converter.toJson(undefined)).toBeUndefined();
    });
  }


() => {
      const timestamp: Timestamp = converter.toJson(new Date(2020, 8));
      expect(timestamp.toDate().getMonth()).toEqual(8);
      expect(timestamp.toDate().getFullYear()).toEqual(2020);
    }


() => {
      expect(converter.toJson(null)).toBeNull();
    }


() => {
      expect(converter.toJson(undefined)).toBeUndefined();
    }


export default class LandAction extends React.PureComponent<Props> {
  render() {
    const { land, title, subtitle, children, onNavigate } = this.props
    return (
      <div className="LandAction">
        <Row height={48}>
          <Back absolute onClick={() => onNavigate(locations.landDetail(land.id))}


render() {
    const { land, title, subtitle, children, onNavigate } = this.props
    return (
      <div className="LandAction">
        <Row height={48}>
          <Back absolute onClick={() => onNavigate(locations.landDetail(land.id))}


title ? (
                <Section


([key, value]) => key.endsWith(".d.ts")


() => 0.5


() => 0.1


() => {
    const params = new URLSearchParams(window.location.search)
    const type = params.get("type") || true
    const [state, setState] = React.useState(false)

    return (
        <>
            <motion.div
                id="a"
                layoutId="box"
                layout={type}
                style={a}
                onClick={()


() => IOHelper.sizeOfUInt8


async (options: TransactionGetScriptHashesForVerifyingOptions) => {
        const { getOutput, getAsset } = options;
        const [hashes, issuerHashes] = await Promise.all([
          getScriptHashesForVerifying(options),
          this.getTransactionResults({ getOutput }).then(async (results) =>
            Promise.all(
              Object.entries(results)
                // tslint:disable-next-line no-unused
                .filter(([_, value]) => value.lt(utils.ZERO))
                // tslint:disable-next-line no-unused
                .map(async ([assetHash, _]) => {
                  const asset = await getAsset({
                    hash: common.hexToUInt256(assetHash),
                  });

                  return common.uInt160ToHex(asset.issuer);
                }),
            ),
          ),
        ]);

        return new Set([...hashes, ...issuerHashes]);
      }


async (results) =>
            Promise.all(
              Object.entries(results)
                // tslint:disable-next-line no-unused
                .filter(([_, value]) => value.lt(utils.ZERO))
                // tslint:disable-next-line no-unused
                .map(async ([assetHash, _]) => {
                  const asset = await getAsset({
                    hash: common.hexToUInt256(assetHash),
                  });

                  return common.uInt160ToHex(asset.issuer);
                }),
            )


([_, value]) => value.lt(utils.ZERO)


async ([assetHash, _]) => {
                  const asset = await getAsset({
                    hash: common.hexToUInt256(assetHash),
                  });

                  return common.uInt160ToHex(asset.issuer);
                }


(output) =>
          common.uInt256Equal(output.asset, governingToken.hash) ||
          common.uInt256Equal(output.asset, utilityToken.hash)


async ([assetHex, value]) => {
        const hash = common.hexToUInt256(assetHex);
        const asset = await getAsset({ hash });
        if (asset.amount.lt(utils.ZERO)) {
          return;
        }

        const issued = asset.available.add(
          memPool
            .filter((transaction) => transaction !== this)
            .reduce(
              (acc, transaction) =>
                transaction.outputs
                  .filter((output) => common.uInt256Equal(hash, output.asset))
                  .reduce((innerAcc, output) => innerAcc.add(output.value), acc),

              utils.ZERO,
            ),
        );

        if (asset.amount.sub(issued).lt(value.neg())) {
          throw new VerifyError('Invalid issue amount');
        }
      }


(transaction) => transaction !== this


(acc, transaction) =>
                transaction.outputs
                  .filter((output) => common.uInt256Equal(hash, output.asset))
                  .reduce((innerAcc, output) => innerAcc.add(output.value), acc)


(output) => common.uInt256Equal(hash, output.asset)


(innerAcc, output) => innerAcc.add(output.value)


export class IssueTransaction extends TransactionBase<
  TransactionType.Issue,
  IssueTransactionJSON,
  Constructor<IssueTransactionModel<Attribute, Input, Output, Witness>>
>(IssueTransactionModel) {
  public static deserializeWireBase(options: DeserializeWireBaseOptions): IssueTransaction {
    const { type, version } = super.deserializeTransactionBaseStartWireBase(options);

    if (type !== TransactionType.Issue) {
      throw new InvalidFormatError(`Expected transaction type to be ${TransactionType.Issue}. Received: ${type}`);
    }

    const { attributes, inputs, outputs, scripts } = super.deserializeTransactionBaseEndWireBase(options);

    return new this({
      version,
      attributes,
      inputs,
      outputs,
      scripts,
    });
  }

  public readonly sizeExclusive: () => number = utils.lazy(() => IOHelper.sizeOfUInt8);
  private readonly issueGetScriptHashesForVerifyingInternal: (
    options: TransactionGetScriptHashesForVerifyingOptions,
  ) => Promise<Set<UInt160Hex>>;

  public constructor(add: IssueTransactionAdd) {
    super(add);

    const getScriptHashesForVerifying = super.getScriptHashesForVerifying.bind(this);
    this.issueGetScriptHashesForVerifyingInternal = utils.lazyAsync(
      async (options: TransactionGetScriptHashesForVerifyingOptions) => {
        const { getOutput, getAsset } = options;
        const [hashes, issuerHashes] = await Promise.all([
          getScriptHashesForVerifying(options),
          this.getTransactionResults({ getOutput }).then(async (results) =>
            Promise.all(
              Object.entries(results)
                // tslint:disable-next-line no-unused
                .filter(([_, value]) => value.lt(utils.ZERO))
                // tslint:disable-next-line no-unused
                .map(async ([assetHash, _]) => {
                  const asset = await getAsset({
                    hash: common.hexToUInt256(assetHash),
                  });

                  return common.uInt160ToHex(asset.issuer);
                }),
            ),
          ),
        ]);

        return new Set([...hashes, ...issuerHashes]);
      },
    );
  }

  public async serializeJSON(context: SerializeJSONContext): Promise<IssueTransactionJSON> {
    const transactionBaseJSON = await super.serializeTransactionBaseJSON(context);

    return {
      ...transactionBaseJSON,
      type: 'IssueTransaction',
    };
  }

  public getSystemFee(context: FeeContext): BN {
    if (this.version >= 1) {
      return utils.ZERO;
    }

    const { governingToken, utilityToken } = context;
    if (
      this.outputs.every(
        (output) =>
          common.uInt256Equal(output.asset, governingToken.hash) ||
          common.uInt256Equal(output.asset, utilityToken.hash),
      )
    ) {
      return utils.ZERO;
    }

    return super.getSystemFee(context);
  }

  public async getScriptHashesForVerifying(
    options: TransactionGetScriptHashesForVerifyingOptions,
  ): Promise<Set<UInt160Hex>> {
    return this.issueGetScriptHashesForVerifyingInternal(options);
  }

  public async verify(options: TransactionVerifyOptions): Promise<readonly VerifyScriptResult[]> {
    const [results] = await Promise.all([super.verify(options), this.verifyInternal(options)]);

    return results;
  }

  private async verifyInternal(options: TransactionVerifyOptions): Promise<void> {
    const { getOutput, getAsset, memPool = [] } = options;
    const results = await this.getTransactionResults({ getOutput });
    await Promise.all(
      Object.entries(results).map(async ([assetHex, value]) => {
        const hash = common.hexToUInt256(assetHex);
        const asset = await getAsset({ hash });
        if (asset.amount.lt(utils.ZERO)) {
          return;
        }

        const issued = asset.available.add(
          memPool
            .filter((transaction) => transaction !== this)
            .reduce(
              (acc, transaction) =>
                transaction.outputs
                  .filter((output) => common.uInt256Equal(hash, output.asset))
                  .reduce((innerAcc, output) => innerAcc.add(output.value), acc),

              utils.ZERO,
            ),
        );

        if (asset.amount.sub(issued).lt(value.neg())) {
          throw new VerifyError('Invalid issue amount');
        }
      }),
    );
  }
}


// tslint:disable-next-line
export interface IssueTransactionAdd extends TransactionBaseAdd {}


public static deserializeWireBase(options: DeserializeWireBaseOptions): IssueTransaction {
    const { type, version } = super.deserializeTransactionBaseStartWireBase(options);

    if (type !== TransactionType.Issue) {
      throw new InvalidFormatError(`Expected transaction type to be ${TransactionType.Issue}. Received: ${type}`);
    }

    const { attributes, inputs, outputs, scripts } = super.deserializeTransactionBaseEndWireBase(options);

    return new this({
      version,
      attributes,
      inputs,
      outputs,
      scripts,
    });
  }


public async serializeJSON(context: SerializeJSONContext): Promise<IssueTransactionJSON> {
    const transactionBaseJSON = await super.serializeTransactionBaseJSON(context);

    return {
      ...transactionBaseJSON,
      type: 'IssueTransaction',
    };
  }


public getSystemFee(context: FeeContext): BN {
    if (this.version >= 1) {
      return utils.ZERO;
    }

    const { governingToken, utilityToken } = context;
    if (
      this.outputs.every(
        (output) =>
          common.uInt256Equal(output.asset, governingToken.hash) ||
          common.uInt256Equal(output.asset, utilityToken.hash),
      )
    ) {
      return utils.ZERO;
    }

    return super.getSystemFee(context);
  }


public async getScriptHashesForVerifying(
    options: TransactionGetScriptHashesForVerifyingOptions,
  ): Promise<Set<UInt160Hex>> {
    return this.issueGetScriptHashesForVerifyingInternal(options);
  }


public async verify(options: TransactionVerifyOptions): Promise<readonly VerifyScriptResult[]> {
    const [results] = await Promise.all([super.verify(options), this.verifyInternal(options)]);

    return results;
  }


private async verifyInternal(options: TransactionVerifyOptions): Promise<void> {
    const { getOutput, getAsset, memPool = [] } = options;
    const results = await this.getTransactionResults({ getOutput });
    await Promise.all(
      Object.entries(results).map(async ([assetHex, value]) => {
        const hash = common.hexToUInt256(assetHex);
        const asset = await getAsset({ hash });
        if (asset.amount.lt(utils.ZERO)) {
          return;
        }

        const issued = asset.available.add(
          memPool
            .filter((transaction) => transaction !== this)
            .reduce(
              (acc, transaction) =>
                transaction.outputs
                  .filter((output) => common.uInt256Equal(hash, output.asset))
                  .reduce((innerAcc, output) => innerAcc.add(output.value), acc),

              utils.ZERO,
            ),
        );

        if (asset.amount.sub(issued).lt(value.neg())) {
          throw new VerifyError('Invalid issue amount');
        }
      }),
    );
  }


export default function NetworkSettings() {
  const [pollingInterval, changePollingInterval] = useNetworkSettingsStore(
    (state) => [state.pollingInterval, state.changePollingInterval],
    shallow,
  );
  return (
    <div>
      <TextField
        variant="outlined"
        margin="normal"
        value={pollingInterval}
        onChange={(e) => changePollingInterval(Number(e.target.value))}


(state) => [state.pollingInterval, state.changePollingInterval]


(interval) => (
          <MenuItem key={interval}


ms(interval, { long: true }) : 'Disable'


@Component({
  selector: 'code-editor-demo',
  styleUrls: ['./code-editor.component.scss'],
  templateUrl: './code-editor.component.html',
  preserveWhitespaces: true,
})
export class CodeEditorDemoComponent {
  editorVal: string = `
  SELECT department_number, sampleid
  FROM department
  SAMPLE .25, .25, .50
  ORDER BY sampleid;

  SELECT department_number, sampleid
  FROM department
  SAMPLE  3, 5, 8
  ORDER BY sampleid;
  `;
}


// for libunboundWorker.jsm
declare function postMessage(WorkerResponse: Libunbound.Log|Libunbound.Result|Libunbound.Exception): void;


interface LibunboundWorker extends Worker {
        onmessage: (this: Worker, ev: WorkerResponse) => any;
        postMessage(message: LoadRequest|ResolveRequest|UpdateCtxRequest, transfer?: any[]): void;
    }


interface Request {
        callId: number,
        method: string,
    }


interface LoadRequest extends Request {
        method: "load",
        path: string,
    }


interface ResolveRequest extends Request {
        method: "resolve",
        name: string,
        rrtype: number,
    }


interface UpdateCtxRequest extends Request {
        method: "update_ctx",
        getNameserversFromOS: boolean,
        nameservers: string[],
        trustAnchors: string[],
        conf?: string,
        debuglevel?: number,
    }


interface WorkerRequest extends MessageEvent {
        data: Request;
    }


interface Log {
        type: string; // "log"
        subType: string;
        message: string;
    }


interface Response {
        type?: string;
        callId: number;
    }


interface Result extends Response {
        result: ub_result;
    }


interface Exception extends Response {
        subType: string;
        message: string;
    }


interface WorkerResponse extends MessageEvent {
        data: Log|Response;
    }


// for dkimVerifier.jsm
interface dkimResultCallback {
    (msgURI: string, result: dkimResultV1): void;
}


interface IDeferred<T> {
    promise: Promise<T>;
    resolve(reason: T): void;
    reject(reason: Error): void;
}


() => {
    /* eslint-disable no-console */
    console.log(`Listening on:`);
    console.log(`  http://localhost:${PORT}/ - client only rendering`);
    console.log(`  http://localhost:${PORT}/server - ssr with hydration`);
    /* eslint-enable no-console */
}


(o, f) => (f ? f(o) : null)


({
    children,
    store = createStore(state),
    mockFramework = mockFrameworks.default_UTC,
    onDragEnd = jest.fn(),
  }) => (
    <I18nProvider>
      <ApolloProvider client={client}>
        <ReduxStoreProvider store


interface Props {
  children: React.ReactNode;
  mockFramework?: Partial<AppTestingFrameworkAdapter>;
  store?: Store;
  onDragEnd?: (result: DropResult, provided: ResponderProvided) => void;
}


export type IPermission = {
    actionId: string;
    id: string;
    menuId: string;
    roleId: string;
    status: string;
};


export type PermissionState = {
    loading: boolean;
    error: string;
    data: IPermission[];
};


export type UpdatePermissionPayload = {
    actionId: string;
    menuId: string;
    roleId: string;
    status: string;
};


function removeExtraSpaces(textS: string) {
  return `${textS}`.replace(/\s+/g, ' ');
}


() => gridOptionMock


() => {
    ea = new EventAggregator();
    i18n = new I18N(ea, new BindingSignaler());

    divContainer = document.createElement('div');
    divContainer.innerHTML = template;
    document.body.appendChild(divContainer);
    spyGetHeaderRow = jest.spyOn(gridStub, 'getHeaderRowColumn').mockReturnValue(divContainer);

    mockColumn = { id: 'finish', field: 'finish', filterable: true, outputType: FieldType.dateIso, filter: { model: Filters.compoundDate, operator: '>' } };

    filterArguments = {
      grid: gridStub,
      columnDef: mockColumn,
      callback: jest.fn()
    };

    i18n.setup({
      resources: {
        en: {
          translation: {
            CONTAINS: 'Contains',
            EQUALS: 'Equals',
            ENDS_WITH: 'Ends With',
            STARTS_WITH: 'Starts With',
            EQUAL_TO: 'Equal to',
            LESS_THAN: 'Less than',
            LESS_THAN_OR_EQUAL_TO: 'Less than or equal to',
            GREATER_THAN: 'Greater than',
            GREATER_THAN_OR_EQUAL_TO: 'Greater than or equal to',
            NOT_EQUAL_TO: 'Not equal to',
          }
        },
        fr: {
          translation:
          {
            CONTAINS: 'Contient',
            EQUALS: 'Égale',
            ENDS_WITH: 'Se termine par',
            STARTS_WITH: 'Commence par',
            EQUAL_TO: 'Égal à',
            LESS_THAN: 'Plus petit que',
            LESS_THAN_OR_EQUAL_TO: 'Plus petit ou égal à',
            GREATER_THAN: 'Plus grand que',
            GREATER_THAN_OR_EQUAL_TO: 'Plus grand ou égal à',
            NOT_EQUAL_TO: 'Non égal à',
          }
        }
      },
      lng: 'en',
      fallbackLng: 'en',
      debug: false
    });

    filter = new CompoundDateFilter(i18n);
  }


() => {
    filter.destroy();
  }


() => {
    expect(() => filter.init(null)).toThrowError('[Aurelia-SlickGrid] A filter must always have an "init()" with valid arguments.');
  }


() => filter.init(null)


() => {
    filter.init(filterArguments);
    const filterCount = divContainer.querySelectorAll('.form-group.search-filter.filter-finish').length;

    expect(spyGetHeaderRow).toHaveBeenCalled();
    expect(filterCount).toBe(1);
  }


() => {
    const testValue = 'test placeholder';
    mockColumn.filter.placeholder = testValue;

    filter.init(filterArguments);
    const filterElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish .flatpickr input.input');

    expect(filterElm.placeholder).toBe(testValue);
  }


() => {
    filter.init(filterArguments);
    const spy = jest.spyOn(filter.flatInstance, 'close');
    const calendarElm = document.body.querySelector<HTMLDivElement>('.flatpickr-calendar');
    filter.hide();

    expect(calendarElm).toBeTruthy();
    expect(spy).toHaveBeenCalled();
  }


() => {
    filter.init(filterArguments);
    const spy = jest.spyOn(filter.flatInstance, 'open');
    const calendarElm = document.body.querySelector<HTMLDivElement>('.flatpickr-calendar');
    filter.show();

    expect(calendarElm).toBeTruthy();
    expect(spy).toHaveBeenCalled();
  }


() => {
    filter.init(filterArguments);

    expect(filter.flatInstance).toBeTruthy();
    expect(filter.flatpickrOptions).toEqual({
      altFormat: 'Y-m-d',
      altInput: true,
      closeOnSelect: true,
      dateFormat: 'Y-m-d',
      defaultDate: '',
      locale: 'en',
      onChange: expect.anything(),
      wrap: true,
    });
  }


() => {
    const mockDate = '2001-01-02T16:02:02.239Z';
    filter.init(filterArguments);
    filter.setValues(mockDate);
    expect(filter.currentDate).toEqual(mockDate);
  }


() => {
    const mockDate = '2001-01-02T16:02:02.239Z';
    filter.init(filterArguments);
    filter.setValues([mockDate]);
    expect(filter.currentDate).toEqual(mockDate);
  }


() => {
    const mockDate = '2001-01-02T16:02:02.239Z';
    filter.init(filterArguments);
    filter.setValues([mockDate], OperatorType.greaterThanOrEqual);

    const filterOperatorElm = divContainer.querySelector<HTMLInputElement>('.input-group-prepend.operator select');

    expect(filter.currentDate).toEqual(mockDate);
    expect(filterOperatorElm.value).toBe('>=');
  }


() => {
    mockColumn.filter.filterOptions = { allowInput: true }; // change to allow input value only for testing purposes
    mockColumn.filter.operator = '>';
    const spyCallback = jest.spyOn(filterArguments, 'callback');

    filter.init(filterArguments);
    const filterInputElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish .flatpickr input.input');
    filterInputElm.value = '2001-01-02T16:02:02.239Z';
    filterInputElm.dispatchEvent(new (window.window as any).KeyboardEvent('keydown', { keyCode: 13, bubbles: true, cancelable: true }));
    const filterFilledElms = divContainer.querySelectorAll<HTMLInputElement>('.form-group.search-filter.filter-finish.filled');

    expect(filterFilledElms.length).toBe(1);
    expect(spyCallback).toHaveBeenCalledWith(undefined, {
      columnDef: mockColumn, operator: '>', searchTerms: ['2001-01-02'], shouldTriggerQuery: true
    });
  }


() => {
    mockColumn.filter.filterOptions = { allowInput: true }; // change to allow input value only for testing purposes
    mockColumn.filter.operator = '>';
    const spyCallback = jest.spyOn(filterArguments, 'callback');

    filter.init(filterArguments);
    const filterInputElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish .flatpickr input.input');
    filterInputElm.value = '2001-01-02T16:02:02.239Z';
    filterInputElm.dispatchEvent(new (window.window as any).KeyboardEvent('keydown', { keyCode: 13, bubbles: true, cancelable: true }));
    const filterFilledElms = divContainer.querySelectorAll<HTMLInputElement>('.form-group.search-filter.filter-finish.filled');

    expect(filterFilledElms.length).toBe(1);
    expect(spyCallback).toHaveBeenCalledWith(undefined, { columnDef: mockColumn, operator: '>', searchTerms: ['2001-01-02'], shouldTriggerQuery: true });
  }


() => {
    filterArguments.searchTerms = ['2000-01-01T05:00:00.000Z'];
    mockColumn.filter.operator = '<=';
    const spyCallback = jest.spyOn(filterArguments, 'callback');

    filter.init(filterArguments);
    const filterInputElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish .flatpickr input.input');

    filterInputElm.focus();
    filterInputElm.dispatchEvent(new (window.window as any).KeyboardEvent('keyup', { keyCode: 97, bubbles: true, cancelable: true }));
    const filterFilledElms = divContainer.querySelectorAll<HTMLInputElement>('.form-group.search-filter.filter-finish.filled');

    expect(filterFilledElms.length).toBe(1);
    expect(filter.currentDate).toBe('2000-01-01T05:00:00.000Z');
    expect(filterInputElm.value).toBe('2000-01-01');
    expect(spyCallback).toHaveBeenCalledWith(expect.anything(), { columnDef: mockColumn, operator: '<=', searchTerms: ['2000-01-01T05:00:00.000Z'], shouldTriggerQuery: true });
  }


() => {
    filterArguments.searchTerms = ['2000-01-01T05:00:00.000Z'];
    mockColumn.filter.operator = '>';
    const spyCallback = jest.spyOn(filterArguments, 'callback');

    filter.init(filterArguments);
    const filterSelectElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish select');

    filterSelectElm.value = '<=';
    filterSelectElm.dispatchEvent(DOM.createCustomEvent('change'));
    const filterFilledElms = divContainer.querySelectorAll<HTMLInputElement>('.form-group.search-filter.filter-finish.filled');

    expect(filterFilledElms.length).toBe(1);
    expect(spyCallback).toHaveBeenCalledWith(expect.anything(), { columnDef: mockColumn, operator: '<=', searchTerms: ['2000-01-01T05:00:00.000Z'], shouldTriggerQuery: true });
  }


() => {
    i18n.setLocale('fr-CA'); // will be trimmed to "fr"
    filterArguments.searchTerms = ['2000-01-01T05:00:00.000Z'];
    mockColumn.filter.operator = '<=';
    const spyCallback = jest.spyOn(filterArguments, 'callback');

    filter.init(filterArguments);
    const filterInputElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish .flatpickr input.input');
    const calendarElm = document.body.querySelector<HTMLDivElement>('.flatpickr-calendar');
    const selectonOptionElms = calendarElm.querySelectorAll<HTMLSelectElement>(' .flatpickr-monthDropdown-months option');

    filter.show();

    filterInputElm.focus();
    filterInputElm.dispatchEvent(new (window.window as any).KeyboardEvent('keyup', { keyCode: 97, bubbles: true, cancelable: true }));
    const filterFilledElms = divContainer.querySelectorAll<HTMLInputElement>('.form-group.search-filter.filter-finish.filled');

    expect(filterFilledElms.length).toBe(1);
    expect(filter.currentDate).toBe('2000-01-01T05:00:00.000Z');
    expect(filterInputElm.value).toBe('2000-01-01');
    expect(spyCallback).toHaveBeenCalledWith(expect.anything(), { columnDef: mockColumn, operator: '<=', searchTerms: ['2000-01-01T05:00:00.000Z'], shouldTriggerQuery: true });
    expect(calendarElm).toBeTruthy();
    expect(selectonOptionElms.length).toBe(12);
    expect(selectonOptionElms[0].textContent).toBe('janvier');
  }


() => {
    i18n.setLocale('zx');
    const consoleSpy = jest.spyOn(global.console, 'warn').mockReturnValue();

    filterArguments.searchTerms = ['2000-01-01T05:00:00.000Z'];
    mockColumn.filter.operator = '<=';

    filter.init(filterArguments);
    const filterInputElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish .flatpickr input.input');
    const calendarElm = document.body.querySelector<HTMLDivElement>('.flatpickr-calendar');
    const selectonOptionElms = calendarElm.querySelectorAll<HTMLSelectElement>(' .flatpickr-monthDropdown-months option');

    filter.show();

    filterInputElm.focus();
    filterInputElm.dispatchEvent(new (window.window as any).KeyboardEvent('keyup', { keyCode: 97, bubbles: true, cancelable: true }));

    expect(consoleSpy).toHaveBeenCalledWith(expect.toInclude('[Aurelia-Slickgrid - CompoundDate Filter] It seems that "zx" is not a locale supported by Flatpickr'));
    expect(selectonOptionElms.length).toBe(12);
    expect(selectonOptionElms[0].textContent).toBe('January');
  }


() => {
    filterArguments.searchTerms = ['2000-01-01T05:00:00.000Z'];
    const spyCallback = jest.spyOn(filterArguments, 'callback');

    filter.init(filterArguments);
    filter.clear();
    const filterInputElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish .flatpickr input.input');
    const filterFilledElms = divContainer.querySelectorAll<HTMLInputElement>('.form-group.search-filter.filter-finish.filled');

    expect(filterInputElm.value).toBe('');
    expect(filterFilledElms.length).toBe(0);
    expect(spyCallback).toHaveBeenCalledWith(undefined, { columnDef: mockColumn, clearFilterTriggered: true, shouldTriggerQuery: true });
  }


() => {
    filterArguments.searchTerms = ['2000-01-01T05:00:00.000Z'];
    const spyCallback = jest.spyOn(filterArguments, 'callback');

    filter.init(filterArguments);
    filter.clear(false);
    const filterInputElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish .flatpickr input.input');
    const filterFilledElms = divContainer.querySelectorAll<HTMLInputElement>('.form-group.search-filter.filter-finish.filled');

    expect(filterInputElm.value).toBe('');
    expect(filterFilledElms.length).toBe(0);
    expect(spyCallback).toHaveBeenCalledWith(undefined, { columnDef: mockColumn, clearFilterTriggered: true, shouldTriggerQuery: false });
  }


() => {
    mockColumn.filter.filterOptions = { enableTime: true, allowInput: true }; // change to allow input value only for testing purposes
    mockColumn.outputType = FieldType.dateTimeIsoAmPm;
    mockColumn.filter.operator = '>';
    const spyCallback = jest.spyOn(filterArguments, 'callback');

    filter.init(filterArguments);
    const filterInputElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish .flatpickr input.input');
    filterInputElm.value = '2001-01-02T16:02:02.000+05:00';
    filterInputElm.dispatchEvent(new (window.window as any).KeyboardEvent('keydown', { keyCode: 13, bubbles: true, cancelable: true }));
    const filterFilledElms = divContainer.querySelectorAll<HTMLInputElement>('.form-group.search-filter.filter-finish.filled');

    expect(filterFilledElms.length).toBe(1);
    // expect(filter.currentDate.toISOString()).toBe('2001-01-02T21:02:02.000Z');
    expect(filterInputElm.value).toBe('2001-01-02 4:02:02 PM');
    expect(spyCallback).toHaveBeenCalledWith(expect.anything(), {
      columnDef: mockColumn, operator: '>', searchTerms: ['2001-01-02'], shouldTriggerQuery: true
    });
  }


() => {
    mockColumn.outputType = null;
    filterArguments.searchTerms = ['2000-01-01T05:00:00.000Z'];
    mockColumn.filter.operator = '<=';
    const spyCallback = jest.spyOn(filterArguments, 'callback');

    filter.init(filterArguments);
    const filterInputElm = divContainer.querySelector<HTMLInputElement>('.search-filter.filter-finish .flatpickr input.input');

    filterInputElm.focus();
    filterInputElm.dispatchEvent(new (window.window as any).KeyboardEvent('keyup', { keyCode: 97, bubbles: true, cancelable: true }));
    const filterFilledElms = divContainer.querySelectorAll<HTMLInputElement>('.form-group.search-filter.filter-finish.filled');

    expect(filterFilledElms.length).toBe(1);
    expect(filter.currentDate).toBe('2000-01-01T05:00:00.000Z');
    expect(filterInputElm.value).toBe('2000-01-01T05:00:00.000Z');
    expect(spyCallback).toHaveBeenCalledWith(expect.anything(), { columnDef: mockColumn, operator: '<=', searchTerms: ['2000-01-01T05:00:00.000Z'], shouldTriggerQuery: true });
  }


() => {
    mockColumn.outputType = null;
    filterArguments.searchTerms = ['2000-01-01T05:00:00.000Z'];

    filter.init(filterArguments);
    const filterOperatorElm = divContainer.querySelectorAll<HTMLSelectElement>('.input-group-prepend.operator select');

    expect(filterOperatorElm[0][0].title).toBe('');
    expect(removeExtraSpaces(filterOperatorElm[0][1].textContent)).toBe('= Equal to');
    expect(removeExtraSpaces(filterOperatorElm[0][2].textContent)).toBe('< Less than');
    expect(removeExtraSpaces(filterOperatorElm[0][3].textContent)).toBe('<= Less than or equal to');
    expect(removeExtraSpaces(filterOperatorElm[0][4].textContent)).toBe('> Greater than');
    expect(removeExtraSpaces(filterOperatorElm[0][5].textContent)).toBe('>= Greater than or equal to');
    expect(removeExtraSpaces(filterOperatorElm[0][6].textContent)).toBe('<> Not equal to');
  }


() => {
    beforeEach(() => {
      gridOptionMock.enableTranslate = true;
      i18n.setLocale('fr');
    });

    it('should have French text translated with operator dropdown options related to dates', () => {
      mockColumn.outputType = null;
      filterArguments.searchTerms = ['2000-01-01T05:00:00.000Z'];

      filter.init(filterArguments);
      const filterOperatorElm = divContainer.querySelectorAll<HTMLSelectElement>('.input-group-prepend.operator select');

      expect(filterOperatorElm[0][0].title).toBe('');
      expect(removeExtraSpaces(filterOperatorElm[0][1].textContent)).toBe('= Égal à');
      expect(removeExtraSpaces(filterOperatorElm[0][2].textContent)).toBe('< Plus petit que');
      expect(removeExtraSpaces(filterOperatorElm[0][3].textContent)).toBe('<= Plus petit ou égal à');
      expect(removeExtraSpaces(filterOperatorElm[0][4].textContent)).toBe('> Plus grand que');
      expect(removeExtraSpaces(filterOperatorElm[0][5].textContent)).toBe('>= Plus grand ou égal à');
      expect(removeExtraSpaces(filterOperatorElm[0][6].textContent)).toBe('<> Non égal à');
    });
  }


() => {
      gridOptionMock.enableTranslate = true;
      i18n.setLocale('fr');
    }


() => {
      mockColumn.outputType = null;
      filterArguments.searchTerms = ['2000-01-01T05:00:00.000Z'];

      filter.init(filterArguments);
      const filterOperatorElm = divContainer.querySelectorAll<HTMLSelectElement>('.input-group-prepend.operator select');

      expect(filterOperatorElm[0][0].title).toBe('');
      expect(removeExtraSpaces(filterOperatorElm[0][1].textContent)).toBe('= Égal à');
      expect(removeExtraSpaces(filterOperatorElm[0][2].textContent)).toBe('< Plus petit que');
      expect(removeExtraSpaces(filterOperatorElm[0][3].textContent)).toBe('<= Plus petit ou égal à');
      expect(removeExtraSpaces(filterOperatorElm[0][4].textContent)).toBe('> Plus grand que');
      expect(removeExtraSpaces(filterOperatorElm[0][5].textContent)).toBe('>= Plus grand ou égal à');
      expect(removeExtraSpaces(filterOperatorElm[0][6].textContent)).toBe('<> Non égal à');
    }


export class HeilbaumPhotoswipe extends ViewController {
    private _app: App;

    /**
     * Constructor of class
     *
     * @param app
     * @param data
     */
    constructor(app: App, data: any) {
        data = data || {};

        super(HeilbaumPhotoswipeComponent, data, '');
        this._app = app;
        this.isOverlay = true;
    }

    /**
     * Presents the action sheet instance.
     *
     * @param navOptions
     * @returns {Promise} Returns a promise which is resolved when the transition has completed.
     */
    present(navOptions = {}) {
        return this._app.present(this, navOptions, AppPortal.MODAL);
    }

}


@Injectable()
export class HeilbaumPhotoswipeController {

    /**
     * Constructor of class
     *
     * @param _app
     */
    constructor(private _app: App) {
    }

    /**
     * Creates a new PhotoSwipe instance
     *
     * @param items
     * @param options
     * @returns {HeilbaumPhotoswipe}
     */
    create(items: Array<PhotoswipeItem>, options: PhotoswipeOptions = {}) {
        return new HeilbaumPhotoswipe(this._app, {items, options})
    }

}


/**
     * Presents the action sheet instance.
     *
     * @param navOptions
     * @returns {Promise} Returns a promise which is resolved when the transition has completed.
     */
present(navOptions = {}) {
        return this._app.present(this, navOptions, AppPortal.MODAL);
    }


/**
     * Creates a new PhotoSwipe instance
     *
     * @param items
     * @param options
     * @returns {HeilbaumPhotoswipe}
     */
create(items: Array<PhotoswipeItem>, options: PhotoswipeOptions = {}) {
        return new HeilbaumPhotoswipe(this._app, {items, options})
    }


@Component({
  selector: 'detail',
  templateUrl: './detail.component.html'
})
export class Detail {
  constructor() {

  }

  ngOnInit() {
    console.log('hello `Detail` component');
  }

}


ngOnInit() {
    console.log('hello `Detail` component');
  }


/**
 * Flattens `array` a single level deep.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to flatten.
 * @returns {Array} Returns the new flattened array.
 * @example
 *
 * _.flatten([1, [2, [3, [4]], 5]]);
 * // => [1, 2, [3, [4]], 5]
 */
export default function flatten(array: any[], depth = 1) {
	const length = array ? array.length : 0;
	if (!length) {
		return [];
	}
	depth = depth === undefined ? 1 : toInteger(depth);
	return baseFlatten(array, depth);
}


@Injectable({
  providedIn: 'root'
})
export class TipoEstabelecimentoService {
  constructor(
    @Inject('TIPO_ESTABELECIMENTO_ENDPOINT') private tipoEndpoint: string,
    private httpClient: HttpClient
  ) { }

  getTipos(): Observable<TipoEstabelecimentoModel[]> {
    return this.httpClient.get<TipoEstabelecimentoModel[]>(this.tipoEndpoint);
  }

  getTipo(id: number): Observable<TipoEstabelecimentoModel> {
    return this.httpClient.get<TipoEstabelecimentoModel>(this.tipoEndpoint + id + '/');
  }

  adicionarTipo(_tipoEstabelecimento: TipoEstabelecimentoModel): Observable<TipoEstabelecimentoModel> {
    return this.httpClient.post<TipoEstabelecimentoModel>(this.tipoEndpoint, _tipoEstabelecimento);
  }

  editarTipo(tipo: any):  Observable<TipoEstabelecimentoModel> {
    return this.httpClient.put<TipoEstabelecimentoModel>(this.tipoEndpoint + tipo.id + '/', tipo);
  }

  // TODO resolver problema de CORS
  removerTipo(id: number): Observable<any> {
    return this.httpClient.delete(this.tipoEndpoint + `${id}`);
  }

}


getTipos(): Observable<TipoEstabelecimentoModel[]> {
    return this.httpClient.get<TipoEstabelecimentoModel[]>(this.tipoEndpoint);
  }


getTipo(id: number): Observable<TipoEstabelecimentoModel> {
    return this.httpClient.get<TipoEstabelecimentoModel>(this.tipoEndpoint + id + '/');
  }


adicionarTipo(_tipoEstabelecimento: TipoEstabelecimentoModel): Observable<TipoEstabelecimentoModel> {
    return this.httpClient.post<TipoEstabelecimentoModel>(this.tipoEndpoint, _tipoEstabelecimento);
  }


editarTipo(tipo: any):  Observable<TipoEstabelecimentoModel> {
    return this.httpClient.put<TipoEstabelecimentoModel>(this.tipoEndpoint + tipo.id + '/', tipo);
  }


// TODO resolver problema de CORS
removerTipo(id: number): Observable<any> {
    return this.httpClient.delete(this.tipoEndpoint + `${id}`);
  }


async ()=>{
        try {
          this.filesContent.push((await this.promiseReadFileAsText(files[i])).toString());
          //this.filesContent += await this.promiseReadFileAsText(files[i]);
          this.fileNames.push((i+1)+': '+files[i].name);
        } catch (e) {
          console.warn(e.message);
        }
      }


(inputFile:File)=>{
    let tempFileReader = new FileReader();
    return new Promise((resolve, reject) => {
      tempFileReader.onerror = () => {
        tempFileReader.abort();
        reject(new DOMException("Problem reading file"));
      };
      tempFileReader.onload = () => {
        resolve(tempFileReader.result);
      };
      tempFileReader.readAsText(inputFile)
    });
  }


(resolve, reject) => {
      tempFileReader.onerror = () => {
        tempFileReader.abort();
        reject(new DOMException("Problem reading file"));
      };
      tempFileReader.onload = () => {
        resolve(tempFileReader.result);
      };
      tempFileReader.readAsText(inputFile)
    }


() => {
        tempFileReader.abort();
        reject(new DOMException("Problem reading file"));
      }


() => {
        resolve(tempFileReader.result);
      }


@Component({
  selector: 'app-load-dialog',
  templateUrl: './load-dialog.component.html',
  styleUrls: ['./load-dialog.component.css']
})
export class LoadDialogComponent {
  public filesContent: string[];
  public fileNames: string[];

  constructor(public dialogRef: MatDialogRef<LoadDialogComponent>) { }

  public onCancel(){
    this.dialogRef.close();
  }

  public handleFiles(files: FileList){
    if(!files){return;}
    if(!this.filesContent){
      this.filesContent = new Array<string>();
      this.fileNames = new Array<string>();
    }
    for (let i=0, numFiles = files.length; i<numFiles;i++){
      (async ()=>{
        try {
          this.filesContent.push((await this.promiseReadFileAsText(files[i])).toString());
          //this.filesContent += await this.promiseReadFileAsText(files[i]);
          this.fileNames.push((i+1)+': '+files[i].name);
        } catch (e) {
          console.warn(e.message);
        }
      })();
    }
  }
  /* Promisify ReadFileAsText to enable string concatenation in for loop */
  private promiseReadFileAsText = (inputFile:File)=>{
    let tempFileReader = new FileReader();
    return new Promise((resolve, reject) => {
      tempFileReader.onerror = () => {
        tempFileReader.abort();
        reject(new DOMException("Problem reading file"));
      };
      tempFileReader.onload = () => {
        resolve(tempFileReader.result);
      };
      tempFileReader.readAsText(inputFile)
    });
  }
}


public onCancel(){
    this.dialogRef.close();
  }


public handleFiles(files: FileList){
    if(!files){return;}
    if(!this.filesContent){
      this.filesContent = new Array<string>();
      this.fileNames = new Array<string>();
    }
    for (let i=0, numFiles = files.length; i<numFiles;i++){
      (async ()=>{
        try {
          this.filesContent.push((await this.promiseReadFileAsText(files[i])).toString());
          //this.filesContent += await this.promiseReadFileAsText(files[i]);
          this.fileNames.push((i+1)+': '+files[i].name);
        } catch (e) {
          console.warn(e.message);
        }
      })();
    }
  }


export async function getEntities(url: string): Promise<Entity[]> {
    const { response, representation } = await Hydra.loadResource(url)
    const rootResource = representation!.root! as RdfResource

    //@ts-ignor
    const links: { supportedProperty: SupportedProperty; resources: RdfResource[] }[] = (rootResource as any).getLinks()

    const classes = links.map((l) => ({
        class: l.supportedProperty.property!.range!,
    }))

    const resUnique = links.map((l) => {
        if (l.resources.length > 1) {
            throw new Error("Multiple links?!")
        }
        return { resource: l.resources[0] }
    })

    const out = _.merge(classes, resUnique)

    return out as Entity[]
}


(l) => ({
        class: l.supportedProperty.property!.range!,
    })


(l) => {
        if (l.resources.length > 1) {
            throw new Error("Multiple links?!")
        }
        return { resource: l.resources[0] }
    }


export type Entity = { class: Class; resource: Resource }


<T, U>(f: (val: T) => U) => (arr: T[]) => arr.map(f)


(arr: T[]) => arr.map(f)


<T, U>(f: (val: T) => U) => (
  iter: ImmutableIterable<number, T>,
) => iter.map(f as (val: T | undefined) => U)


(
  iter: ImmutableIterable<number, T>,
) => iter.map(f as (val: T | undefined) => U)


<T, U>(f: (val: T) => U) => <TMonad extends Monad<T>>(
  monad: TMonad,
) =>
  resolve(
    rxMap(f),
    immutableIterableMap(f),
    arrayMap(f),
    maybeMap(f),
    iterableMap(f),
    monad,
  ) as MapMonad<TMonad, U>


<TMonad extends Monad<T>>(
  monad: TMonad,
) =>
  resolve(
    rxMap(f),
    immutableIterableMap(f),
    arrayMap(f),
    maybeMap(f),
    iterableMap(f),
    monad,
  ) as MapMonad<TMonad, U>


@Directive({
  selector: '[starkG2plotArea]',
  exportAs: 'g2plotArea'
})
export class G2plotAreaDirective implements AfterViewInit {

  @Input() options: AreaOptions;

  public instance: Area;

  constructor(
    private elementRef: ElementRef
  ) { }

  ngAfterViewInit(): void {
    const hostElement = this.elementRef.nativeElement;
    this.instance = new Area(hostElement, this.options);
    this.instance.render();
  }

  /**
   * 通过这个方法，可以增量的更新图表配置
   * @param options AreaOptions
   */
  update(options: AreaOptions): void {
    this.instance.update(options);
  }

  /**
   * 通过这个方法，可以修改图表的数据，并自动重新渲染
   * @param newData Array<object>
   */
  changeData(newData: Array<object>): void {
    this.instance.changeData(newData);
  }

  /**
   * 完全销毁整个画布，回收所有资源，仅仅保留传入的 DOM container 容器
   */
  destroy(): void {
    this.instance.destroy();
  }

}


ngAfterViewInit(): void {
    const hostElement = this.elementRef.nativeElement;
    this.instance = new Area(hostElement, this.options);
    this.instance.render();
  }


/**
   * 通过这个方法，可以增量的更新图表配置
   * @param options AreaOptions
   */
update(options: AreaOptions): void {
    this.instance.update(options);
  }


/**
   * 通过这个方法，可以修改图表的数据，并自动重新渲染
   * @param newData Array<object>
   */
changeData(newData: Array<object>): void {
    this.instance.changeData(newData);
  }


/**
   * 完全销毁整个画布，回收所有资源，仅仅保留传入的 DOM container 容器
   */
destroy(): void {
    this.instance.destroy();
  }


export async function* getExclusionsPreviewPaginate(
  config: InspectorPaginationConfiguration,
  input: GetExclusionsPreviewCommandInput,
  ...additionalArguments: any
): Paginator<GetExclusionsPreviewCommandOutput> {
  let token: string | undefined = config.startingToken || undefined;
  let hasNext = true;
  let page: GetExclusionsPreviewCommandOutput;
  while (hasNext) {
    input.nextToken = token;
    input["maxResults"] = config.pageSize;
    if (config.client instanceof Inspector) {
      page = await makePagedRequest(config.client, input, ...additionalArguments);
    } else if (config.client instanceof InspectorClient) {
      page = await makePagedClientRequest(config.client, input, ...additionalArguments);
    } else {
      throw new Error("Invalid client, expected Inspector | InspectorClient");
    }
    yield page;
    token = page.nextToken;
    hasNext = !!token;
  }
  // @ts-ignore
  return undefined;
}


async (
  client: InspectorClient,
  input: GetExclusionsPreviewCommandInput,
  ...args: any
): Promise<GetExclusionsPreviewCommandOutput> => {
  // @ts-ignore
  return await client.send(new GetExclusionsPreviewCommand(input, ...args));
}


async (
  client: Inspector,
  input: GetExclusionsPreviewCommandInput,
  ...args: any
): Promise<GetExclusionsPreviewCommandOutput> => {
  // @ts-ignore
  return await client.getExclusionsPreview(input, ...args);
}


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

  constructor(private loginService: LoginService) { }

  ngOnInit(): void {

    this.loginService.login();
  }

}


ngOnInit(): void {

    this.loginService.login();
  }


() => {
    const testDir = join(__filename, "..", "..", "..", "test_env");

    before((done) => {
        createDir(testDir).then(async () => {
            await createFile(join(testDir, "TestFirstJUnit.java"));
            await createFile(join(testDir, "TestSecondJUnit.java"));
            await createFile(join(testDir, "TestThirdJUnit.java"));
            await createFile(join(testDir, "TestFourthJUnit.java"));
            await createFile(join(testDir, "TestTenthJUnit.java"));
            await createFile(join(testDir, "TestEleventhJUnit.java"));
            await createFile(join(testDir, "TestNinethJUnit.java"));
            done();
        });
    });

    test("Should correctly put test", () => {
        const filename = join(testDir, "TestFirstJUnit.java");
        let test = new Test("firstTest", filename, new JUnitLibrary(new JavaHandler()), "TestFirstJUnit");
        writeFileSync(filename, "class TestFirstJUnit {\n\n}", "utf-8");
        test.appendTestToFile();
        const shouldBe =
            "import org.junit.*;\n\n" +
            "class TestFirstJUnit {\n\n" +
            "\t@Test\n" +
            "\tvoid firstTest() {\n" +
            "\t\t// TODO\n" +
            "\t}\n\n" +
            "}";

        assert.strictEqual(readFileSync(filename, 'utf8'), shouldBe);
    });

    test("Should put class stuff correctly", () => {
        const filename = join(testDir, "TestSecondJUnit.java");
        let test = new Test("firstTest", filename, new JUnitLibrary(new JavaHandler()), "TestSecondJUnit");
        writeFileSync(filename, "", "utf-8");
        test.appendTestToFile();
        const shouldBe =
            "import org.junit.*;\n\n" +
            "class TestSecondJUnit {\n\n" +
            "\t@Test\n" +
            "\tvoid firstTest() {\n" +
            "\t\t// TODO\n" +
            "\t}\n\n" +
            "}";

        assert.strictEqual(readFileSync(filename, 'utf8'), shouldBe);
    });

    test("Shouldn't override other test when adding inside existing suite", () => {
        const filename = join(testDir, "TestThirdJUnit.java");
        let test = new Test("thirdTest", filename, new JUnitLibrary(new JavaHandler()), "TestThirdJUnit");
        writeFileSync(filename,
            "import org.junit.*;\n\n" +
            "class TestThirdJUnit {\n\n" +
            "\t@Test\n" +
            "\tvoid firstTest() {\n" +
            "\t\t// TODO\n" +
            "\t}\n\n" +
            "}",
            { encoding: "utf8" });
        test.appendTestToFile();

        const shouldBe = "import org.junit.*;\n\n" +
            "class TestThirdJUnit {\n\n" +
            "\t@Test\n" +
            "\tvoid firstTest() {\n" +
            "\t\t// TODO\n" +
            "\t}\n\n" +
            "\t@Test\n" +
            "\tvoid thirdTest() {\n" +
            "\t\t// TODO\n" +
            "\t}\n\n" +
            "}";

        assert.strictEqual(readFileSync(filename, "utf-8"), shouldBe);
    });

    test("Shouldn't remove package keyword from the top", () => {
        const filename = join(testDir, "TestTenthJUnit.java");
        let test = new Test("tenthTest", filename, new JUnitLibrary(new JavaHandler()), "TestTenthJUnit");
        writeFileSync(filename,
            "package mypackage;\n" +
            "class TestTenthJUnit {\n\n" +
            "}", { encoding: "utf-8" });
        test.appendTestToFile();
        const shouldBe = "package mypackage;\n" +
            "import org.junit.*;\n\n" +
            "class TestTenthJUnit {\n\n" +
            "\t@Test\n" +
            "\tvoid tenthTest() {\n" +
            "\t\t// TODO\n" +
            "\t}\n\n" +
            "}";

        assert.strictEqual(readFileSync(filename, "utf-8"), shouldBe);
    });

    test("Shouldn't remove package keyword from the top without overwriting datas", () => {
        const filename = join(testDir, "TestNinethJUnit.java");
        let test = new Test("tenthTest", filename, new JUnitLibrary(new JavaHandler()), "TestNinethJUnit");
        writeFileSync(filename,
            "package mypackage;\n" +
            "class TestNinethJUnit {\n\n" +
            "}", { encoding: "utf-8" });
        test.appendTestToFile();
        const shouldBe = "package mypackage;\n" +
            "import org.junit.*;\n\n" +
            "class TestNinethJUnit {\n\n" +
            "\t@Test\n" +
            "\tvoid tenthTest() {\n" +
            "\t\t// TODO\n" +
            "\t}\n\n" +
            "}";

        assert.strictEqual(readFileSync(filename, "utf-8"), shouldBe);
    });

    test("Shouldn't import when an import contains JUnit", () => {
        const filename = join(testDir, "TestEleventhJUnit.java");
        let test = new Test("thirdTest", filename, new JUnitLibrary(new JavaHandler()), "TestEleventhJUnit");
        writeFileSync(filename,
            "import org.java.junit.*;\n\n" +
            "class TestEleventhJUnit {\n\n" +
            "\t@Test\n" +
            "\tvoid firstTest() {\n" +
            "\t\t// TODO\n" +
            "\t}\n\n" +
            "}", { encoding: "utf-8" });
        test.appendTestToFile();
        const shouldBe = "import org.java.junit.*;\n\n" +
            "class TestEleventhJUnit {\n\n" +
            "\t@Test\n" +
            "\tvoid firstTest() {\n" +
            "\t\t// TODO\n" +
            "\t}\n\n" +
            "\t@Test\n" +
            "\tvoid thirdTest() {\n" +
            "\t\t// TODO\n" +
            "\t}\n\n" +
            "}";

        assert.strictEqual(readFileSync(filename, "utf-8"), shouldBe);
    });
}


(done) => {
        createDir(testDir).then(async () => {
            await createFile(join(testDir, "TestFirstJUnit.java"));
            await createFile(join(testDir, "TestSecondJUnit.java"));
            await createFile(join(testDir, "TestThirdJUnit.java"));
            await createFile(join(testDir, "TestFourthJUnit.java"));
            await createFile(join(testDir, "TestTenthJUnit.java"));
            await createFile(join(testDir, "TestEleventhJUnit.java"));
            await createFile(join(testDir, "TestNinethJUnit.java"));
            done();
        });
    }


async () => {
            await createFile(join(testDir, "TestFirstJUnit.java"));
            await createFile(join(testDir, "TestSecondJUnit.java"));
            await createFile(join(testDir, "TestThirdJUnit.java"));
            await createFile(join(testDir, "TestFourthJUnit.java"));
            await createFile(join(testDir, "TestTenthJUnit.java"));
            await createFile(join(testDir, "TestEleventhJUnit.java"));
            await createFile(join(testDir, "TestNinethJUnit.java"));
            done();
        }