export function watchForInlineStyles(elementStyleDidChange: (element: HTMLElement) => void) {
    if (observer) {
        observer.disconnect();
    }
    observer = new MutationObserver((mutations) => {
        mutations.forEach((m) => {
            const createdInlineStyles = expand(Array.from(m.addedNodes), INLINE_STYLE_SELECTOR);
            if (createdInlineStyles.length > 0) {
                createdInlineStyles.forEach((el: HTMLElement) => elementStyleDidChange(el));
            }
            if (m.type === 'attributes') {
                if (INLINE_STYLE_ATTRS.includes(m.attributeName)) {
                    elementStyleDidChange(m.target as HTMLElement);
                }
                overridesList
                    .filter(({store, dataAttr}) => store.has(m.target) && !(m.target as HTMLElement).hasAttribute(dataAttr))
                    .forEach(({dataAttr}) => (m.target as HTMLElement).setAttribute(dataAttr, ''));
            }
        });
    });
    observer.observe(document, {
        childList: true,
        subtree: true,
        attributes: true,
        attributeFilter: INLINE_STYLE_ATTRS.concat(overridesList.map(({dataAttr}) => dataAttr)),
    });
}


export function stopWatchingForInlineStyles() {
    if (observer) {
        observer.disconnect();
        observer = null;
    }
}


function getInlineStyleCacheKey(el: HTMLElement, theme: FilterConfig) {
    return INLINE_STYLE_ATTRS
        .map((attr) => `${attr}="${el.getAttribute(attr)}"`)
        .concat(filterProps.map((prop) => `${prop}="${theme[prop]}"`))
        .join(' ');
}


export function overrideInlineStyle(element: HTMLElement, theme: FilterConfig) {
    const cacheKey = getInlineStyleCacheKey(element, theme);
    if (cacheKey === inlineStyleCache.get(element)) {
        return;
    }

    const unsetProps = new Set(Object.keys(overrides));

    function setCustomProp(targetCSSProp: string, modifierCSSProp: string, cssVal: string) {
        const {customProp, dataAttr} = overrides[targetCSSProp];

        const mod = getModifiableCSSDeclaration(modifierCSSProp, cssVal, null, null);
        if (!mod) {
            return;
        }
        let value = mod.value;
        if (typeof value === 'function') {
            value = value(theme) as string;
        }
        element.style.setProperty(customProp, value as string);
        if (!element.hasAttribute(dataAttr)) {
            element.setAttribute(dataAttr, '');
        }
        unsetProps.delete(targetCSSProp);
    }

    if (element.hasAttribute('bgcolor')) {
        let value = element.getAttribute('bgcolor');
        if (value.match(/^[0-9a-f]{3}$/i) || value.match(/^[0-9a-f]{6}$/i)) {
            value = `#${value}`;
        }
        setCustomProp('background-color', 'background-color', value);
    }
    if (element.hasAttribute('color')) {
        let value = element.getAttribute('color');
        if (value.match(/^[0-9a-f]{3}$/i) || value.match(/^[0-9a-f]{6}$/i)) {
            value = `#${value}`;
        }
        setCustomProp('color', 'color', value);
    }
    if (element.hasAttribute('fill') && element instanceof SVGElement) {
        const SMALL_SVG_LIMIT = 32;
        let value = element.getAttribute('fill');
        let isBg = false;
        if (!(element instanceof SVGTextElement)) {
            const {width, height} = element.getBoundingClientRect();
            isBg = (width > SMALL_SVG_LIMIT || height > SMALL_SVG_LIMIT);
        }
        setCustomProp('fill', isBg ? 'background-color' : 'color', value);
    }
    if (element.hasAttribute('stroke')) {
        let value = element.getAttribute('stroke');
        setCustomProp('stroke', element instanceof SVGLineElement || element instanceof SVGTextElement ? 'border-color' : 'color', value);
    }
    element.style && iterateCSSDeclarations(element.style, (property, value) => {
        // Temporaty ignore background images
        // due to possible performance issues
        // and complexity of handling async requests
        if (property === 'background-image' && value.indexOf('url') >= 0) {
            return;
        }
        if (overrides.hasOwnProperty(property)) {
            setCustomProp(property, property, value);
        }
    });
    if (element.style && element instanceof SVGTextElement && element.style.fill) {
        setCustomProp('fill', 'color', element.style.getPropertyValue('fill'));
    }

    Array.from(unsetProps).forEach((cssProp) => {
        const {store, dataAttr} = overrides[cssProp];
        store.delete(element);
        element.removeAttribute(dataAttr);
    });
    inlineStyleCache.set(element, getInlineStyleCacheKey(element, theme));
}


function setCustomProp(targetCSSProp: string, modifierCSSProp: string, cssVal: string) {
        const {customProp, dataAttr} = overrides[targetCSSProp];

        const mod = getModifiableCSSDeclaration(modifierCSSProp, cssVal, null, null);
        if (!mod) {
            return;
        }
        let value = mod.value;
        if (typeof value === 'function') {
            value = value(theme) as string;
        }
        element.style.setProperty(customProp, value as string);
        if (!element.hasAttribute(dataAttr)) {
            element.setAttribute(dataAttr, '');
        }
        unsetProps.delete(targetCSSProp);
    }


(attr) => `[${attr}]`


({dataAttr, customProp, cssProp}) => {
        return [
            `[${dataAttr}] {`,
            `  ${cssProp}: var(${customProp}) !important;`,
            '}',
        ].join('\n');
    }


(n) => {
        if (n instanceof Element) {
            if (n.matches(selector)) {
                results.push(n);
            }
            results.push(...Array.from(n.querySelectorAll(selector)));
        }
    }


(mutations) => {
        mutations.forEach((m) => {
            const createdInlineStyles = expand(Array.from(m.addedNodes), INLINE_STYLE_SELECTOR);
            if (createdInlineStyles.length > 0) {
                createdInlineStyles.forEach((el: HTMLElement) => elementStyleDidChange(el));
            }
            if (m.type === 'attributes') {
                if (INLINE_STYLE_ATTRS.includes(m.attributeName)) {
                    elementStyleDidChange(m.target as HTMLElement);
                }
                overridesList
                    .filter(({store, dataAttr}) => store.has(m.target) && !(m.target as HTMLElement).hasAttribute(dataAttr))
                    .forEach(({dataAttr}) => (m.target as HTMLElement).setAttribute(dataAttr, ''));
            }
        });
    }


(m) => {
            const createdInlineStyles = expand(Array.from(m.addedNodes), INLINE_STYLE_SELECTOR);
            if (createdInlineStyles.length > 0) {
                createdInlineStyles.forEach((el: HTMLElement) => elementStyleDidChange(el));
            }
            if (m.type === 'attributes') {
                if (INLINE_STYLE_ATTRS.includes(m.attributeName)) {
                    elementStyleDidChange(m.target as HTMLElement);
                }
                overridesList
                    .filter(({store, dataAttr}) => store.has(m.target) && !(m.target as HTMLElement).hasAttribute(dataAttr))
                    .forEach(({dataAttr}) => (m.target as HTMLElement).setAttribute(dataAttr, ''));
            }
        }


(el: HTMLElement) => elementStyleDidChange(el)


({store, dataAttr}) => store.has(m.target) && !(m.target as HTMLElement).hasAttribute(dataAttr)


({dataAttr}) => (m.target as HTMLElement).setAttribute(dataAttr, '')


({dataAttr}) => dataAttr


(attr) => `${attr}="${el.getAttribute(attr)}"`


(prop) => `${prop}="${theme[prop]}"`


(property, value) => {
        // Temporaty ignore background images
        // due to possible performance issues
        // and complexity of handling async requests
        if (property === 'background-image' && value.indexOf('url') >= 0) {
            return;
        }
        if (overrides.hasOwnProperty(property)) {
            setCustomProp(property, property, value);
        }
    }


(cssProp) => {
        const {store, dataAttr} = overrides[cssProp];
        store.delete(element);
        element.removeAttribute(dataAttr);
    }


interface Overrides {
    [cssProp: string]: {
        customProp: string;
        cssProp: string;
        dataAttr: string;
        store: WeakSet<Node>;
    };
}


/**
 * Contains a tag and either a Hash or set of opcodes
 */
export class Lock {
    /**
     * Specifies the type of lock script
     */
    public type: LockType;

    /**
     * May either be a Hash, or a sequence of opcodes
     */
    public bytes: Buffer;

    /**
     * Constructor
     * @param type  Specifies the type of lock script
     * @param data May either be a Hash, or a sequence of opcodes
     */
    constructor(type: LockType, data: Buffer | string) {
        this.type = type;
        if (typeof data === "string") this.bytes = Buffer.from(data, "base64");
        else this.bytes = Buffer.from(data);
    }

    /**
     * The reviver parameter to give to `JSON.parse`
     * @param key   Name of the field being parsed
     * @param value The value associated with `key`
     * @returns A new instance of `Lock` if `key == ""`, `value` otherwise.
     */
    public static reviver(key: string, value: any): any {
        if (key !== "") return value;

        JSONValidator.isValidOtherwiseThrow("Lock", value);
        return new Lock(value.type, value.bytes);
    }

    /**
     * Collects data to create a hash.
     * @param buffer The buffer where collected data is stored
     */
    public computeHash(buffer: SmartBuffer) {
        buffer.writeUInt8(this.type);
        hashPart(this.bytes, buffer);
    }

    /**
     * Generates a LockType.Key lock script.
     * @param key the public key which can unlock this lock script
     * @returns The lock script
     */
    public static fromPublicKey(key: PublicKey): Lock {
        return new Lock(LockType.Key, key.data);
    }

    /**
     * The bytes consisting of null values for all bytes.
     * @returns The instance of Unlock
     */
    public static get Null(): Lock {
        return new Lock(LockType.Key, Buffer.alloc(0));
    }

    /**
     * Converts this object to its JSON representation
     */
    public toJSON(): any {
        return {
            type: this.type,
            bytes: this.bytes.toString("base64"),
        };
    }

    /**
     * Returns the data size.
     */
    public getNumberOfBytes(): number {
        return (
            Utils.SIZE_OF_BYTE + // Lock.type
            this.bytes.length
        ); // Lock.bytes
    }

    /**
     * Serialize as binary data.
     * @param buffer - The buffer where serialized data is stored
     */
    public serialize(buffer: SmartBuffer) {
        VarInt.fromNumber(this.type, buffer, 1);
        VarInt.fromNumber(this.bytes.length, buffer);
        buffer.writeBuffer(this.bytes);
    }

    /**
     * Deserialize as binary data.
     * @param buffer - The buffer to be deserialized
     */
    public static deserialize(buffer: SmartBuffer): Lock {
        const type = VarInt.toNumber(buffer, 1);
        const length = VarInt.toNumber(buffer);
        return new Lock(type, Utils.readBuffer(buffer, length));
    }

    /**
     * Creates and returns a copy of this object.
     */
    public clone(): Lock {
        return new Lock(this.type, this.bytes);
    }
}


/**
 * Contains a data tuple or a set of push opcodes
 */
export class Unlock {
    /**
     * May be: <signature>, <signature, key>, <key, push opcodes>
     */
    public bytes: Buffer;

    /**
     * Constructor
     * @param data May be: <signature>, <signature, key>, <key, push opcodes>
     */
    constructor(data: Buffer | string) {
        if (typeof data === "string") this.bytes = Buffer.from(data, "base64");
        else this.bytes = Buffer.from(data);
    }

    /**
     * The reviver parameter to give to `JSON.parse`
     * @param key   Name of the field being parsed
     * @param value The value associated with `key`
     * @returns A new instance of `Unlock` if `key == ""`, `value` otherwise.
     */
    public static reviver(key: string, value: any): any {
        if (key !== "") return value;

        JSONValidator.isValidOtherwiseThrow("Unlock", value);
        return new Unlock(value.bytes);
    }

    /**
     * Collects data to create a hash.
     * @param buffer The buffer where collected data is stored
     */
    public computeHash(buffer: SmartBuffer) {
        buffer.writeBuffer(this.bytes);
    }

    /**
     * Generates a LockType.Key unlock script.
     * @param sig The signature that will be embedded in the script
     * @returns The unlock script
     */
    public static fromSignature(sig: Signature): Unlock {
        return Unlock.fromSigPair(new SigPair(sig));
    }

    /**
     * Generates a LockType.Key unlock script.
     * @param sig The instance of SigPair that will be embedded in the script
     * @returns The unlock script
     */
    public static fromSigPair(sig: SigPair): Unlock {
        return new Unlock(sig.encode());
    }

    /**
     * The bytes consisting of null values for all bytes.
     * @returns The instance of Unlock
     */
    public static get Null(): Unlock {
        return new Unlock(Buffer.alloc(0));
    }

    /**
     * Converts this object to its JSON representation
     */
    public toJSON(): any {
        return {
            bytes: this.bytes.toString("base64"),
        };
    }

    /**
     * Returns the data size.
     */
    public getNumberOfBytes(): number {
        return this.bytes.length; // Unlock.bytes
    }

    /**
     * Serialize as binary data.
     * @param buffer - The buffer where serialized data is stored
     */
    public serialize(buffer: SmartBuffer) {
        VarInt.fromNumber(this.bytes.length, buffer);
        buffer.writeBuffer(this.bytes);
    }

    /**
     * Deserialize as binary data.
     * @param buffer - The buffer to be deserialized
     */
    public static deserialize(buffer: SmartBuffer): Unlock {
        const length = VarInt.toNumber(buffer);
        return new Unlock(Utils.readBuffer(buffer, length));
    }

    /**
     * Creates and returns a copy of this object.
     */
    public clone(): Unlock {
        return new Unlock(this.bytes);
    }
}


/**
 * The input lock types. 1 Byte unsigned integer
 */
export enum LockType {
    /// lock is a 64-byte public key, unlock is the signature
    Key = 0x00,

    /// lock is a 64-byte public key hash, unlock is a (sig, key) pair
    KeyHash = 0x01,

    /// lock is a script, unlock may be anything required by the lock script
    Script = 0x02,

    /// lock is a 64-byte hash of a script, unlock is the script containing
    /// only stack pushes which will push the redeem script last
    Redeem = 0x03,
}


/**
     * The reviver parameter to give to `JSON.parse`
     * @param key   Name of the field being parsed
     * @param value The value associated with `key`
     * @returns A new instance of `Lock` if `key == ""`, `value` otherwise.
     */
public static reviver(key: string, value: any): any {
        if (key !== "") return value;

        JSONValidator.isValidOtherwiseThrow("Lock", value);
        return new Lock(value.type, value.bytes);
    }


/**
     * Collects data to create a hash.
     * @param buffer The buffer where collected data is stored
     */
public computeHash(buffer: SmartBuffer) {
        buffer.writeUInt8(this.type);
        hashPart(this.bytes, buffer);
    }


/**
     * Generates a LockType.Key lock script.
     * @param key the public key which can unlock this lock script
     * @returns The lock script
     */
public static fromPublicKey(key: PublicKey): Lock {
        return new Lock(LockType.Key, key.data);
    }


/**
     * Converts this object to its JSON representation
     */
public toJSON(): any {
        return {
            type: this.type,
            bytes: this.bytes.toString("base64"),
        };
    }


/**
     * Returns the data size.
     */
public getNumberOfBytes(): number {
        return (
            Utils.SIZE_OF_BYTE + // Lock.type
            this.bytes.length
        ); // Lock.bytes
    }


/**
     * Serialize as binary data.
     * @param buffer - The buffer where serialized data is stored
     */
public serialize(buffer: SmartBuffer) {
        VarInt.fromNumber(this.type, buffer, 1);
        VarInt.fromNumber(this.bytes.length, buffer);
        buffer.writeBuffer(this.bytes);
    }


/**
     * Deserialize as binary data.
     * @param buffer - The buffer to be deserialized
     */
public static deserialize(buffer: SmartBuffer): Lock {
        const type = VarInt.toNumber(buffer, 1);
        const length = VarInt.toNumber(buffer);
        return new Lock(type, Utils.readBuffer(buffer, length));
    }


/**
     * Creates and returns a copy of this object.
     */
public clone(): Lock {
        return new Lock(this.type, this.bytes);
    }


/**
     * The reviver parameter to give to `JSON.parse`
     * @param key   Name of the field being parsed
     * @param value The value associated with `key`
     * @returns A new instance of `Unlock` if `key == ""`, `value` otherwise.
     */
public static reviver(key: string, value: any): any {
        if (key !== "") return value;

        JSONValidator.isValidOtherwiseThrow("Unlock", value);
        return new Unlock(value.bytes);
    }


/**
     * Collects data to create a hash.
     * @param buffer The buffer where collected data is stored
     */
public computeHash(buffer: SmartBuffer) {
        buffer.writeBuffer(this.bytes);
    }


/**
     * Generates a LockType.Key unlock script.
     * @param sig The signature that will be embedded in the script
     * @returns The unlock script
     */
public static fromSignature(sig: Signature): Unlock {
        return Unlock.fromSigPair(new SigPair(sig));
    }


/**
     * Generates a LockType.Key unlock script.
     * @param sig The instance of SigPair that will be embedded in the script
     * @returns The unlock script
     */
public static fromSigPair(sig: SigPair): Unlock {
        return new Unlock(sig.encode());
    }


/**
     * Converts this object to its JSON representation
     */
public toJSON(): any {
        return {
            bytes: this.bytes.toString("base64"),
        };
    }


/**
     * Returns the data size.
     */
public getNumberOfBytes(): number {
        return this.bytes.length; // Unlock.bytes
    }


/**
     * Serialize as binary data.
     * @param buffer - The buffer where serialized data is stored
     */
public serialize(buffer: SmartBuffer) {
        VarInt.fromNumber(this.bytes.length, buffer);
        buffer.writeBuffer(this.bytes);
    }


/**
     * Deserialize as binary data.
     * @param buffer - The buffer to be deserialized
     */
public static deserialize(buffer: SmartBuffer): Unlock {
        const length = VarInt.toNumber(buffer);
        return new Unlock(Utils.readBuffer(buffer, length));
    }


/**
     * Creates and returns a copy of this object.
     */
public clone(): Unlock {
        return new Unlock(this.bytes);
    }


/**
 * The `vsphere_tag` data source can be used to reference tags that are not
 * managed by Terraform. Its attributes are exactly the same as the [`vsphere_tag`
 * resource][resource-tag], and, like importing, the data source takes a name and
 * category to search on. The `id` and other attributes are then populated with
 * the data found by the search.
 *
 * [resource-tag]: /docs/providers/vsphere/r/tag.html
 *
 * ~> **NOTE:** Tagging support is unsupported on direct ESXi connections and
 * requires vCenter 6.0 or higher.
 */
export declare function getTag(args: GetTagArgs, opts?: pulumi.InvokeOptions): Promise<GetTagResult>;


/**
 * A collection of arguments for invoking getTag.
 */
export interface GetTagArgs {
    /**
     * The ID of the tag category the tag is located in.
     */
    readonly categoryId: string;
    /**
     * The name of the tag.
     */
    readonly name: string;
}


/**
 * A collection of values returned by getTag.
 */
export interface GetTagResult {
    readonly description: string;
    /**
     * id is the provider-assigned unique ID for this managed resource.
     */
    readonly id: string;
}


async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 전역 범위 파이프
  app.useGlobalPipes(new ValidationPipe());

  await app.listen(3000);
}


elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)


k => httpParams = this.addToHttpParamsRecursive(
                    httpParams, value[k], key != null ? `${key}.${k}` : k)


private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
        if (typeof value === "object" && value instanceof Date === false) {
            httpParams = this.addToHttpParamsRecursive(httpParams, value);
        } else {
            httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
        }
        return httpParams;
    }


private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
        if (value == null) {
            return httpParams;
        }

        if (typeof value === "object") {
            if (Array.isArray(value)) {
                (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
            } else if (value instanceof Date) {
                if (key != null) {
                    httpParams = httpParams.append(key,
                        (value as Date).toISOString().substr(0, 10));
                } else {
                   throw Error("key may not be null if value is Date");
                }
            } else {
                Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive(
                    httpParams, value[k], key != null ? `${key}.${k}` : k));
            }
        } else if (key != null) {
            httpParams = httpParams.append(key, value);
        } else {
            throw Error("key may not be null if value is not object or array");
        }
        return httpParams;
    }


/**
     * @param limit
     * @param offset
     * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
     * @param reportProgress flag to report request and response progress.
     */
public encounterConditionList(limit?: number, offset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain', context?: HttpContext}): Observable<string>;


public encounterConditionList(limit?: number, offset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain', context?: HttpContext}): Observable<HttpResponse<string>>;


public encounterConditionList(limit?: number, offset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain', context?: HttpContext}): Observable<HttpEvent<string>>;


public encounterConditionList(limit?: number, offset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'text/plain', context?: HttpContext}): Observable<any> {

        let localVarQueryParameters = new HttpParams({encoder: this.encoder});
        if (limit !== undefined && limit !== null) {
          localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
            <any>limit, 'limit');
        }
        if (offset !== undefined && offset !== null) {
          localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
            <any>offset, 'offset');
        }

        let localVarHeaders = this.defaultHeaders;

        let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
        if (localVarHttpHeaderAcceptSelected === undefined) {
            // to determine the Accept header
            const httpHeaderAccepts: string[] = [
                'text/plain'
            ];
            localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
        }
        if (localVarHttpHeaderAcceptSelected !== undefined) {
            localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
        }

        let localVarHttpContext: HttpContext | undefined = options && options.context;
        if (localVarHttpContext === undefined) {
            localVarHttpContext = new HttpContext();
        }

        let responseType_: 'text' | 'json' | 'blob' = 'json';
        if (localVarHttpHeaderAcceptSelected) {
            if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
                responseType_ = 'text';
            } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
                responseType_ = 'json';
            } else {
                responseType_ = 'blob';
            }
        }

        return this.httpClient.get<string>(`${this.configuration.basePath}/api/v2/encounter-condition/`,
            {
                context: localVarHttpContext,
                params: localVarQueryParameters,
                responseType: <any>responseType_,
                withCredentials: this.configuration.withCredentials,
                headers: localVarHeaders,
                observe: observe,
                reportProgress: reportProgress
            }
        );
    }


/**
     * @param id
     * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
     * @param reportProgress flag to report request and response progress.
     */
public encounterConditionRead(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain', context?: HttpContext}): Observable<string>;


public encounterConditionRead(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain', context?: HttpContext}): Observable<HttpResponse<string>>;


public encounterConditionRead(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain', context?: HttpContext}): Observable<HttpEvent<string>>;


public encounterConditionRead(id: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'text/plain', context?: HttpContext}): Observable<any> {
        if (id === null || id === undefined) {
            throw new Error('Required parameter id was null or undefined when calling encounterConditionRead.');
        }

        let localVarHeaders = this.defaultHeaders;

        let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
        if (localVarHttpHeaderAcceptSelected === undefined) {
            // to determine the Accept header
            const httpHeaderAccepts: string[] = [
                'text/plain'
            ];
            localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
        }
        if (localVarHttpHeaderAcceptSelected !== undefined) {
            localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
        }

        let localVarHttpContext: HttpContext | undefined = options && options.context;
        if (localVarHttpContext === undefined) {
            localVarHttpContext = new HttpContext();
        }

        let responseType_: 'text' | 'json' | 'blob' = 'json';
        if (localVarHttpHeaderAcceptSelected) {
            if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
                responseType_ = 'text';
            } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
                responseType_ = 'json';
            } else {
                responseType_ = 'blob';
            }
        }

        return this.httpClient.get<string>(`${this.configuration.basePath}/api/v2/encounter-condition/${encodeURIComponent(String(id))}/`,
            {
                context: localVarHttpContext,
                responseType: <any>responseType_,
                withCredentials: this.configuration.withCredentials,
                headers: localVarHeaders,
                observe: observe,
                reportProgress: reportProgress
            }
        );
    }


()=>{
    const state = getState();
    const name = state.modalName;
    return(
        <>
        {
            name == "" ? <></>
            :name == "feed" ? <FeedModal></FeedModal>
            : <></>
        }


() => {
      console.info('AssetRangeInput mounted!');
    }


() => {
    const _value_input = '' as string | number;
    const _value_slider = 0 as string | number;
    return {
      _value_input,
      _value_slider
    };
  }


() => this.$forceUpdate()


export interface INPUT_TIPS {
  amount?: number;
  amountSymbol?: string;
  tipLeft?: string;
  tipRight: string;
}


export type ERROR = string | ((value: number | string) => string | VNode) | VNode;


setup(props) {
    const classes = classnames(props.prefixCls);

    onMounted(() => {
      console.info('AssetRangeInput mounted!');
    });

    return {
      classes
    };
  }


get(): MixinAsset {
        return this.asset;
      }


set(val) {
        this.$emit('update:asset', val);
      }


hasInputLeftTips(): boolean {
      return !!(this.inputTips?.amount || this.inputTips?.amountSymbol || this.inputTips?.tipLeft);
    }


hasUpperLimit(): number {
      return this.max && (1 / this.max);
    }


created() {
    if (!this.isInRange(+this.value)) this.$emit('error:limit');
    this._value_input = this.value;
    this.setSliderValueWithLimit(+this.value);
  }


isInRange(val: number) {
      return val >= this.min && (!this.hasUpperLimit || val <= this.max);
    }


setSliderValueWithLimit(val: number) {
      if (this.hasUpperLimit && typeof val === 'number') {
        let _val = val / this.max * 100;
        if (_val > 100) _val = 100;
        if (_val < 0) _val = 0;
        this._value_slider = format({
          n: _val,
          p: 2
        });
      }
    }


render(h: CreateElement): VNode {
    const btn = this.$slots.button;
    const slider = this.$slots.slider;
    const inputTips = this.$slots.inputTips;
    const sliderTips = this.$slots.sliderTips;
    const scopedSlots = {
      activator: this.$scopedSlots.activator
    };

    return (
      <VLayout
        class={this.classes()}
        attrs={{
          column: true,
          'align-center': true
        }}


if (!this


function UnavailableMessage(props: {icon: ComponentType; children: ReactNode; title: ReactNode}) {
  const Icon = props.icon
  return (
    <Flex padding={3}>
      <Box>
        <Text size={1}>
          <Icon />
        </Text>
      </Box>
      <Box flex={1} marginLeft={3}>
        <Text size={1} weight="semibold">
          {props.title}
        </Text>

        <Box marginTop={3}>
          <Text as="p" muted size={1}>
            {props.children}
          </Text>
        </Box>
      </Box>
    </Flex>
  )
}


/**
 * Used to preview a referenced type
 * Takes the reference type as props
 * @param props
 * @constructor
 */
export function ReferencePreview(props: {
  availability: DocumentAvailability
  id: string
  preview: {draft: DocumentPreview | undefined; published: DocumentPreview | undefined}
  refType: ObjectSchemaType
  layout: string
  showTypeLabel: boolean
}) {
  const {layout, refType, showTypeLabel, availability, preview, id} = props

  const theme = useRootTheme()

  const notFound = availability.reason === 'NOT_FOUND'
  const insuficcientPermissions = availability.reason === 'PERMISSION_DENIED'

  const previewId = preview.draft?._id || preview.published?._id

  // Note: we can't pass the preview values as-is to the Preview-component here since it's a "prepared" value and the
  // Preview component expects the "raw"/unprepared value. By passing only _id and _type we make sure the Preview-component
  // resolve the preview value it needs (this is cached in the runtime, so not likely to cause any fetch overhead)
  const previewStub = useMemo(() => ({_id: previewId, _type: refType.name}), [
    previewId,
    refType.name,
  ])

  return (
    <Flex align="center">
      {availability.available ? (
        <Box flex={1}>
          <Preview type={refType} value={previewStub} layout={layout} />
        </Box>
      ) : (
        <Box flex={1}>
          <Flex align="center">
            <Box flex={1} paddingY={2}>
              <Text muted>Document unavailable</Text>
            </Box>
          </Flex>
        </Box>
      )}


() => ({_id: previewId, _type: refType.name})


notFound ? (
                    <UnavailableMessage title="Not found" icon={HelpCircleIcon}>
                      The referenced document does not exist
                      <br


function getIdentifier(element: HTMLElement) {
  return (
    element.id ||
    element.getAttribute("aria-label") ||
    element.ownerDocument?.getElementById(
      element.getAttribute("aria-labelledby") || ""
    )?.textContent ||
    element.textContent
  );
}


export function useAllEvents(ref: React.RefObject<Element>, stack: string[]) {
  React.useEffect(() => {
    const element = ref.current;
    if (!element) return undefined;
    const handler = (event: Event) =>
      stack.push(`${event.type} ${getIdentifier(event.target as HTMLElement)}`);
    eventNames.forEach((event) => element.addEventListener(event, handler));
    return () => {
      eventNames.forEach((event) =>
        element.removeEventListener(event, handler)
      );
    };
  }, [ref]);
}


() => {
    const element = ref.current;
    if (!element) return undefined;
    const handler = (event: Event) =>
      stack.push(`${event.type} ${getIdentifier(event.target as HTMLElement)}`);
    eventNames.forEach((event) => element.addEventListener(event, handler));
    return () => {
      eventNames.forEach((event) =>
        element.removeEventListener(event, handler)
      );
    };
  }


(event: Event) =>
      stack.push(`${event.type} ${getIdentifier(event.target as HTMLElement)}`)


(event) => element.addEventListener(event, handler)


() => {
      eventNames.forEach((event) =>
        element.removeEventListener(event, handler)
      );
    }


(event) =>
        element.removeEventListener(event, handler)


(): ProfilesFiltersContextInterface => {
  const context = useContext(ProfilesFiltersContext);
  if (context === undefined) {
    throw new Error('useProfilesFilterContext must be used within a ProfilesFiltersContext');
  }
  return context;
}


({ children, trial }: Props) => {
  const { settings, updateSettings } = useSettings<Settings>(settingsConfig);
  const systemSeries = useFetchAvailableSeries(trial.id)[MetricType.System];
  const systemMetrics = useFetchMetrics(
    trial.id,
    MetricType.System,
    settings.name,
    settings.agentId,
    settings.gpuUuid,
  );
  const throughputMetrics = useFetchMetrics(
    trial.id,
    MetricType.Throughput,
    'samples_per_second',
    undefined,
    undefined,
  );
  const timingMetrics = useFetchMetrics(trial.id, MetricType.Timing);

  const canRender = !!settings.agentId && !!settings.name && !!systemSeries;

  /*
   * Set default filter settings.
   */
  useEffect(() => {
    if (!systemSeries || (settings.agentId && settings.name)) return;

    const newSettings: Partial<Settings> = {};

    if (!settings.name) {
      if (Object.keys(systemSeries).includes('gpu_util')) newSettings.name = 'gpu_util';
      else if (Object.keys(systemSeries).includes('cpu_util')) newSettings.name = 'cpu_util';
      else newSettings.name = Object.keys(systemSeries)[0];
    }

    if (!settings.agentId) {
      newSettings.agentId = Object.keys(systemSeries[newSettings.name as unknown as string])[0];
    }

    if (Object.keys(newSettings).length !== 0) updateSettings(newSettings);
  }, [ settings.agentId, settings.name, systemSeries, updateSettings ]);

  const context = useMemo<ProfilesFiltersContextInterface>(() => ({
    metrics: {
      [MetricType.System]: systemMetrics,
      [MetricType.Throughput]: throughputMetrics,
      [MetricType.Timing]: timingMetrics,
    },
    settings,
    systemSeries,
    updateSettings,
  }), [ settings, systemMetrics, systemSeries, throughputMetrics, timingMetrics, updateSettings ]);

  if (!canRender) {
    return <Alert message="No data available." type="warning" />;
  }

  return (
    <ProfilesFiltersContext.Provider value={context}>
      {children}
    </ProfilesFiltersContext.Provider>


() => {
    if (!systemSeries || (settings.agentId && settings.name)) return;

    const newSettings: Partial<Settings> = {};

    if (!settings.name) {
      if (Object.keys(systemSeries).includes('gpu_util')) newSettings.name = 'gpu_util';
      else if (Object.keys(systemSeries).includes('cpu_util')) newSettings.name = 'cpu_util';
      else newSettings.name = Object.keys(systemSeries)[0];
    }

    if (!settings.agentId) {
      newSettings.agentId = Object.keys(systemSeries[newSettings.name as unknown as string])[0];
    }

    if (Object.keys(newSettings).length !== 0) updateSettings(newSettings);
  }


() => ({
    metrics: {
      [MetricType.System]: systemMetrics,
      [MetricType.Throughput]: throughputMetrics,
      [MetricType.Timing]: timingMetrics,
    },
    settings,
    systemSeries,
    updateSettings,
  })


export interface ProfilesFiltersInterface {
  agentId?: string;
  gpuUuid?: string;
  name?: string;
}


export interface ProfilesFiltersContextInterface {
  metrics: Record<MetricType, MetricsAggregateInterface>,
  settings: Settings,
  systemSeries: AvailableSeriesType,
  updateSettings: (newSettings: Partial<Settings>, push?: boolean) => void;
}


interface Props {
  children: React.ReactNode;
  trial: TrialDetails;
}


() => {
  let component: VariantFilterBarComponent;
  let fixture: ComponentFixture<VariantFilterBarComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: SpecService.imports,
      declarations: [VariantFilterBarComponent]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(VariantFilterBarComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
}


async () => {
    await TestBed.configureTestingModule({
      imports: SpecService.imports,
      declarations: [VariantFilterBarComponent]
    })
      .compileComponents();
  }


() => {
    fixture = TestBed.createComponent(VariantFilterBarComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }


() => {
    it('handle empty inputs', () => {
        expect(getAirConditioningEmission(EmptyEmissionInput)).toEqual(jasmine.objectContaining({ emission_gCO2e: 0 }));
    });
}


() => {
        expect(getAirConditioningEmission(EmptyEmissionInput)).toEqual(jasmine.objectContaining({ emission_gCO2e: 0 }));
    }


(args: any[]) => {
      if (args?.length > 0) {
        const originalArgs = [];
        originalArgs.push(...process.argv.splice(2, process.argv.length - 2, ...args));
        return () => {
          process.argv.splice(2, args.length, ...originalArgs)
        };
      } else {
        return () => {};
      }
    }


() => {
          process.argv.splice(2, args.length, ...originalArgs)
        }


async execute(task: BuildPipeFromFileTask, context: ExecutorContext): Promise<{ success: boolean }> {
    const filePath = Path.join(context.root, task.path);

    const loader = LOADERS[Path.extname(filePath)];
    if (!loader) {
      logger.error(`Error Running Task: Unsupported file ${task.path}.`);
      return { success: false };
    }

    const modifyArgs = (args: any[]) => {
      if (args?.length > 0) {
        const originalArgs = [];
        originalArgs.push(...process.argv.splice(2, process.argv.length - 2, ...args));
        return () => {
          process.argv.splice(2, args.length, ...originalArgs)
        };
      } else {
        return () => {};
      }
    }

    try {
      const unModify = modifyArgs(task.args);
      const dynamicTask = loader(filePath);
      unModify();
      if (!dynamicTask) {
        throw new Error(`Invalid task loaded from file "${task.path}"`);
      }
      return runTask(dynamicTask, context);
    } catch (err) {
      logger.error(`Error Running Task: ${err.message}`);
      return { success: false };
    }
  }


getDescription(task: BuildPipeFromFileTask): string { return task.path; }


/**
 *
Updates the image scanning configuration for the specified repository.

 * @example
 * Use a bare-bones client and the command you need to make an API call.
 * ```javascript
 * import { ECRClient, PutImageScanningConfigurationCommand } from "@aws-sdk/client-ecr"; // ES Modules import
 * // const { ECRClient, PutImageScanningConfigurationCommand } = require("@aws-sdk/client-ecr"); // CommonJS import
 * const client = new ECRClient(config);
 * const command = new PutImageScanningConfigurationCommand(input);
 * const response = await client.send(command);
 * ```
 *
 * @see {@link PutImageScanningConfigurationCommandInput} for command's `input` shape.
 * @see {@link PutImageScanningConfigurationCommandOutput} for command's `response` shape.
 * @see {@link ECRClientResolvedConfig | config} for ECRClient's `config` shape.
 *
 */
export class PutImageScanningConfigurationCommand extends $Command<
  PutImageScanningConfigurationCommandInput,
  PutImageScanningConfigurationCommandOutput,
  ECRClientResolvedConfig
> {
  // Start section: command_properties
  // End section: command_properties

  constructor(readonly input: PutImageScanningConfigurationCommandInput) {
    // Start section: command_constructor
    super();
    // End section: command_constructor
  }

  /**
   * @internal
   */
  resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: ECRClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<PutImageScanningConfigurationCommandInput, PutImageScanningConfigurationCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

    const stack = clientStack.concat(this.middlewareStack);

    const { logger } = configuration;
    const clientName = "ECRClient";
    const commandName = "PutImageScanningConfigurationCommand";
    const handlerExecutionContext: HandlerExecutionContext = {
      logger,
      clientName,
      commandName,
      inputFilterSensitiveLog: PutImageScanningConfigurationRequest.filterSensitiveLog,
      outputFilterSensitiveLog: PutImageScanningConfigurationResponse.filterSensitiveLog,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }

  private serialize(input: PutImageScanningConfigurationCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
    return serializeAws_json1_1PutImageScanningConfigurationCommand(input, context);
  }

  private deserialize(
    output: __HttpResponse,
    context: __SerdeContext
  ): Promise<PutImageScanningConfigurationCommandOutput> {
    return deserializeAws_json1_1PutImageScanningConfigurationCommand(output, context);
  }

  // Start section: command_body_extra
  // End section: command_body_extra
}


export interface PutImageScanningConfigurationCommandInput extends PutImageScanningConfigurationRequest {}


export interface PutImageScanningConfigurationCommandOutput
  extends PutImageScanningConfigurationResponse,
    __MetadataBearer {}


/**
   * @internal
   */
resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: ECRClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<PutImageScanningConfigurationCommandInput, PutImageScanningConfigurationCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

    const stack = clientStack.concat(this.middlewareStack);

    const { logger } = configuration;
    const clientName = "ECRClient";
    const commandName = "PutImageScanningConfigurationCommand";
    const handlerExecutionContext: HandlerExecutionContext = {
      logger,
      clientName,
      commandName,
      inputFilterSensitiveLog: PutImageScanningConfigurationRequest.filterSensitiveLog,
      outputFilterSensitiveLog: PutImageScanningConfigurationResponse.filterSensitiveLog,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }


private serialize(input: PutImageScanningConfigurationCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
    return serializeAws_json1_1PutImageScanningConfigurationCommand(input, context);
  }


private deserialize(
    output: __HttpResponse,
    context: __SerdeContext
  ): Promise<PutImageScanningConfigurationCommandOutput> {
    return deserializeAws_json1_1PutImageScanningConfigurationCommand(output, context);
  }


/**
 * @namespace Konva
 */
function detectBrowser() {
  return (
    typeof window !== 'undefined' &&
    // browser case
    ({}.toString.call(window) === '[object Window]' ||
      // electron case
      {}.toString.call(window) === '[object global]')
  );
}


NodeClass => {
  _NODES_REGISTRY[NodeClass.prototype.getClassName()] = NodeClass;
  Konva[NodeClass.prototype.getClassName()] = NodeClass;
}


getAngle(angle) {
    return Konva.angleDeg ? angle * PI_OVER_180 : angle;
  }


/**
   * returns whether or not drag and drop is currently active
   * @method
   * @memberof Konva
   */
isDragging() {
    return Konva['DD'].isDragging;
  }


/**
   * returns whether or not a drag and drop operation is ready, but may
   *  not necessarily have started
   * @method
   * @memberof Konva
   */
isDragReady() {
    return !!Konva['DD'].node;
  }


// insert Konva into global namaspace (window)
// it is required for npm packages
_injectGlobal(Konva) {
    glob.Konva = Konva;
  }


export declare class CpuBinaryOp extends BinaryOp {
    private opLambda?;
    constructor(typeConstraint: ReadonlyArray<Tensor.DataType>, opLambda?: ((e1: number, e2: number) => number) | undefined, opType?: string, resultType?: Tensor.DataType);
    initialize(attributes: Attribute): void;
    run(inferenceHandler: CpuInferenceHandler, inputs: Tensor[]): Tensor[];
}


initialize(attributes: Attribute): void;


run(inferenceHandler: CpuInferenceHandler, inputs: Tensor[]): Tensor[];


export default function MHPRatingScreen() {
  const [cardWidth, setCardWidth] = useState(0);
  const [comments, setComments] = useState('');
  const [loading, setLoading] = useState(false);
  const [selectedRating, setSelectedRating] = useState(0);

  const starSize = cardWidth / (AMOUNT_STARS * 2);
  const spacingSize = starSize / 2;

  async function onPress() {
    if (!loading) {
      setLoading(true);
      const result = await mentalHealthApiClient.feedback(selectedRating, comments);
      setLoading(false);
      if (result) {
        NavigatorService.reset([{ name: homeScreenName() }, { name: 'MentalHealthPlaybackThankYou' }]);
      }
    }
  }

  function onLayout(event: LayoutChangeEvent) {
    setCardWidth(event.nativeEvent.layout.width);
  }

  return (
    <BasicPage
      hasStickyHeader
      active={!loading && selectedRating > 0}


async function onPress() {
    if (!loading) {
      setLoading(true);
      const result = await mentalHealthApiClient.feedback(selectedRating, comments);
      setLoading(false);
      if (result) {
        NavigatorService.reset([{ name: homeScreenName() }, { name: 'MentalHealthPlaybackThankYou' }]);
      }
    }
  }


function onLayout(event: LayoutChangeEvent) {
    setCardWidth(event.nativeEvent.layout.width);
  }


(_, i) => i


(func) => func()


(rating) => (
              <TouchableOpacity
                key={`touchable-star-${rating}`


off => {
        if (off) {
          // User should only get here if url is manually entered
          this.store.dispatch(new RouterNav({
            path: ['applications'],
            extras: {
              replaceUrl: true
            }
          }));
        }
      }


sessionData => sessionData?.plugins.backup


enabled => enabled ? currentUserPermissionsService.can(this.canRegisterEndpoint) : of(false)


() => {
      this.healthCheckTimeout = window.setInterval(() => {
        this.ngZone.run(() => {
          this.endpointsService.checkAllEndpoints();
        });
      }, 30000);
    }


() => {
        this.ngZone.run(() => {
          this.endpointsService.checkAllEndpoints();
        });
      }


() => {
          this.endpointsService.checkAllEndpoints();
        }


haveRegistered => {
      // Use custom component if specified
      this.customNoEndpointsContainer.clear();
      if (!haveRegistered && this.customizations.noEndpointsComponent) {
        const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(this.customizations.noEndpointsComponent);
        this.customContentComponentRef = this.customNoEndpointsContainer.createComponent(factory);
      }
    }


dashboard => {
      if (dashboard.pollingEnabled) {
        this.startEndpointHealthCheckPulse();
      }
    }


([hasRegistered, hasConnected]) => {
        this.showSnackBar(hasRegistered && !hasConnected);
      }


@Component({
  selector: 'app-endpoints-page',
  templateUrl: './endpoints-page.component.html',
  styleUrls: ['./endpoints-page.component.scss'],
  providers: [{
    provide: ListConfig,
    useClass: EndpointsListConfigService,
  }, EndpointListHelper]
})
export class EndpointsPageComponent implements AfterViewInit, OnDestroy, OnInit {
  public canRegisterEndpoint = StratosCurrentUserPermissions.ENDPOINT_REGISTER;
  private healthCheckTimeout: number;

  public canBackupRestore$: Observable<boolean>;

  @ViewChild('customNoEndpoints', { read: ViewContainerRef, static: true }) customNoEndpointsContainer;
  customContentComponentRef: ComponentRef<any>;

  private snackBarText = {
    message: `There are no connected endpoints, connect with your personal credentials to get started.`,
    action: 'Got it'
  };

  public customizations: CustomizationsMetadata;

  constructor(
    public endpointsService: EndpointsService,
    public store: Store<EndpointOnlyAppState>,
    private ngZone: NgZone,
    private resolver: ComponentFactoryResolver,
    private snackBarService: SnackBarService,
    cs: CustomizationService,
    currentUserPermissionsService: CurrentUserPermissionsService,
  ) {
    this.customizations = cs.get();

    // Redirect to /applications if not enabled.
    endpointsService.disablePersistenceFeatures$.pipe(
      map(off => {
        if (off) {
          // User should only get here if url is manually entered
          this.store.dispatch(new RouterNav({
            path: ['applications'],
            extras: {
              replaceUrl: true
            }
          }));
        }
      }),
      first()
    ).subscribe();

    // Is the backup/restore plugin available on the backend?
    this.canBackupRestore$ = this.store.select(selectSessionData()).pipe(
      first(),
      map(sessionData => sessionData?.plugins.backup),
      switchMap(enabled => enabled ? currentUserPermissionsService.can(this.canRegisterEndpoint) : of(false))
    );
  }

  subs: Subscription[] = [];

  public extensionActions: StratosActionMetadata[] = getActionsFromExtensions(StratosActionType.Endpoints);

  private startEndpointHealthCheckPulse() {
    this.ngZone.runOutsideAngular(() => {
      this.healthCheckTimeout = window.setInterval(() => {
        this.ngZone.run(() => {
          this.endpointsService.checkAllEndpoints();
        });
      }, 30000);
    });
  }

  private stopEndpointHealthCheckPulse() {
    clearInterval(this.healthCheckTimeout);
  }

  private showSnackBar(show: boolean) {
    if (show) {
      this.snackBarService.show(this.snackBarText.message, this.snackBarText.action, 20000);
    } else {
      this.snackBarService.hide();
    }
  }

  ngOnInit() {
    this.subs.push(this.endpointsService.haveRegistered$.subscribe(haveRegistered => {
      // Use custom component if specified
      this.customNoEndpointsContainer.clear();
      if (!haveRegistered && this.customizations.noEndpointsComponent) {
        const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(this.customizations.noEndpointsComponent);
        this.customContentComponentRef = this.customNoEndpointsContainer.createComponent(factory);
      }
    }));

    this.endpointsService.checkAllEndpoints();
    this.store.select(selectDashboardState).pipe(
      first()
    ).subscribe(dashboard => {
      if (dashboard.pollingEnabled) {
        this.startEndpointHealthCheckPulse();
      }
    });
  }

  ngAfterViewInit() {
    this.subs.push(combineLatest(
      this.endpointsService.haveRegistered$,
      this.endpointsService.haveConnected$,
    ).pipe(
      delay(1),
      tap(([hasRegistered, hasConnected]) => {
        this.showSnackBar(hasRegistered && !hasConnected);
      }),
    ).subscribe());
  }

  ngOnDestroy() {
    this.stopEndpointHealthCheckPulse();
    safeUnsubscribe(...this.subs);
    if (this.customContentComponentRef) {
      this.customContentComponentRef.destroy();
    }
    this.showSnackBar(false);
  }
}


private startEndpointHealthCheckPulse() {
    this.ngZone.runOutsideAngular(() => {
      this.healthCheckTimeout = window.setInterval(() => {
        this.ngZone.run(() => {
          this.endpointsService.checkAllEndpoints();
        });
      }, 30000);
    });
  }


private stopEndpointHealthCheckPulse() {
    clearInterval(this.healthCheckTimeout);
  }


private showSnackBar(show: boolean) {
    if (show) {
      this.snackBarService.show(this.snackBarText.message, this.snackBarText.action, 20000);
    } else {
      this.snackBarService.hide();
    }
  }


ngOnInit() {
    this.subs.push(this.endpointsService.haveRegistered$.subscribe(haveRegistered => {
      // Use custom component if specified
      this.customNoEndpointsContainer.clear();
      if (!haveRegistered && this.customizations.noEndpointsComponent) {
        const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(this.customizations.noEndpointsComponent);
        this.customContentComponentRef = this.customNoEndpointsContainer.createComponent(factory);
      }
    }));

    this.endpointsService.checkAllEndpoints();
    this.store.select(selectDashboardState).pipe(
      first()
    ).subscribe(dashboard => {
      if (dashboard.pollingEnabled) {
        this.startEndpointHealthCheckPulse();
      }
    });
  }


ngAfterViewInit() {
    this.subs.push(combineLatest(
      this.endpointsService.haveRegistered$,
      this.endpointsService.haveConnected$,
    ).pipe(
      delay(1),
      tap(([hasRegistered, hasConnected]) => {
        this.showSnackBar(hasRegistered && !hasConnected);
      }),
    ).subscribe());
  }


ngOnDestroy() {
    this.stopEndpointHealthCheckPulse();
    safeUnsubscribe(...this.subs);
    if (this.customContentComponentRef) {
      this.customContentComponentRef.destroy();
    }
    this.showSnackBar(false);
  }


@Entity("users")
class User {

    @PrimaryColumn()
    id: string;

    @Column()
    email: string;

    @CreateDateColumn()
    created_at: Date;

    constructor() {
        if(!this.id) {
            this.id = uuid();
        }
    }
}


function getTypeIcon(type: string, size: number = 24) {
  switch (type) {
    case 'info':
      return <FiAlertCircle size={size} />
    case 'warning':
      return <FiAlertTriangle size={size} />
    case 'danger':
      return <FiXOctagon size={size} />
    case 'success':
    default:
      return <FiCheckCircle size={size} />
  }
}


function getTypeColor(type: string) {
  switch (type) {
    case 'info':
      return '#425EC2'
    case 'warning':
      return '#EF7F00'
    case 'danger':
      return '#ff5c77'
    case 'success':
    default:
      return '#00e676'
  }
}


(props: IToastProps) => {
  const { className, toast, removeToast } = props
  const [inProgress, setInProgress] = useState(false)
  const remove = useCallback(() => removeToast(toast.id), [toast])
  useLayoutEffect(() => {
    const id = setTimeout(() => setInProgress(true), 0)
    return () => clearTimeout(id)
  }, [])
  useLayoutEffect(() => {
    const id = setTimeout(remove, toast.duration)
    return () => clearTimeout(id)
  }, [])
  return (
    <ToastItem className={className} type={toast.type}>
      <ToastBody type={toast.type}>
        <SvgWrapper className="type-icon">{ getTypeIcon(toast.type


() => removeToast(toast.id)


() => {
    const id = setTimeout(() => setInProgress(true), 0)
    return () => clearTimeout(id)
  }


() => setInProgress(true)


() => clearTimeout(id)


() => {
    const id = setTimeout(remove, toast.duration)
    return () => clearTimeout(id)
  }


(stores: Stores) => ({
  toasts: stores.toastStore.toasts,
  toasterLocation: stores.toastStore.toasterLocation,
  removeToast: stores.toastStore.removeToast,
})


(props: IProps) => {
  const { className, toasts = [], toasterLocation, removeToast } = props
  return (
    <ToastsList className={`${className} ${toasterLocation}`}


t =>
      <Toast key


({ type }) => getTypeColor(type)


({ inProgress }) => inProgress ? '0%' : '100%'


({ duration }) => duration


interface IToastProps {
  className?: string
  toast: IToast
  removeToast: (id: number) => void
}


interface IProps {
  className?: string
  toasts?: IToast[]
  toasterLocation?: ToastLocation
  removeToast?: (id: number) => void
}


type ToastItemProps = {
  type: string
}


type ToastBodyProps = { type: string }


type ProgressProps = { type: string, inProgress: boolean, duration: number }


getTypeIcon(toast


function App () {
  const [initialThemeType, setInitialThemeType] = React.useState<chrome.braveTheme.ThemeType>()
  React.useEffect(() => {
    chrome.braveTheme.getBraveThemeType(setInitialThemeType)
  }, [])
  return (
    <Provider store={store}>
      {initialThemeType &&
      <BraveCoreThemeProvider
        initialThemeType={initialThemeType}
        dark={walletDarkTheme}
        light={walletLightTheme}
      >
        <Container />
      </BraveCoreThemeProvider>
      }


function initialize () {
  store.dispatch(WalletActions.initialize())
  render(<App />, document.getElementById('root'))
}


() => {
    chrome.braveTheme.getBraveThemeType(setInitialThemeType)
  }


() => {
  let s2: SpreadSheet;

  const props: BaseSheetComponentProps = {
    options: s2Options,
    dataCfg: mockDataConfig,
  };

  beforeEach(() => {
    s2 = new PivotSheet(getContainer(), mockDataConfig, s2Options);
    s2.render();
  });

  test('should be defined', () => {
    const { result } = renderHook(() => usePagination(s2, props));

    expect(result.current).toBeDefined();
  });

  test('should get default pagination', () => {
    const { result } = renderHook(() => usePagination(s2, props));

    expect(result.current.total).toEqual(0);
    expect(result.current.current).toEqual(1);
    expect(result.current.pageSize).toEqual(10);
  });

  test('should update pagination', () => {
    const { result } = renderHook(() => usePagination(s2, props));

    act(() => {
      result.current.setCurrent(2);
      result.current.setPageSize(5);
      result.current.setTotal(10);
    });

    expect(result.current.total).toEqual(10);
    expect(result.current.current).toEqual(2);
    expect(result.current.pageSize).toEqual(5);
  });
}


() => {
    s2 = new PivotSheet(getContainer(), mockDataConfig, s2Options);
    s2.render();
  }


() => {
    const { result } = renderHook(() => usePagination(s2, props));

    expect(result.current).toBeDefined();
  }


() => usePagination(s2, props)


() => {
    const { result } = renderHook(() => usePagination(s2, props));

    expect(result.current.total).toEqual(0);
    expect(result.current.current).toEqual(1);
    expect(result.current.pageSize).toEqual(10);
  }


() => {
    const { result } = renderHook(() => usePagination(s2, props));

    act(() => {
      result.current.setCurrent(2);
      result.current.setPageSize(5);
      result.current.setTotal(10);
    });

    expect(result.current.total).toEqual(10);
    expect(result.current.current).toEqual(2);
    expect(result.current.pageSize).toEqual(5);
  }


() => {
      result.current.setCurrent(2);
      result.current.setPageSize(5);
      result.current.setTotal(10);
    }


export interface CreateDataAssetResponse {
  /**
   * For optimistic concurrency control. See [ETags for Optimistic Concurrency Control](https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#eleven).
   *
   */
  "etag": string;
  /**
   * Unique Oracle-assigned identifier for the request. If you need to contact
   * Oracle about a particular request, please provide the request ID.
   *
   */
  "opcRequestId": string;
  /**
   * The returned model.DataAsset instance.
   */
  "dataAsset": model.DataAsset;
}


async function run() {
    const client = new SingleNodeClient(API_ENDPOINT);

    const info = await client.info();

    console.log("Base");

    // Generate a random mnemonic.
    const randomMnemonic = Bip39.randomMnemonic();
    console.log("\tMnemonic:", randomMnemonic);

    // Generate the seed from the Mnemonic
    const baseSeed = Ed25519Seed.fromMnemonic(randomMnemonic);
    console.log("\tSeed", Converter.bytesToHex(baseSeed.toBytes()));

    // Generate the next addresses for your account.
    console.log();
    console.log("Generated Addresses using Bip44 Format");
    const addressGeneratorAccountState = {
        accountIndex: 0,
        addressIndex: 0,
        isInternal: false
    };
    for (let i = 0; i < 6; i++) {
        const path = generateBip44Address(addressGeneratorAccountState);

        console.log(`Wallet Index ${path}`);

        const addressSeed = baseSeed.generateSeedFromPath(new Bip32Path(path));
        const addressKeyPair = addressSeed.keyPair();

        console.log("\tPrivate Key", Converter.bytesToHex(addressKeyPair.privateKey));
        console.log("\tPublic Key", Converter.bytesToHex(addressKeyPair.publicKey));

        const indexEd25519Address = new Ed25519Address(addressKeyPair.publicKey);
        const indexPublicKeyAddress = indexEd25519Address.toAddress();
        console.log("\tAddress Ed25519", Converter.bytesToHex(indexPublicKeyAddress));
        console.log(
            "\tAddress Bech32",
            Bech32Helper.toBech32(ED25519_ADDRESS_TYPE, indexPublicKeyAddress, info.bech32HRP)
        );
        console.log();
    }

    console.log();
    console.log("Generated Addresses manually using Bip44 Format");
    console.log();

    // You can perform the same process as the generator manually as follows.
    const basePath = new Bip32Path(IOTA_BIP44_BASE_PATH);
    const accountIndex = 0;
    let isInternal = false;
    let addressIndex = 0;
    for (let i = 0; i < 6; i++) {
        basePath.pushHardened(accountIndex);
        basePath.pushHardened(isInternal ? 1 : 0);
        basePath.pushHardened(addressIndex);

        console.log(`Wallet Index ${basePath.toString()}`);

        // Create a new seed from the base seed using the path
        const indexSeed = baseSeed.generateSeedFromPath(basePath);
        console.log("\tSeed", Converter.bytesToHex(indexSeed.toBytes()));

        // Get the public and private keys for the path seed
        const indexSeedKeyPair = indexSeed.keyPair();
        console.log("\tPrivate Key", Converter.bytesToHex(indexSeedKeyPair.privateKey));
        console.log("\tPublic Key", Converter.bytesToHex(indexSeedKeyPair.publicKey));

        // Get the address for the path seed which is actually the Blake2b.sum256 of the public key
        // display it in both Ed25519 and Bech 32 format
        const indexEd25519Address = new Ed25519Address(indexSeedKeyPair.publicKey);
        const indexPublicKeyAddress = indexEd25519Address.toAddress();
        console.log("\tAddress Ed25519", Converter.bytesToHex(indexPublicKeyAddress));
        console.log(
            "\tAddress Bech32",
            Bech32Helper.toBech32(ED25519_ADDRESS_TYPE, indexPublicKeyAddress, info.bech32HRP)
        );
        console.log();

        basePath.pop();
        basePath.pop();
        basePath.pop();

        if (isInternal) {
            addressIndex++;
        }
        isInternal = !isInternal;
    }
}


() => console.log("Done")


_ => this.initMap()


result => {
      this.barangaysource.addFeatures(
        new GeoJSON().readFeatures(result, {
          dataProjection: "EPSG:4326",
          featureProjection: "EPSG:3857"
        })
      );
    }


items => {
      let geojson = {
        type: "FeatureCollection",
        features: []
      };

      if (items && this.item.location) {
        geojson.features = items.filter(o => o.features[0].id !== this.item.location.objid).map(item => item.features[0]);
      } else {
        geojson.features = items.map(item => item.features[0]);
      }
      if (items) {
        this.farmsource.clear();
        this.farmsource.addFeatures(new GeoJSON().readFeatures(geojson));
        this.farmvector.setStyle((feature, resolution) => {
          let geom = feature.getGeometry();
          var output;
          if (geom instanceof Polygon) {
            output = this.formatArea(geom);
          }
          farmsLabelStyle.getText().setText(output);
          return farmsstyle;
        });
      }

      this.mapsloaded = true;

    }


o => o.features[0].id !== this.item.location.objid


item => item.features[0]


(feature, resolution) => {
          let geom = feature.getGeometry();
          var output;
          if (geom instanceof Polygon) {
            output = this.formatArea(geom);
          }
          farmsLabelStyle.getText().setText(output);
          return farmsstyle;
        }


e => {
        var extent = e.selected[0].getGeometry().getExtent();
        let farmerid = e.selected[0].get("farmerid");
        let itemtype = e.selected[0].get("itemtype");
        let itemid = e.selected[0].get("itemid");
        this.selectedFeature.emit({'locationid':e.selected[0].getId(),'farmerid':farmerid,'itemtype':itemtype,'itemid':itemid});

        this.farmerService.getItem(farmerid).then(item => {
          if (item) {
            let content = "";
            content +=
              "
Farmer : " + item.farmer.name + "
";
            if (itemtype === "commodity") {
              let commodity = item.commodities.find(o => o.objid === itemid);
              content +=
                "
" +
                commodity.variety.commoditytype.commodity.name +
                "
";
              content +=
                "
" +
                commodity.variety.commoditytype.unit +
                " : " +
                commodity.quantity;
              content +=
                "
Commodity Type : " + commodity.variety.commoditytype.name;
              content += "
Variety : " + commodity.variety.name;
              content +=
                "
Sruvey Period : " + commodity.surveyperiod.name + "
";

              //
{{item.variety.commoditytype.commodity.name}}

              //

              //   {{item.variety.commoditytype.unit}} : {{item.quantity}}

              //   Commodity Type : {{item.variety.commoditytype.name}}

              //   Variety : {{item.variety.name}}

              //   Survey Period : {{item.surveyperiod.name}}
              //

            } else {
              let livestock = item.livestocks.find(o => o.objid === itemid);
              content += "
" + livestock.breed.species.name + "
";
              content +=
                "
" + "Sruvey Period : " + livestock.surveyperiod.name;
              //
{{item.breed.species.name}}

              //

              //   Harvesting qty. : {{item.breed.name}}

              //   Seeding qty. : {{item.seedingqty}}

              //   Harvesting qty. : {{item.harvestingqty}}

              //   Survey Period : {{item.surveyperiod.name}}
              //

            }
            this.renderer.setProperty(
              this.popupcontent.nativeElement,
              "innerHTML",
              content
            );
          } else {
            this.renderer.setProperty(
              this.popupcontent.nativeElement,
              "innerHTML",
              "No Farmer Data"
            );
          }
        });

        this.popupoverlay.setPosition(getCenter(extent));
      }


item => {
          if (item) {
            let content = "";
            content +=
              "
Farmer : " + item.farmer.name + "
";
            if (itemtype === "commodity") {
              let commodity = item.commodities.find(o => o.objid === itemid);
              content +=
                "
" +
                commodity.variety.commoditytype.commodity.name +
                "
";
              content +=
                "
" +
                commodity.variety.commoditytype.unit +
                " : " +
                commodity.quantity;
              content +=
                "
Commodity Type : " + commodity.variety.commoditytype.name;
              content += "
Variety : " + commodity.variety.name;
              content +=
                "
Sruvey Period : " + commodity.surveyperiod.name + "
";

              //
{{item.variety.commoditytype.commodity.name}}

              //

              //   {{item.variety.commoditytype.unit}} : {{item.quantity}}

              //   Commodity Type : {{item.variety.commoditytype.name}}

              //   Variety : {{item.variety.name}}

              //   Survey Period : {{item.surveyperiod.name}}
              //

            } else {
              let livestock = item.livestocks.find(o => o.objid === itemid);
              content += "
" + livestock.breed.species.name + "
";
              content +=
                "
" + "Sruvey Period : " + livestock.surveyperiod.name;
              //
{{item.breed.species.name}}

              //

              //   Harvesting qty. : {{item.breed.name}}

              //   Seeding qty. : {{item.seedingqty}}

              //   Harvesting qty. : {{item.harvestingqty}}

              //   Survey Period : {{item.surveyperiod.name}}
              //

            }
            this.renderer.setProperty(
              this.popupcontent.nativeElement,
              "innerHTML",
              content
            );
          } else {
            this.renderer.setProperty(
              this.popupcontent.nativeElement,
              "innerHTML",
              "No Farmer Data"
            );
          }
        }


o => o.objid === itemid


feature => {
        let geom = feature.getGeometry();
        var output;
        if (geom instanceof Polygon) {
          output = this.formatArea(geom);
        }
        drawLabelStyle.getText().setText(output);
        return drawstyle;
      }


() => {
      this.renderer.addClass(this.helpTooltipElement, "hidden");
      // console.log(this.helpTooltipElement);
    }


evt => {
      if (evt.dragging) {
        return;
      }

      this.renderer.setProperty(
        this.helpTooltipElement,
        "textContent",
        "Click to continue drawing the polygon"
      );

      this.helpTooltip.setPosition(evt.coordinate);
      this.renderer.removeClass(this.helpTooltipElement, "hidden");
    }


evt => {
      // set sketch
      this.sketch = evt.feature;

      var tooltipCoord = evt.coordinate;

      listener = this.sketch.getGeometry().on("change", evt => {
        var geom = evt.target;
        var output;
        if (geom instanceof Polygon) {
          output = this.formatArea(geom);
          tooltipCoord = geom.getInteriorPoint().getCoordinates();
        }
        this.renderer.setProperty(
          this.measureTooltipElement,
          "textContent",
          output
        );
        // this.measureTooltipElement.innerHTML = output;
        this.measureTooltip.setPosition(tooltipCoord);
      });
    }


evt => {
        var geom = evt.target;
        var output;
        if (geom instanceof Polygon) {
          output = this.formatArea(geom);
          tooltipCoord = geom.getInteriorPoint().getCoordinates();
        }
        this.renderer.setProperty(
          this.measureTooltipElement,
          "textContent",
          output
        );
        // this.measureTooltipElement.innerHTML = output;
        this.measureTooltip.setPosition(tooltipCoord);
      }


evt => {
      // this.renderer.setProperty(this.measureTooltipElement, 'class', 'ol-tooltip ol-tooltip-static');
      // this.measureTooltip.setOffset([0, -7]);
      // unset sketch
      this.sketch = null;
      // unset tooltip so that a new one can be created
      this.measureTooltipElement = null;
      // this.createMeasureTooltip();
      unByKey(listener);

      this.map.removeInteraction(this.draw);
      evt.feature.setId(this.item.location.objid);
      evt.feature.setProperties({
        farmerid: this.farmerid,
        itemtype: this.type,
        itemid: this.item.objid
      });
    }


item => {
      if (this.type === "commodity") {
        item.commodities = item.commodities.map(c =>
          c.objid === this.item.objid ? (c = this.item) : c
        );
      } else {
        item.livestocks = item.livestocks.map(l =>
          l.objid === this.item.objid ? (l = this.item) : l
        );
      }
      // console.log(item);
      this.farmerService.updatefarmer(item);
      this.mapService.saveItem(JSON.parse(data));
      this.farmlocationService.updateItem(this.item.location);
    }


c =>
          c.objid === this.item.objid ? (c = this.item) : c


l =>
          l.objid === this.item.objid ? (l = this.item) : l


item => {
      if (this.type === "commodity") {
        item.commodities = item.commodities.map(c =>
          c.objid === this.item.objid ? (c = this.item) : c
        );
      } else {
        item.livestocks = item.livestocks.map(l =>
          l.objid === this.item.objid ? (l = this.item) : l
        );
      }

      this.farmerService.updatefarmer(item);
      this.mapService.deleteItem(this.item.location.objid);
      this.farmlocationService.updateItem(this.item.location);
    }


formatArea(polygon) {
    var area = getArea(polygon);
    var output;
    // if (area > 10000) {
    //   output =
    //     Math.round((area / 1000000) * 100) / 100 + " " + "km2";
    // } else {
    //   output = Math.round(area * 100) / 100 + " " + "m2";
    // }
    output = Math.round(area * 100) / 100;
    output =
      output.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " " + "sqm";
    return output;
  }


ngOnInit() {
    setTimeout(_ => this.initMap(), 2000);
  }


// ngAfterViewInit() {
//   setTimeout(_ => this.initMap(), 2000);
// }
ngOnChanges(simpleChanges: SimpleChanges) {
    if (simpleChanges.item.previousValue) {
      this.drawlocationfeature();
    }
  }


initMap() {
    var barangaylabelStyle = new Style({
      text: new Text({
        font: "12px Calibri,sans-serif",
        overflow: true,
        fill: new Fill({
          color: "#000"
        }),
        stroke: new Stroke({
          color: "#fff",
          width: 3
        })
      })
    });
    var barangaystylefill = new Style({
      // fill: new Fill({
      //   color: 'rgba(255, 255, 255, 0.6)'
      // }),
      stroke: new Stroke({
        color: "#319FD3",
        width: 1
      })
    });
    var barangaystyle = [barangaystylefill, barangaylabelStyle];

    //base map
    this.geometryType = "Polygon";
    this.raster = new TileLayer({
      source: new OSM()
    });
    this.basemap = new TileLayer({
      source: new XYZ({
        maxZoom: 17,
        attributions:
          'Tiles © ArcGIS',
        url:
          "https://server.arcgisonline.com/ArcGIS/rest/services/" +
          "World_Imagery/MapServer/tile/{z}/{y}/{x}"
      })
    });
    //allfarms
    this.farmsource = new VectorSource({
      format: new GeoJSON()
    });
    this.farmvector = new VectorLayer({
      source: this.farmsource
    });

    //draw map
    this.source = new VectorSource({
      format: new GeoJSON()
    });
    this.vector = new VectorLayer({
      source: this.source
      // style:
    });
    //barangay map
    this.barangaysource = new VectorSource({
      format: new GeoJSON()
    });
    this.barangayvector = new VectorLayer({
      declutter: true,
      source: this.barangaysource,
      style: function(feature) {
        barangaylabelStyle.getText().setText(feature.get("brgyname"));
        return barangaystyle;
      }
    });

    this.map = new Map({
      layers: [this.basemap, this.barangayvector, this.farmvector, this.vector],
      target: this.mapmode === "preview" ? "preview" : "map",
      view: new View({
        zoom: 15,
        maxZoom: 20
      })
    });

    var zoomslider = new ZoomSlider();
    this.map.addControl(zoomslider);
    this.map
      .getView()
      .fit([13784343.025655, 814368.207926, 14048821.648763, 978738.393527]);

    //add barangay boundaries
    this.getBrgyBoundaries().subscribe(result => {
      this.barangaysource.addFeatures(
        new GeoJSON().readFeatures(result, {
          dataProjection: "EPSG:4326",
          featureProjection: "EPSG:3857"
        })
      );
    });
    //edit feature controls
    this.enablesave = false;
    this.enableclear = false;
    this.enablemodify = false;

    this.drawlocationfeature();
    this.getalllayers();
    this.createMeasureTooltip();
    this.createpopup();
  }


closepopup() {
    this.popupoverlay.setPosition(undefined);
  }


getalllayers() {
    var farmsLabelStyle = new Style({
      text: new Text({
        font: "12px Calibri,sans-serif",
        overflow: false,
        fill: new Fill({
          color: "#000"
        }),
        backgroundFill: new Fill({
          color: "#ffcc33"
        }),
        padding: [4, 8, 4, 8]
      })
    });

    var farmsFillStyle = new Style({
      fill: new Fill({
        color: "rgba(255, 255, 255, 0.2)"
      }),
      stroke: new Stroke({
        color: "#fc2803",
        width: 2
      }),
      image: new CircleStyle({
        radius: 7,
        fill: new Fill({
          color: "#fc2803"
        })
      })
    });

    var farmsstyle = [farmsFillStyle, farmsLabelStyle];

    this.mapService.getItems().then(items => {
      let geojson = {
        type: "FeatureCollection",
        features: []
      };

      if (items && this.item.location) {
        geojson.features = items.filter(o => o.features[0].id !== this.item.location.objid).map(item => item.features[0]);
      } else {
        geojson.features = items.map(item => item.features[0]);
      }
      if (items) {
        this.farmsource.clear();
        this.farmsource.addFeatures(new GeoJSON().readFeatures(geojson));
        this.farmvector.setStyle((feature, resolution) => {
          let geom = feature.getGeometry();
          var output;
          if (geom instanceof Polygon) {
            output = this.formatArea(geom);
          }
          farmsLabelStyle.getText().setText(output);
          return farmsstyle;
        });
      }

      this.mapsloaded = true;

    });
  }


createpopup() {

    this.popupoverlay = new Overlay({
      element: this.popup.nativeElement,
      autoPan: true,
      autoPanAnimation: {
        duration: 250
      }
    });
    this.map.addOverlay(this.popupoverlay);

    if (this.mapmode === "preview") {
      var selectSingleClick = new Select();
      this.map.addInteraction(selectSingleClick);
      selectSingleClick.on("select", e => {
        var extent = e.selected[0].getGeometry().getExtent();
        let farmerid = e.selected[0].get("farmerid");
        let itemtype = e.selected[0].get("itemtype");
        let itemid = e.selected[0].get("itemid");
        this.selectedFeature.emit({'locationid':e.selected[0].getId(),'farmerid':farmerid,'itemtype':itemtype,'itemid':itemid});

        this.farmerService.getItem(farmerid).then(item => {
          if (item) {
            let content = "";
            content +=
              "
Farmer : " + item.farmer.name + "
";
            if (itemtype === "commodity") {
              let commodity = item.commodities.find(o => o.objid === itemid);
              content +=
                "
" +
                commodity.variety.commoditytype.commodity.name +
                "
";
              content +=
                "
" +
                commodity.variety.commoditytype.unit +
                " : " +
                commodity.quantity;
              content +=
                "
Commodity Type : " + commodity.variety.commoditytype.name;
              content += "
Variety : " + commodity.variety.name;
              content +=
                "
Sruvey Period : " + commodity.surveyperiod.name + "
";

              //
{{item.variety.commoditytype.commodity.name}}

              //

              //   {{item.variety.commoditytype.unit}} : {{item.quantity}}

              //   Commodity Type : {{item.variety.commoditytype.name}}

              //   Variety : {{item.variety.name}}

              //   Survey Period : {{item.surveyperiod.name}}
              //

            } else {
              let livestock = item.livestocks.find(o => o.objid === itemid);
              content += "
" + livestock.breed.species.name + "
";
              content +=
                "
" + "Sruvey Period : " + livestock.surveyperiod.name;
              //
{{item.breed.species.name}}

              //

              //   Harvesting qty. : {{item.breed.name}}

              //   Seeding qty. : {{item.seedingqty}}

              //   Harvesting qty. : {{item.harvestingqty}}

              //   Survey Period : {{item.surveyperiod.name}}
              //

            }
            this.renderer.setProperty(
              this.popupcontent.nativeElement,
              "innerHTML",
              content
            );
          } else {
            this.renderer.setProperty(
              this.popupcontent.nativeElement,
              "innerHTML",
              "No Farmer Data"
            );
          }
        });

        this.popupoverlay.setPosition(getCenter(extent));
      });
    }
  }


drawlocationfeature() {
    var drawLabelStyle = new Style({
      text: new Text({
        font: "12px Calibri,sans-serif",
        overflow: false,
        fill: new Fill({
          color: "#000"
        }),
        backgroundFill: new Fill({
          color: "#ffcc33"
        }),
        padding: [4, 8, 4, 8]
      })
    });

    var drawFillStyle = new Style({
      fill: new Fill({
        color: "rgba(255, 255, 255, 0.2)"
      }),
      stroke: new Stroke({
        color: "#ffcc33",
        width: 2
      }),
      image: new CircleStyle({
        radius: 7,
        fill: new Fill({
          color: "#ffcc33"
        })
      })
    });
    var drawstyle = [drawFillStyle, drawLabelStyle];
    if (this.item.location?.geolocation?.type) {
      this.source.clear();
      this.source.addFeatures(
        new GeoJSON().readFeatures(this.item.location.geolocation)
      );
      this.enabledraw = false;
      this.enablemodify = true;
      this.enableclear = true;

      //zoom to layer
      var extent = this.vector.getSource().getExtent();
      this.map.getView().fit(extent);

      this.vector.setStyle(feature => {
        let geom = feature.getGeometry();
        var output;
        if (geom instanceof Polygon) {
          output = this.formatArea(geom);
        }
        drawLabelStyle.getText().setText(output);
        return drawstyle;
      });
    }
  }


// pointerMoveHandler(evt) {
//   if (evt.dragging) {
//     return;
//   }
//   // this.helpMsg = this.renderer.createText('Click to start drawing');
//   // if (this.sketch) {
//   //   var geom = this.sketch.getGeometry();
//   //   if (geom instanceof Polygon) {
//   //     this.helpMsg = this.renderer.createText(this.continuePolygonMsg);
//   //   } else if (geom instanceof LineString) {
//   //     this.helpMsg = this.renderer.createText(this.continueLineMsg);
//   //   }
//   // }
//   // this.renderer.appendChild(this.helpTooltipElement, this.helpMsg);
//   this.helpTooltip.setPosition(evt.coordinate);
//   this.renderer.removeClass(this.helpTooltipElement.nativeElement, "hidden");
// }
removehelpTooltipElement() {
    this.map.getViewport().addEventListener("mouseout", () => {
      this.renderer.addClass(this.helpTooltipElement, "hidden");
      // console.log(this.helpTooltipElement);
    });
  }


addpointermovehandler() {
    this.map.on("pointermove", evt => {
      if (evt.dragging) {
        return;
      }

      this.renderer.setProperty(
        this.helpTooltipElement,
        "textContent",
        "Click to continue drawing the polygon"
      );

      this.helpTooltip.setPosition(evt.coordinate);
      this.renderer.removeClass(this.helpTooltipElement, "hidden");
    });
  }


createHelpTooltip() {
    if (this.helpTooltipElement) {
      // this.helpTooltipElement.parentNode.removeChild(this.helpTooltipElement);
      this.el.nativeElement.remove(this.helpTooltipElement);
    }

    this.helpTooltipElement = this.renderer.createElement("div");
    this.renderer.addClass(this.helpTooltipElement, "ol-tooltip");
    this.renderer.addClass(this.helpTooltipElement, "hidden");
    this.renderer.appendChild(this.el.nativeElement, this.helpTooltipElement);

    this.helpTooltip = new Overlay({
      element: this.helpTooltipElement,
      offset: [15, 0],
      positioning: OverlayPositioning.CENTER_LEFT
    });
    this.map.addOverlay(this.helpTooltip);
  }


createMeasureTooltip() {
    if (this.measureTooltipElement) {
      this.renderer.removeChild(
        this.el.nativeElement,
        this.measureTooltipElement
      );
    }
    this.measureTooltipElement = this.renderer.createElement("div");
    this.renderer.addClass(this.measureTooltipElement, "ol-tooltip");
    this.renderer.addClass(this.measureTooltipElement, "ol-tooltip-measure");
    this.renderer.appendChild(
      this.el.nativeElement,
      this.measureTooltipElement
    );

    this.measureTooltip = new Overlay({
      element: this.measureTooltipElement,
      offset: [0, -15],
      positioning: OverlayPositioning.BOTTOM_CENTER
    });
    this.map.addOverlay(this.measureTooltip);
  }


startDraw() {
    this.enabledraw = false;
    this.enablesave = true;
    this.enableclear = true;

    this.draw = new Draw({
      source: this.source,
      type: this.geometryType
    });
    this.map.addInteraction(this.draw);
    this.snap = new Snap({ source: this.source });
    this.map.addInteraction(this.snap);

    // this.draw.on("drawend", event => {
    //   this.map.removeInteraction(this.draw);
    //   event.feature.setId(this.farmlocation.objid);
    // });

    // this.createMeasureTooltip();
    // this.addpointermovehandler();

    var listener;
    this.draw.on("drawstart", evt => {
      // set sketch
      this.sketch = evt.feature;

      var tooltipCoord = evt.coordinate;

      listener = this.sketch.getGeometry().on("change", evt => {
        var geom = evt.target;
        var output;
        if (geom instanceof Polygon) {
          output = this.formatArea(geom);
          tooltipCoord = geom.getInteriorPoint().getCoordinates();
        }
        this.renderer.setProperty(
          this.measureTooltipElement,
          "textContent",
          output
        );
        // this.measureTooltipElement.innerHTML = output;
        this.measureTooltip.setPosition(tooltipCoord);
      });
    });
    this.draw.on("drawend", evt => {
      // this.renderer.setProperty(this.measureTooltipElement, 'class', 'ol-tooltip ol-tooltip-static');
      // this.measureTooltip.setOffset([0, -7]);
      // unset sketch
      this.sketch = null;
      // unset tooltip so that a new one can be created
      this.measureTooltipElement = null;
      // this.createMeasureTooltip();
      unByKey(listener);

      this.map.removeInteraction(this.draw);
      evt.feature.setId(this.item.location.objid);
      evt.feature.setProperties({
        farmerid: this.farmerid,
        itemtype: this.type,
        itemid: this.item.objid
      });
    });
  }


startModify() {
    this.enablemodify = false;
    this.enabledraw = false;
    this.enablesave = true;
    this.enableclear = true;
    this.modify = new Modify({ source: this.source });
    this.map.addInteraction(this.modify);
    // this.addpointermovehandler();
  }


savePolygon() {
    let format = new GeoJSON();
    let data = format.writeFeatures(this.vector.getSource().getFeatures());
    this.item.location = {
      ...this.item.location,
      geolocation: JSON.parse(data)
    };
    this.farmerService.getItem(this.farmerid).then(item => {
      if (this.type === "commodity") {
        item.commodities = item.commodities.map(c =>
          c.objid === this.item.objid ? (c = this.item) : c
        );
      } else {
        item.livestocks = item.livestocks.map(l =>
          l.objid === this.item.objid ? (l = this.item) : l
        );
      }
      // console.log(item);
      this.farmerService.updatefarmer(item);
      this.mapService.saveItem(JSON.parse(data));
      this.farmlocationService.updateItem(this.item.location);
    });
    this.enablemodify = true;
    this.enablesave = false;
    this.enableclear = true;
    this.map.removeInteraction(this.draw);
    this.map.removeInteraction(this.modify);
    this.getalllayers();
    // this.renderer.addClass(this.helpTooltipElement, 'hidden');
  }


clearMap() {
    this.vector.getSource().clear();
    this.item.location = { ...this.item.location, geolocation: {} };
    this.farmerService.getItem(this.farmerid).then(item => {
      if (this.type === "commodity") {
        item.commodities = item.commodities.map(c =>
          c.objid === this.item.objid ? (c = this.item) : c
        );
      } else {
        item.livestocks = item.livestocks.map(l =>
          l.objid === this.item.objid ? (l = this.item) : l
        );
      }

      this.farmerService.updatefarmer(item);
      this.mapService.deleteItem(this.item.location.objid);
      this.farmlocationService.updateItem(this.item.location);
    });
    this.enabledraw = true;
    this.enablemodify = false;
    this.enablesave = false;
    this.enableclear = false;
    this.getalllayers();
  }


private getBrgyBoundaries(): Observable<any[]> {
    return this.httpClient.get<any[]>("assets/barangay.json");
  }


dismissModal() {
    this.modalCtrl.dismiss({
      'dismissed': true
    });
  }


export class FormDefinition extends Identifier implements IFormDefinition {
  private readonly node: StatementNode;
  private readonly parameters: TypedIdentifier[];
  private readonly tableParameters: TypedIdentifier[];
  private readonly usingParameters: TypedIdentifier[];
  private readonly changingParameters: TypedIdentifier[];

  public constructor(node: StructureNode | StatementNode, filename: string, scope: CurrentScope) {
    const st = node instanceof StructureNode ? node.findFirstStatement(Statements.Form)! : node;

    // FORMs can contain a dash in the name
    const pos = st.findFirstExpression(Expressions.FormName)!.getFirstToken().getStart();
    const name = st.findFirstExpression(Expressions.FormName)!.concatTokens();
    const nameToken = new Tokens.Identifier(pos, name);

    super(nameToken, filename);
    this.node = st;

    this.parameters = this.findParams(this.node, scope);
    this.tableParameters = this.findType(Expressions.FormTables, scope);
    this.usingParameters = this.findType(Expressions.FormUsing, scope);
    this.changingParameters = this.findType(Expressions.FormChanging, scope);
  }

  public getParameters(): TypedIdentifier[] {
    return this.parameters;
  }

  public getTablesParameters(): TypedIdentifier[] {
    return this.tableParameters;
  }

  public getUsingParameters(): TypedIdentifier[] {
    return this.usingParameters;
  }

  public getChangingParameters(): TypedIdentifier[] {
    return this.changingParameters;
  }

///////////////

  private findType(type: new () => Expression, scope: CurrentScope): TypedIdentifier[] {
    const found = this.node.findFirstExpression(type);
    if (found === undefined) {
      return [];
    }
    return this.findParams(found, scope);
  }

  private findParams(node: ExpressionNode | StatementNode, scope: CurrentScope) {
    const res: TypedIdentifier[] = [];
    for (const param of node.findAllExpressions(Expressions.FormParam)) {
//      const para = param.get() as Expressions.FormParam;
      res.push(new FormParam().runSyntax(param, scope, this.filename));
    }
    return res;
  }

}


public getParameters(): TypedIdentifier[] {
    return this.parameters;
  }


public getTablesParameters(): TypedIdentifier[] {
    return this.tableParameters;
  }


public getUsingParameters(): TypedIdentifier[] {
    return this.usingParameters;
  }


public getChangingParameters(): TypedIdentifier[] {
    return this.changingParameters;
  }


///////////////
private findType(type: new () => Expression, scope: CurrentScope): TypedIdentifier[] {
    const found = this.node.findFirstExpression(type);
    if (found === undefined) {
      return [];
    }
    return this.findParams(found, scope);
  }


private findParams(node: ExpressionNode | StatementNode, scope: CurrentScope) {
    const res: TypedIdentifier[] = [];
    for (const param of node.findAllExpressions(Expressions.FormParam)) {
//      const para = param.get() as Expressions.FormParam;
      res.push(new FormParam().runSyntax(param, scope, this.filename));
    }
    return res;
  }


export interface Card {
  suit: Suit
  number: number
}


export enum Suit {
  SPADE,
  HEART,
  CLUB,
  DIAMOND
}


export type Deck = Card[]


export type StateMapper = (prevState: Poker99State) => Poker99State


export type IsCard = (card: Card) => boolean


export type PlayCard = (payload: PlayCardPayload, playerId: number) => StateMapper


async () => {
		await employees.insertMany({ documents: [Employee.new({})] });
		await employees.drop({ name: "testing-employees" });
	}


async () => {
		const operation = await employees.createOne({
			document: Employee.new({}),
		});
		expect(operation.result.n).eq(1);
	}


async () => {
		const operation = await employees.createMany({
			documents: [
				Employee.new({
					name: "alex",
					email: "alex@gmail.com",
					salary: 1,
					children: [{ name: "al", age: 1 }],
				}),
				Employee.new({
					name: "john",
					email: "john@gmail.com",
					salary: 3,
					children: [{ name: "jo", age: 1 }],
				}),
				Employee.new({
					name: "dina",
					email: "dina@gmail.com",
					salary: 4,
					children: [{ name: "di", age: 1 }],
				}),
				Employee.new({
					name: "bill",
					email: "bill@gmail.com",
					salary: 9,
					children: [{ name: "bi", age: 1 }],
				}),
				Employee.new({
					name: "samy",
					email: "samy@gmail.com",
					salary: 2,
					children: [{ name: "sa", age: 1 }],
				}),
				Employee.new({
					name: "eddy",
					email: "eddy@gmail.com",
					salary: 6,
					children: [{ name: "ed", age: 1 }],
				}),
				Employee.new({
					name: "dann",
					email: "dann@gmail.com",
					salary: 7,
					children: [{ name: "da", age: 1 }],
				}),
				Employee.new({
					name: "eliz",
					email: "eliz@gmail.com",
					salary: 8,
					children: [{ name: "el", age: 1 }],
				}),
				Employee.new({
					name: "rich",
					email: "rich@gmail.com",
					salary: 5,
					children: [{ name: "ri", age: 1 }],
				}),
			],
		});
		expect(operation.result.n).eq(9);
	}


async () => {
		expect((await employees.find({})).length).eq(10);
	}


async () => {
		const doc = await employees.findOne({ filter: { name: "samy" } });
		expect(doc.salary).eq(2);
	}


async () => {
		const operationA = await employees.read({
			limit: 5,
			skip: 0,
			sort: { key: "name", direction: 1 },
		});
		const operationB = await employees.read({
			limit: 5,
			skip: 5,
			sort: { key: "name", direction: 1 },
		});

		const operationAIds = operationA.map((x) => x._id);
		const operationANames = operationA.map((x) => x.name);

		const operationBIds = operationB.map((x) => x._id);
		const operationBNames = operationB.map((x) => x.name);

		expect(operationANames.length).eq(5);
		expect(operationBNames.length).eq(5);
		expect(JSON.stringify(operationANames)).eq(
			JSON.stringify(operationANames.sort())
		);
		expect(JSON.stringify(operationBNames)).eq(
			JSON.stringify(operationBNames.sort())
		);
		expect([...new Set(operationAIds.concat(operationBIds))].length).eq(10);
	}


(x) => x._id


(x) => x.name


async () => {
		const newDocument = Employee.new({ name: "jack" });
		const replacementOperation = await employees.replaceOne({
			filter: { name: "alex" },
			document: newDocument,
			upsert: false,
		});

		const readOperation = await employees.read({
			filter: { name: newDocument.name },
		});

		expect(replacementOperation.result.nModified).eq(readOperation.length);
	}


async () => {
		const newDocument = Employee.new({ name: "alberto" });
		const replacementOperation = await employees.replaceOne({
			filter: { name: "ricardo" },
			document: newDocument,
			upsert: true,
		});
		const readOperation = await employees.read({
			filter: { name: newDocument.name },
		});
		expect(replacementOperation.upsertedCount).eq(1);
		expect(readOperation.length).eq(1);
	}


async () => {
		const newDocument = Employee.new({ name: "william" });
		const replacementOperation = await employees.replaceOne({
			filter: { name: "ricardo" },
			document: newDocument,
			upsert: false,
		});

		const readOperation = await employees.read({
			filter: { name: newDocument.name },
		});

		expect(replacementOperation.result.nModified).eq(0);
		expect(readOperation.length).eq(0);
	}


async () => {
		const deleteOperation = await employees.deleteOne({
			filter: { name: "alberto" },
		});
		const readOperation = await employees.read({
			filter: { name: "alberto" },
		});

		expect(deleteOperation.result.n).eq(1);
		expect(readOperation.length).eq(0);
	}


async () => {
		const deleteOperation = await employees.deleteMany({
			filter: { salary: { $lt: 5 } },
		});
		const readOperation = await employees.read({
			filter: { salary: { $lt: 5 } },
		});
		expect(deleteOperation.result.n).not.eq(0);
		expect(readOperation.length).eq(0);
	}


async () => {
		await employees.insertMany({
			documents: [
				Employee.new({ name: "john", salary: 99 }),
				Employee.new({ name: "alex", salary: 99 }),
				Employee.new({ name: "robert", salary: 99 }),
				Employee.new({ name: "peet", salary: 99 }),
				Employee.new({ name: "sarah", salary: 99 }),
			],
		});
		const count = await employees.count({ filter: { salary: 99 } });
		expect(count).eq(5);
	}


async () => {
		const distinctNames = await employees.readDistinct({
			key: "name",
		});
		const name = distinctNames[0];
		if (name) {
			const r = await employees.read({ filter: { name } });
			expect(r.length).eq(1);
		}
	}


async () => {
		const operation = await employees.createIndex({
			key: "email",
			unique: false,
			background: true,
			dropDups: true,
			sparse: true,
		});
		expect(typeof operation).eq("string");
	}


async () => {
		const operation = await employees.aggregate<{ _id: number, count: number }>({
			pipeline: [
				{
					$match: { salary: 99 },
				},
				{
					$group: {
						_id: "$salary",
						count: { $sum: 1 }
					}
				}
			]
		});
		expect(operation[0].count).eq(5);
	}