public gameStarted(...args: any[]): void {
        if (null === this.platform) {
            //Silently return for when no platform is set
            return
        }

        this.platform.gameStarted.apply(this.platform, args)
    }


public getGameSettings(...args: any[]): any {
        if (null === this.platform) {
            //Silently return for when no platform is set
            return
        }

        this.platform.getGameSettings.apply(this.platform, args)
    }


public gameEnded(fail: boolean, score?: number, level?: number | string, ...args: any[]): void {
        if (null === this.platform) {
            throw new Error(
                'Can not request an ad without an provider, please attach an ad provider!'
            )
        }

        this.platform.gameEnded.apply(this.platform, args)

        if (score) {
            this.sendScore(score)
        }
    }


public gamePaused(...args: any[]): void {
        if (null === this.platform) {
            //Silently return for when no platform is set
            return
        }

        this.platform.gamePaused.apply(this.platform, args)
    }


public gameResumed(...args: any[]): void {
        if (null === this.platform) {
            //Silently return for when no platform is set
            return
        }

        this.platform.gameResumed.apply(this.platform, args)
    }


public sendScore(score: number): void {
        if (null === this.platform) {
            //Silently return for when no platform is set
            return
        }

        this.platform.sendScore.apply(this.platform, score)
    }


export declare class CategoriesController {
    private categoriesService;
    constructor(categoriesService: CategoriesService);
    getAllCategories(limit: number, offset: number, brand: string): import("../entitis/categories.entity").Categories[];
    getCategories(productId: number): import("../entitis/categories.entity").Categories;
    createCategories(payload: CreateCategorie): {
        name: string;
        stock: number;
        logo: string;
        id: number;
    };
    updateCategorie(id: number, payload: UpdateCategories): {
        id: number;
        name: string;
        stock: number;
        logo?: string;
    };
    delete(id: number): boolean;
}


getAllCategories(limit: number, offset: number, brand: string): import("../entitis/categories.entity").Categories[];


getCategories(productId: number): import("../entitis/categories.entity").Categories;


createCategories(payload: CreateCategorie): {
        name: string;
        stock: number;
        logo: string;
        id: number;
    };


updateCategorie(id: number, payload: UpdateCategories): {
        id: number;
        name: string;
        stock: number;
        logo?: string;
    };


delete(id: number): boolean;


(routeProps: RouteProperties) => routeProps.route === route


@Injectable({
  providedIn: 'root'
})
export class ProjectMapService {

  projectData: Project;

  constructor() {
    this.projectData = projectData;
  }

  getRoute(route: string) {
    const found = this.findRoute(route);
    return (found > -1) ? this.projectData.routes[found] : undefined;
  }

  setRoute(routeProps: RouteProperties) {
    routeProps.route = this.normalizeRoute(routeProps.route);
    const found = this.findRoute(routeProps.route);
    if (found > -1) {
      this.projectData.routes[found] = routeProps;
    } else {
      this.projectData.routes.push(routeProps);
    }
  }

  findRoute(route: string): number {
    route = this.normalizeRoute(route);
    return this.projectData.routes.findIndex((routeProps: RouteProperties) => routeProps.route === route);
  }

  normalizeRoute(route: string): string {
    if ( route === '' ) {
      route = '/';
    }
    return route;
  }

  getGlobalExits() {
    return this.projectData.globalExits;
  }

  setGlobalExits(globalExits: Exit[]) {
    this.projectData.globalExits = globalExits;
  }

  export() {
    const a = document.createElement('a');
    a.href = URL.createObjectURL(
      new Blob([JSON.stringify(this.projectData)], {type: 'application/json'})
    );
    a.download = 'project.json';
    a.click();
  }

  reset() {
    this.projectData = {
      routes: [
        {
          route: '/',
          description: 'Homepage for the website',
          exits: [],
          forms: []
        }
      ],
      globalExits: [
        {
          route: '/',
          visibleText: 'Home',
          routeLocations: ['']
        }
      ]
    };
  }
}


getRoute(route: string) {
    const found = this.findRoute(route);
    return (found > -1) ? this.projectData.routes[found] : undefined;
  }


setRoute(routeProps: RouteProperties) {
    routeProps.route = this.normalizeRoute(routeProps.route);
    const found = this.findRoute(routeProps.route);
    if (found > -1) {
      this.projectData.routes[found] = routeProps;
    } else {
      this.projectData.routes.push(routeProps);
    }
  }


findRoute(route: string): number {
    route = this.normalizeRoute(route);
    return this.projectData.routes.findIndex((routeProps: RouteProperties) => routeProps.route === route);
  }


normalizeRoute(route: string): string {
    if ( route === '' ) {
      route = '/';
    }
    return route;
  }


getGlobalExits() {
    return this.projectData.globalExits;
  }


setGlobalExits(globalExits: Exit[]) {
    this.projectData.globalExits = globalExits;
  }


export() {
    const a = document.createElement('a');
    a.href = URL.createObjectURL(
      new Blob([JSON.stringify(this.projectData)], {type: 'application/json'})
    );
    a.download = 'project.json';
    a.click();
  }


reset() {
    this.projectData = {
      routes: [
        {
          route: '/',
          description: 'Homepage for the website',
          exits: [],
          forms: []
        }
      ],
      globalExits: [
        {
          route: '/',
          visibleText: 'Home',
          routeLocations: ['']
        }
      ]
    };
  }


(proxy) => (
                  <li className="nav-item"


export class NetworkView extends React.PureComponent<NetworkProps> {
  constructor(props: NetworkProps) {
    super(props);
    if (props.selectedProxyId === undefined && props.proxies.length > 0) {
      props.setSelectedProxyId(props.proxies[0].id);
    }
  }

  render() {
    const { isInstanceSelected, proxies, selectedProxyId, setSelectedProxyId } = this.props;
    if (!isInstanceSelected) {
      return
Select Muster instance to begin
;
    }
    return (
      <>
        {selectedProxyId === undefined && (

Select Proxy instance to begin

        )}


export interface MiddlewareProxy {
  id: string;
  path: Array<any>;
}


export interface NetworkProps {
  isInstanceSelected: boolean;
  proxies: Array<MiddlewareProxy>;
  selectedProxyId: string | undefined;
  setSelectedProxyId: (value: string | undefined) => void;
}


render() {
    const { isInstanceSelected, proxies, selectedProxyId, setSelectedProxyId } = this.props;
    if (!isInstanceSelected) {
      return
Select Muster instance to begin
;
    }
    return (
      <>
        {selectedProxyId === undefined && (

Select Proxy instance to begin

        )}


classnames('nav-link', { active: selectedProxyId


() => {
  beforeEach(() => {
    cy.login();
    cy.goToAdultMeasures();
    cy.goToMeasure("HVL-AD");
  });

  it("Ensure correct sections display if user is/not reporting", () => {
    cy.displaysSectionsWhenUserNotReporting();
    cy.displaysSectionsWhenUserIsReporting();
  });

  it("If not reporting and not why not -> show error", () => {
    cy.get('[data-cy="DidReport1"]').click();
    cy.get('[data-cy="Validate Measure"]').click();
    cy.get(
      '[data-cy="Why Are You Not Reporting On This Measure Error"]'
    ).should("have.text", "Why Are You Not Reporting On This Measure Error");
  });

  it("should show correct measurement spec", () => {
    cy.get("#MeasurementSpecification-HRSA").should(
      "have.text",
      "Health Resources and Services Administration (HRSA)"
    );
  });

  it("should show correct data source options", () => {
    cy.get(
      '[data-cy="DataSource0"] > .chakra-checkbox__label > .chakra-text'
    ).should("have.text", "Administrative Data");
    cy.get(
      '[data-cy="DataSource1"] > .chakra-checkbox__label > .chakra-text'
    ).should("have.text", "Electronic Health Records");
    cy.get(
      '[data-cy="DataSource2"] > .chakra-checkbox__label > .chakra-text'
    ).should("have.text", "Other Data Source");
  });

  it("if primary measurement spec is selected -> show performance measures", () => {
    cy.get("#MeasurementSpecification-HRSA").click();
    cy.get('[data-cy="Performance Measure"]').should(
      "have.text",
      "Performance Measure"
    );
    cy.get('[data-cy="Ages 18 to 64"]').should("have.text", "Ages 18 to 64");
    cy.get('[data-cy="Age 65 and older"]').should(
      "have.text",
      "Age 65 and older"
    );
  });

  it("if other measurement spec is selected -> show other performance measures", () => {
    cy.get('[data-cy="DidReport0"]').click();
    cy.get('[data-cy="MeasurementSpecification1"]').click();
    cy.get(
      '[data-cy="MeasurementSpecification-OtherMeasurementSpecificationDescription"]'
    ).should("be.visible");
    cy.get('[data-cy="Other Performance Measure"]').should("be.visible");
  });

  it("if only admin data cannot override, if anything else, rate is editable", () => {
    cy.get("#MeasurementSpecification-HRSA").click();
    cy.get(
      '[data-cy="PerformanceMeasure.rates.singleCategory.0.numerator"]'
    ).type("5");
    cy.get(
      '[data-cy="PerformanceMeasure.rates.singleCategory.0.denominator"]'
    ).type("5");
    cy.get('[data-cy="DataSource2"] > .chakra-checkbox__control').click();
    cy.get('[data-cy="PerformanceMeasure.rates.singleCategory.0.rate"]').should(
      "not.have.attr",
      "aria-readonly"
    );
  });

  it("at least one dnr set if reporting and measurement spec or error.", () => {
    cy.get('[data-cy="DidReport0"]').click();
    cy.get('[data-cy="Validate Measure"]').click();
    cy.get(
      '[data-cy="Performance Measure/Other Performance Measure Error"]'
    ).should("be.visible");
  });

  it("if yes for combined rates → and no additional selection → show warning", () => {
    cy.get('[data-cy="DidReport0"]').click();
    cy.get('[data-cy="MeasurementSpecification0"]').click();
    cy.get('[data-cy="CombinedRates0"]').click();
    cy.get('[data-cy="Validate Measure"]').click();
    cy.get(
      '[data-cy="You must select at least one option for Combined Rate(s) Details if Yes is selected."]'
    ).should(
      "have.text",
      "You must select at least one option for Combined Rate(s) Details if Yes is selected."
    );
  });
}


() => {
    cy.login();
    cy.goToAdultMeasures();
    cy.goToMeasure("HVL-AD");
  }


() => {
    cy.displaysSectionsWhenUserNotReporting();
    cy.displaysSectionsWhenUserIsReporting();
  }


() => {
    cy.get('[data-cy="DidReport1"]').click();
    cy.get('[data-cy="Validate Measure"]').click();
    cy.get(
      '[data-cy="Why Are You Not Reporting On This Measure Error"]'
    ).should("have.text", "Why Are You Not Reporting On This Measure Error");
  }


() => {
    cy.get("#MeasurementSpecification-HRSA").should(
      "have.text",
      "Health Resources and Services Administration (HRSA)"
    );
  }


() => {
    cy.get(
      '[data-cy="DataSource0"] > .chakra-checkbox__label > .chakra-text'
    ).should("have.text", "Administrative Data");
    cy.get(
      '[data-cy="DataSource1"] > .chakra-checkbox__label > .chakra-text'
    ).should("have.text", "Electronic Health Records");
    cy.get(
      '[data-cy="DataSource2"] > .chakra-checkbox__label > .chakra-text'
    ).should("have.text", "Other Data Source");
  }


() => {
    cy.get("#MeasurementSpecification-HRSA").click();
    cy.get('[data-cy="Performance Measure"]').should(
      "have.text",
      "Performance Measure"
    );
    cy.get('[data-cy="Ages 18 to 64"]').should("have.text", "Ages 18 to 64");
    cy.get('[data-cy="Age 65 and older"]').should(
      "have.text",
      "Age 65 and older"
    );
  }


() => {
    cy.get('[data-cy="DidReport0"]').click();
    cy.get('[data-cy="MeasurementSpecification1"]').click();
    cy.get(
      '[data-cy="MeasurementSpecification-OtherMeasurementSpecificationDescription"]'
    ).should("be.visible");
    cy.get('[data-cy="Other Performance Measure"]').should("be.visible");
  }


() => {
    cy.get("#MeasurementSpecification-HRSA").click();
    cy.get(
      '[data-cy="PerformanceMeasure.rates.singleCategory.0.numerator"]'
    ).type("5");
    cy.get(
      '[data-cy="PerformanceMeasure.rates.singleCategory.0.denominator"]'
    ).type("5");
    cy.get('[data-cy="DataSource2"] > .chakra-checkbox__control').click();
    cy.get('[data-cy="PerformanceMeasure.rates.singleCategory.0.rate"]').should(
      "not.have.attr",
      "aria-readonly"
    );
  }


() => {
    cy.get('[data-cy="DidReport0"]').click();
    cy.get('[data-cy="Validate Measure"]').click();
    cy.get(
      '[data-cy="Performance Measure/Other Performance Measure Error"]'
    ).should("be.visible");
  }


() => {
    cy.get('[data-cy="DidReport0"]').click();
    cy.get('[data-cy="MeasurementSpecification0"]').click();
    cy.get('[data-cy="CombinedRates0"]').click();
    cy.get('[data-cy="Validate Measure"]').click();
    cy.get(
      '[data-cy="You must select at least one option for Combined Rate(s) Details if Yes is selected."]'
    ).should(
      "have.text",
      "You must select at least one option for Combined Rate(s) Details if Yes is selected."
    );
  }


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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SpringBootAngularCrudComponent ]
    })
    .compileComponents();
  }));

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

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


() => {
    TestBed.configureTestingModule({
      declarations: [ SpringBootAngularCrudComponent ]
    })
    .compileComponents();
  }


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


export class TaskStatusValidationPipe implements PipeTransform {
    readonly allowedStatuses = [
      TaskStatus.OPEN,
        TaskStatus.IN_PROGRESS,
        TaskStatus.DONE,
    ];
    transform(value: any){
        value = value.toUpperCase();

        if (!this.isStatusValid(value)) {
            throw new BadRequestException(`"${value}" is an invalid status`);
        }

        return value;
    }

    private isStatusValid(status: any) {
        const idx = this.allowedStatuses.indexOf(status);
        return idx !== -1;
    }
}


transform(value: any){
        value = value.toUpperCase();

        if (!this.isStatusValid(value)) {
            throw new BadRequestException(`"${value}" is an invalid status`);
        }

        return value;
    }


private isStatusValid(status: any) {
        const idx = this.allowedStatuses.indexOf(status);
        return idx !== -1;
    }


(...args) => args.join('_')


({ facet, config }) => ({
    items: facet.get('values')
  })


export default function TourmalineJewelersSvgComponent(props: { icon: Icon }) {
  return (
    <Svg width={props.icon.width} height={props.icon.height} viewBox="0 0 512 512">
      <G fill={props.icon.color}>
        <Polygon points="393.06 130.05 393.06 36.854 293.87 36.854"/>
        <Polygon points="141.81 149.73 370.19 149.73 256 42.436"/>
        <Polygon points="385.13 179.73 126.87 179.73 256 475.15"/>
        <Polygon points="118.94 130.05 218.13 36.854 118.94 36.854"/>
        <Polygon points="88.938 149.73 88.938 59.447 3.25 149.73"/>
        <Polygon points="423.06 149.73 508.75 149.73 423.06 59.447"/>
        <Polygon points="417.88 179.73 312.55 420.67 512 179.73"/>
        <Polygon points="94.125 179.73 0 179.73 199.45 420.67"/>
      </G>
    </Svg>
  );
}


() => Highcharts


@NgModule({
	declarations: [HighchartsDirective],
	exports: [HighchartsDirective],
})
export class HighchartsModule {}


(image: any, layer: SKLayer): Image => {
    // 画板图赋值
    if (layer._class === 'artboard') {
        image.value = layer.imageUrl;
    // 切片转换为图片
    } else if (layer.imageUrl) {
        image.type = 'Image';
        image.value = layer.imageUrl;
    }

    return image;
}


function isRenderLocation(node: Node): node is Node & IRenderLocation {
  return node.textContent === 'au-end';
}


() => NodeSequence.empty


proto => {
  proto.previousSibling = null!;
  proto.childNodes = PLATFORM.emptyArray;
  proto.nodeName = 'AU-M';
  proto.nodeType = NodeType.Element;
}


/**
 * IDOM implementation for Html.
 */
export class HTMLDOM implements IDOM {
  public readonly Node: typeof Node;
  public readonly Element: typeof Element;
  public readonly HTMLElement: typeof HTMLElement;
  public readonly CustomEvent: typeof CustomEvent;
  public readonly window: Window;
  public readonly document: Document;

  constructor(
    window: Window,
    document: Document,
    TNode: typeof Node,
    TElement: typeof Element,
    THTMLElement: typeof HTMLElement,
    TCustomEvent: typeof CustomEvent
  ) {
    this.window = window;
    this.document = document;
    this.Node = TNode;
    this.Element = TElement;
    this.HTMLElement = THTMLElement;
    this.CustomEvent = TCustomEvent;
    if (DOM.isInitialized) {
      Reporter.write(1001); // TODO: create reporters code // DOM already initialized (just info)
      DOM.destroy();
    }
    DOM.initialize(this);
  }

  public static register(container: IContainer): IResolver<HTMLDOM> {
    return Registration.alias(IDOM, this).register(container);
  }

  public addEventListener(eventName: string, subscriber: EventListenerOrEventListenerObject, publisher?: Node, options?: boolean | AddEventListenerOptions): void {
    (publisher || this.document).addEventListener(eventName, subscriber, options);
  }

  public appendChild(parent: Node, child: Node): void {
    parent.appendChild(child);
  }

  public cloneNode<T>(node: T, deep?: boolean): T {
    return (node as unknown as Node).cloneNode(deep !== false) as unknown as T;
  }

  public convertToRenderLocation(node: Node): IRenderLocation {
    if (this.isRenderLocation(node)) {
      return node; // it's already a IRenderLocation (converted by FragmentNodeSequence)
    }

    if (node.parentNode == null) {
      throw Reporter.error(52);
    }

    const locationEnd = this.document.createComment('au-end');
    const locationStart = this.document.createComment('au-start');

    node.parentNode.replaceChild(locationEnd, node);

    locationEnd.parentNode!.insertBefore(locationStart, locationEnd);

    (locationEnd as IRenderLocation).$start = locationStart as IRenderLocation;
    (locationStart as IRenderLocation).$nodes = null!;

    return locationEnd as IRenderLocation;
  }

  public createDocumentFragment(markupOrNode?: string | Node): DocumentFragment {
    if (markupOrNode == null) {
      return this.document.createDocumentFragment();
    }

    if (this.isNodeInstance(markupOrNode)) {
      if ((markupOrNode as HTMLTemplateElement).content !== undefined) {
        return (markupOrNode as HTMLTemplateElement).content;
      }

      const fragment = this.document.createDocumentFragment();
      fragment.appendChild(markupOrNode);
      return fragment;
    }

    return this.createTemplate(markupOrNode).content;
  }

  public createElement(name: string): HTMLElement {
    return this.document.createElement(name);
  }

  public fetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
    return this.window.fetch(input, init);
  }

  // tslint:disable-next-line:no-any // this is how the DOM is typed
  public createCustomEvent<T = any>(eventType: string, options?: CustomEventInit<T>): CustomEvent<T> {
    return new this.CustomEvent(eventType, options);
  }

  public dispatchEvent(evt: Event): void {
    this.document.dispatchEvent(evt);
  }

  public createNodeObserver(node: Node, cb: MutationCallback, init: MutationObserverInit): MutationObserver {
    if (typeof MutationObserver === 'undefined') {
      // TODO: find a proper response for this scenario
      return {
        disconnect(): void { /*empty*/ },
        observe(): void { /*empty*/ },
        takeRecords(): MutationRecord[] { return PLATFORM.emptyArray as typeof PLATFORM.emptyArray & MutationRecord[]; }
      };
    }

    const observer = new MutationObserver(cb);
    observer.observe(node, init);
    return observer;
  }

  public createTemplate(markup?: unknown): HTMLTemplateElement {
    if (markup == null) {
      return this.document.createElement('template');
    }

    const template = this.document.createElement('template');
    template.innerHTML = (markup as string | object).toString();

    return template;
  }
  public createTextNode(text: string): Text {
    return this.document.createTextNode(text);
  }

  public insertBefore(nodeToInsert: Node, referenceNode: Node): void {
    referenceNode.parentNode!.insertBefore(nodeToInsert, referenceNode);
  }

  public isMarker(node: unknown): node is HTMLElement {
    return (node as AuMarker).nodeName === 'AU-M';
  }

  public isNodeInstance(potentialNode: unknown): potentialNode is Node {
    return potentialNode != null && (potentialNode as Node).nodeType > 0;
  }

  public isRenderLocation(node: unknown): node is IRenderLocation {
    return (node as Comment).textContent === 'au-end';
  }

  public makeTarget(node: unknown): void {
    (node as Element).className = 'au';
  }

  public registerElementResolver(container: IContainer, resolver: IResolver): void {
    container.registerResolver(INode, resolver);
    container.registerResolver(this.Node, resolver);
    container.registerResolver(this.Element, resolver);
    container.registerResolver(this.HTMLElement, resolver);
  }

  public remove(node: Node): void {
    if ((node as ChildNode).remove) {
      (node as ChildNode).remove();
    } else {
      node.parentNode!.removeChild(node);
    }
  }

  public removeEventListener(eventName: string, subscriber: EventListenerOrEventListenerObject, publisher?: Node, options?: boolean | EventListenerOptions): void {
    (publisher || this.document).removeEventListener(eventName, subscriber, options);
  }

  public setAttribute(node: Element, name: string, value: unknown): void {
    node.setAttribute(name, value as string);
  }
}


/**
 * A specialized INodeSequence with optimizations for text (interpolation) bindings
 * The contract of this INodeSequence is:
 * - the previous element is an `au-m` node
 * - text is the actual text node
 */
/** @internal */
export class TextNodeSequence implements INodeSequence {
  public isMounted: boolean;
  public isLinked: boolean;

  public dom: HTMLDOM;
  public firstChild: Text;
  public lastChild: Text;
  public childNodes: Text[];

  public next?: INodeSequence<Node>;

  private refNode?: Node;

  private readonly targets: [Node];

  constructor(dom: HTMLDOM, text: Text) {
    this.isMounted = false;
    this.isLinked = false;

    this.dom = dom;
    this.firstChild = text;
    this.lastChild = text;
    this.childNodes = [text];
    this.targets = [new AuMarker(text) as unknown as Node];

    this.next = void 0;

    this.refNode = void 0;
  }

  public findTargets(): ArrayLike<Node> {
    return this.targets;
  }

  public insertBefore(refNode: Node): void {
    if (this.isLinked && !!this.refNode) {
      this.addToLinked();
    } else {
      this.isMounted = true;
      refNode.parentNode!.insertBefore(this.firstChild, refNode);
    }
  }

  public appendTo(parent: Node): void {
    if (this.isLinked && !!this.refNode) {
      this.addToLinked();
    } else {
      this.isMounted = true;
      parent.appendChild(this.firstChild);
    }
  }

  public remove(): void {
    this.isMounted = false;
    this.firstChild.remove();
  }

  public addToLinked(): void {
    const refNode = this.refNode!;
    this.isMounted = true;
    refNode.parentNode!.insertBefore(this.firstChild, refNode);
  }

  public unlink(): void {
    this.isLinked = false;
    this.next = void 0;
    this.refNode = void 0;
  }

  public link(next: INodeSequence<Node> | (IRenderLocation & Comment) | undefined): void {
    this.isLinked = true;
    if (this.dom.isRenderLocation(next)) {
      this.refNode = next;
    } else {
      this.next = next;
      this.obtainRefNode();
    }
  }

  private obtainRefNode(): void {
    if (this.next !== void 0) {
      this.refNode = this.next.firstChild;
    } else {
      this.refNode = void 0;
    }
  }
}


// tslint:enable:no-any
// This is the most common form of INodeSequence.
// Every custom element or template controller whose node sequence is based on an HTML template
// has an instance of this under the hood. Anyone who wants to create a node sequence from
// a string of markup would also receive an instance of this.
// CompiledTemplates create instances of FragmentNodeSequence.
/**
 * This is the most common form of INodeSequence.
 * @internal
 */
export class FragmentNodeSequence implements INodeSequence {
  public isMounted: boolean;
  public isLinked: boolean;

  public dom: IDOM;
  public firstChild: Node;
  public lastChild: Node;
  public childNodes: Node[];

  public next?: INodeSequence<Node>;

  private refNode?: Node;

  private readonly fragment: DocumentFragment;
  private readonly targets: ArrayLike<Node>;

  constructor(dom: IDOM, fragment: DocumentFragment) {
    this.isMounted = false;
    this.isLinked = false;

    this.dom = dom;
    this.fragment = fragment;
    // tslint:disable-next-line:no-any
    const targetNodeList = fragment.querySelectorAll('.au');
    let i = 0;
    let ii = targetNodeList.length;
    const targets = this.targets = Array(ii);

    while (i < ii) {
      // eagerly convert all markers to RenderLocations (otherwise the renderer
      // will do it anyway) and store them in the target list (since the comments
      // can't be queried)
      const target = targetNodeList[i];

      if (target.nodeName === 'AU-M') {
        // note the renderer will still call this method, but it will just return the
        // location if it sees it's already a location
        targets[i] = this.dom.convertToRenderLocation(target);
      } else {
        // also store non-markers for consistent ordering
        targets[i] = target;
      }
      ++i;
    }

    const childNodeList = fragment.childNodes;
    i = 0;
    ii = childNodeList.length;
    const childNodes = this.childNodes = Array(ii);
    while (i < ii) {
      childNodes[i] = childNodeList[i] as Writable<Node>;
      ++i;
    }

    this.firstChild = fragment.firstChild!;
    this.lastChild = fragment.lastChild!;

    this.next = void 0;

    this.refNode = void 0;
  }

  public findTargets(): ArrayLike<Node> {
    return this.targets;
  }

  public insertBefore(refNode: IRenderLocation & Comment): void {
    if (this.isLinked && !!this.refNode) {
      this.addToLinked();
    } else {
      const parent = refNode.parentNode!;
      if (this.isMounted) {
        let current = this.firstChild;
        const end = this.lastChild;
        let next: Node;

        while (current != null) {
          next = current.nextSibling!;
          parent.insertBefore(current, refNode);

          if (current === end) {
            break;
          }

          current = next;
        }
      } else {
        this.isMounted = true;
        refNode.parentNode!.insertBefore(this.fragment, refNode);
      }
    }
  }

  public appendTo(parent: Node): void {
    if (this.isMounted) {
      let current = this.firstChild;
      const end = this.lastChild;
      let next: Node;

      while (current != null) {
        next = current.nextSibling!;
        parent.appendChild(current);

        if (current === end) {
          break;
        }

        current = next;
      }
    } else {
      this.isMounted = true;
      parent.appendChild(this.fragment);
    }
  }

  public remove(): void {
    if (this.isMounted) {
      this.isMounted = false;

      const fragment = this.fragment;
      const end = this.lastChild;
      let next: Node;

      let current = this.firstChild;
      while (current !== null) {
        next = current.nextSibling!;
        fragment.appendChild(current);

        if (current === end) {
          break;
        }

        current = next;
      }
    }
  }

  public addToLinked(): void {
    const refNode = this.refNode!;
    const parent = refNode.parentNode!;
    if (this.isMounted) {
      let current = this.firstChild;
      const end = this.lastChild;
      let next: Node;

      while (current != null) {
        next = current.nextSibling!;
        parent.insertBefore(current, refNode);

        if (current === end) {
          break;
        }

        current = next;
      }
    } else {
      this.isMounted = true;
      parent.insertBefore(this.fragment, refNode);
    }
  }

  public unlink(): void {
    this.isLinked = false;
    this.next = void 0;
    this.refNode = void 0;
  }

  public link(next: INodeSequence<Node> | IRenderLocation & Comment | undefined): void {
    this.isLinked = true;
    if (this.dom.isRenderLocation(next)) {
      this.refNode = next;
    } else {
      this.next = next;
      this.obtainRefNode();
    }
  }

  private obtainRefNode(): void {
    if (this.next !== void 0) {
      this.refNode = this.next.firstChild;
    } else {
      this.refNode = void 0;
    }
  }
}


export class NodeSequenceFactory implements NodeSequenceFactory {
  private readonly dom: IDOM;
  private readonly deepClone!: boolean;
  private readonly node!: Node;
  private readonly Type!: Constructable<INodeSequence>;

  constructor(dom: IDOM, markupOrNode: string | Node) {
    this.dom = dom;
    const fragment = dom.createDocumentFragment(markupOrNode) as DocumentFragment;
    const childNodes = fragment.childNodes;
    switch (childNodes.length) {
      case 0:
        this.createNodeSequence = () => NodeSequence.empty;
        return;
      case 2:
        const target = childNodes[0];
        if (target.nodeName === 'AU-M' || target.nodeName === '#comment') {
          const text = childNodes[1];
          if (text.nodeType === NodeType.Text && text.textContent!.length === 0) {
            this.deepClone = false;
            this.node = text;
            this.Type = TextNodeSequence;
            return;
          }
        }
      // falls through if not returned
      default:
        this.deepClone = true;
        this.node = fragment;
        this.Type = FragmentNodeSequence;
    }
  }

  public createNodeSequence(): INodeSequence {
    return new this.Type(this.dom, this.node.cloneNode(this.deepClone));
  }
}


/** @internal */
export class AuMarker implements INode {
  public get parentNode(): Node & ParentNode {
    return this.nextSibling.parentNode!;
  }

  public readonly nextSibling: Node;
  public readonly previousSibling!: Node;
  public readonly content?: Node;
  public readonly childNodes!: ArrayLike<ChildNode>;
  public readonly nodeName!: 'AU-M';
  public readonly nodeType!: NodeType.Element;

  public textContent: string;

  constructor(next: Node) {
    this.nextSibling = next;
    this.textContent = '';
  }

  public remove(): void { /* do nothing */ }
}


/** @internal */
export class HTMLTemplateFactory implements ITemplateFactory {
  public static readonly inject: InjectArray = [IDOM];

  private readonly dom: IDOM;

  constructor(dom: IDOM) {
    this.dom = dom;
  }

  public static register(container: IContainer): IResolver<ITemplateFactory> {
    return Registration.singleton(ITemplateFactory, this).register(container);
  }

  public create(parentRenderContext: IRenderContext, definition: TemplateDefinition): ITemplate {
    return new CompiledTemplate(this.dom, definition, new NodeSequenceFactory(this.dom, definition.template as string | Node), parentRenderContext);
  }
}


export interface NodeSequenceFactory {
  createNodeSequence(): INodeSequence;
}


export interface AuMarker extends INode { }


export const enum NodeType {
  Element = 1,
  Attr = 2,
  Text = 3,
  CDATASection = 4,
  EntityReference = 5,
  Entity = 6,
  ProcessingInstruction = 7,
  Comment = 8,
  Document = 9,
  DocumentType = 10,
  DocumentFragment = 11,
  Notation = 12
}


public static register(container: IContainer): IResolver<HTMLDOM> {
    return Registration.alias(IDOM, this).register(container);
  }


public addEventListener(eventName: string, subscriber: EventListenerOrEventListenerObject, publisher?: Node, options?: boolean | AddEventListenerOptions): void {
    (publisher || this.document).addEventListener(eventName, subscriber, options);
  }


public appendChild(parent: Node, child: Node): void {
    parent.appendChild(child);
  }


public cloneNode<T>(node: T, deep?: boolean): T {
    return (node as unknown as Node).cloneNode(deep !== false) as unknown as T;
  }


public convertToRenderLocation(node: Node): IRenderLocation {
    if (this.isRenderLocation(node)) {
      return node; // it's already a IRenderLocation (converted by FragmentNodeSequence)
    }

    if (node.parentNode == null) {
      throw Reporter.error(52);
    }

    const locationEnd = this.document.createComment('au-end');
    const locationStart = this.document.createComment('au-start');

    node.parentNode.replaceChild(locationEnd, node);

    locationEnd.parentNode!.insertBefore(locationStart, locationEnd);

    (locationEnd as IRenderLocation).$start = locationStart as IRenderLocation;
    (locationStart as IRenderLocation).$nodes = null!;

    return locationEnd as IRenderLocation;
  }


public createDocumentFragment(markupOrNode?: string | Node): DocumentFragment {
    if (markupOrNode == null) {
      return this.document.createDocumentFragment();
    }

    if (this.isNodeInstance(markupOrNode)) {
      if ((markupOrNode as HTMLTemplateElement).content !== undefined) {
        return (markupOrNode as HTMLTemplateElement).content;
      }

      const fragment = this.document.createDocumentFragment();
      fragment.appendChild(markupOrNode);
      return fragment;
    }

    return this.createTemplate(markupOrNode).content;
  }


public createElement(name: string): HTMLElement {
    return this.document.createElement(name);
  }


public fetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
    return this.window.fetch(input, init);
  }


// tslint:disable-next-line:no-any // this is how the DOM is typed
public createCustomEvent<T = any>(eventType: string, options?: CustomEventInit<T>): CustomEvent<T> {
    return new this.CustomEvent(eventType, options);
  }


public dispatchEvent(evt: Event): void {
    this.document.dispatchEvent(evt);
  }


public createNodeObserver(node: Node, cb: MutationCallback, init: MutationObserverInit): MutationObserver {
    if (typeof MutationObserver === 'undefined') {
      // TODO: find a proper response for this scenario
      return {
        disconnect(): void { /*empty*/ },
        observe(): void { /*empty*/ },
        takeRecords(): MutationRecord[] { return PLATFORM.emptyArray as typeof PLATFORM.emptyArray & MutationRecord[]; }
      };
    }

    const observer = new MutationObserver(cb);
    observer.observe(node, init);
    return observer;
  }


disconnect(): void { /*empty*/ }


observe(): void { /*empty*/ }


takeRecords(): MutationRecord[] { return PLATFORM.emptyArray as typeof PLATFORM.emptyArray & MutationRecord[]; }


public createTemplate(markup?: unknown): HTMLTemplateElement {
    if (markup == null) {
      return this.document.createElement('template');
    }

    const template = this.document.createElement('template');
    template.innerHTML = (markup as string | object).toString();

    return template;
  }


public createTextNode(text: string): Text {
    return this.document.createTextNode(text);
  }


public insertBefore(nodeToInsert: Node, referenceNode: Node): void {
    referenceNode.parentNode!.insertBefore(nodeToInsert, referenceNode);
  }


public isMarker(node: unknown): node is HTMLElement {
    return (node as AuMarker).nodeName === 'AU-M';
  }


public isNodeInstance(potentialNode: unknown): potentialNode is Node {
    return potentialNode != null && (potentialNode as Node).nodeType > 0;
  }


public isRenderLocation(node: unknown): node is IRenderLocation {
    return (node as Comment).textContent === 'au-end';
  }


public makeTarget(node: unknown): void {
    (node as Element).className = 'au';
  }


public registerElementResolver(container: IContainer, resolver: IResolver): void {
    container.registerResolver(INode, resolver);
    container.registerResolver(this.Node, resolver);
    container.registerResolver(this.Element, resolver);
    container.registerResolver(this.HTMLElement, resolver);
  }


public remove(node: Node): void {
    if ((node as ChildNode).remove) {
      (node as ChildNode).remove();
    } else {
      node.parentNode!.removeChild(node);
    }
  }


public removeEventListener(eventName: string, subscriber: EventListenerOrEventListenerObject, publisher?: Node, options?: boolean | EventListenerOptions): void {
    (publisher || this.document).removeEventListener(eventName, subscriber, options);
  }


public setAttribute(node: Element, name: string, value: unknown): void {
    node.setAttribute(name, value as string);
  }


public findTargets(): ArrayLike<Node> {
    return this.targets;
  }


public insertBefore(refNode: Node): void {
    if (this.isLinked && !!this.refNode) {
      this.addToLinked();
    } else {
      this.isMounted = true;
      refNode.parentNode!.insertBefore(this.firstChild, refNode);
    }
  }


public appendTo(parent: Node): void {
    if (this.isLinked && !!this.refNode) {
      this.addToLinked();
    } else {
      this.isMounted = true;
      parent.appendChild(this.firstChild);
    }
  }


public remove(): void {
    this.isMounted = false;
    this.firstChild.remove();
  }


public addToLinked(): void {
    const refNode = this.refNode!;
    this.isMounted = true;
    refNode.parentNode!.insertBefore(this.firstChild, refNode);
  }


public unlink(): void {
    this.isLinked = false;
    this.next = void 0;
    this.refNode = void 0;
  }


public link(next: INodeSequence<Node> | (IRenderLocation & Comment) | undefined): void {
    this.isLinked = true;
    if (this.dom.isRenderLocation(next)) {
      this.refNode = next;
    } else {
      this.next = next;
      this.obtainRefNode();
    }
  }


private obtainRefNode(): void {
    if (this.next !== void 0) {
      this.refNode = this.next.firstChild;
    } else {
      this.refNode = void 0;
    }
  }


public insertBefore(refNode: IRenderLocation & Comment): void {
    if (this.isLinked && !!this.refNode) {
      this.addToLinked();
    } else {
      const parent = refNode.parentNode!;
      if (this.isMounted) {
        let current = this.firstChild;
        const end = this.lastChild;
        let next: Node;

        while (current != null) {
          next = current.nextSibling!;
          parent.insertBefore(current, refNode);

          if (current === end) {
            break;
          }

          current = next;
        }
      } else {
        this.isMounted = true;
        refNode.parentNode!.insertBefore(this.fragment, refNode);
      }
    }
  }


public appendTo(parent: Node): void {
    if (this.isMounted) {
      let current = this.firstChild;
      const end = this.lastChild;
      let next: Node;

      while (current != null) {
        next = current.nextSibling!;
        parent.appendChild(current);

        if (current === end) {
          break;
        }

        current = next;
      }
    } else {
      this.isMounted = true;
      parent.appendChild(this.fragment);
    }
  }


public remove(): void {
    if (this.isMounted) {
      this.isMounted = false;

      const fragment = this.fragment;
      const end = this.lastChild;
      let next: Node;

      let current = this.firstChild;
      while (current !== null) {
        next = current.nextSibling!;
        fragment.appendChild(current);

        if (current === end) {
          break;
        }

        current = next;
      }
    }
  }


public addToLinked(): void {
    const refNode = this.refNode!;
    const parent = refNode.parentNode!;
    if (this.isMounted) {
      let current = this.firstChild;
      const end = this.lastChild;
      let next: Node;

      while (current != null) {
        next = current.nextSibling!;
        parent.insertBefore(current, refNode);

        if (current === end) {
          break;
        }

        current = next;
      }
    } else {
      this.isMounted = true;
      parent.insertBefore(this.fragment, refNode);
    }
  }


public link(next: INodeSequence<Node> | IRenderLocation & Comment | undefined): void {
    this.isLinked = true;
    if (this.dom.isRenderLocation(next)) {
      this.refNode = next;
    } else {
      this.next = next;
      this.obtainRefNode();
    }
  }


public createNodeSequence(): INodeSequence {
    return new this.Type(this.dom, this.node.cloneNode(this.deepClone));
  }


public remove(): void { /* do nothing */ }


public static register(container: IContainer): IResolver<ITemplateFactory> {
    return Registration.singleton(ITemplateFactory, this).register(container);
  }


public create(parentRenderContext: IRenderContext, definition: TemplateDefinition): ITemplate {
    return new CompiledTemplate(this.dom, definition, new NodeSequenceFactory(this.dom, definition.template as string | Node), parentRenderContext);
  }


(db: MongoDb.Db) => {
            return db.collection(this.getCollectionName());
        }


(collection: any) => {
            return collection.findOne({_id: id}).then((result) => {
                return result;
            });
        }


(result) => {
                return result;
            }


(collection: MongoDb.Collection) => {
            return collection.deleteOne({ _id: id }).then((result) => {
                console.log(result);
                return result;
            });
        }


(result) => {
                console.log(result);
                return result;
            }


(collection: MongoDb.Collection) => {
            entity.updatedAt = new Date();
            return collection.updateOne({ _id: id }, entity).then((result) => {
                return entity;
            });
        }


(result) => {
                return entity;
            }


(collection: MongoDb.Collection) => {
            return collection.find(filter).limit(top).skip(skip).toArray();
        }


(collection: MongoDb.Collection) => {
            entity.createdDate = new Date();
            return collection.insertOne(entity).then((result) => {
                return entity;
            });
        }


abstract class MongoRepository<T extends IEntity> implements IRepository<IEntity>  {

    protected collection: Promise<MongoDb.Collection>;

    constructor() {
        this.collection = this.getCollection(Configurations.Repository.connectionString);
    }

    protected abstract getCollectionName(): string;

    private getCollection(url: string): Promise<MongoDb.Collection> {
        return MongoDb.MongoClient.connect(url).then((db: MongoDb.Db) => {
            return db.collection(this.getCollectionName());
        });
    }

    public findById(id: string): Promise<T> {
        return this.collection.then((collection: any) => {
            return collection.findOne({_id: id}).then((result) => {
                return result;
            });
        });
    }

    public findByIdAndDelete(id: string): Promise<any> {
        return this.collection.then((collection: MongoDb.Collection) => {
            return collection.deleteOne({ _id: id }).then((result) => {
                console.log(result);
                return result;
            });
        });
    }

    public findByIdAndUpdate(id: string, entity: T): Promise<T> {
        return this.collection.then((collection: MongoDb.Collection) => {
            entity.updatedAt = new Date();
            return collection.updateOne({ _id: id }, entity).then((result) => {
                return entity;
            });
        });
    }

    public find(filter: Object, top?: number, skip?: number): Promise<Array<T>> {
        return this.collection.then((collection: MongoDb.Collection) => {
            return collection.find(filter).limit(top).skip(skip).toArray();
        });
    }

    public create(entity: T): Promise<T> {

        entity._id = UUID.v4();
        return this.collection.then((collection: MongoDb.Collection) => {
            entity.createdDate = new Date();
            return collection.insertOne(entity).then((result) => {
                return entity;
            });
        });
    }
}


protected abstract getCollectionName(): string;


private getCollection(url: string): Promise<MongoDb.Collection> {
        return MongoDb.MongoClient.connect(url).then((db: MongoDb.Db) => {
            return db.collection(this.getCollectionName());
        });
    }


public findById(id: string): Promise<T> {
        return this.collection.then((collection: any) => {
            return collection.findOne({_id: id}).then((result) => {
                return result;
            });
        });
    }


public findByIdAndDelete(id: string): Promise<any> {
        return this.collection.then((collection: MongoDb.Collection) => {
            return collection.deleteOne({ _id: id }).then((result) => {
                console.log(result);
                return result;
            });
        });
    }


public findByIdAndUpdate(id: string, entity: T): Promise<T> {
        return this.collection.then((collection: MongoDb.Collection) => {
            entity.updatedAt = new Date();
            return collection.updateOne({ _id: id }, entity).then((result) => {
                return entity;
            });
        });
    }


public find(filter: Object, top?: number, skip?: number): Promise<Array<T>> {
        return this.collection.then((collection: MongoDb.Collection) => {
            return collection.find(filter).limit(top).skip(skip).toArray();
        });
    }


public create(entity: T): Promise<T> {

        entity._id = UUID.v4();
        return this.collection.then((collection: MongoDb.Collection) => {
            entity.createdDate = new Date();
            return collection.insertOne(entity).then((result) => {
                return entity;
            });
        });
    }


(props) => {
        return columnsRenderImg(props.value, props.data)
    }


(props) => {
        return (props.value === true || props.value === 'true') ? <Switch checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="close" />}


(props) => {
        if (props.value) {
            return <div style={{ textAlign: "center" }} >
                <Button style={{ height: 25, width: 25, objectFit: "cover" }} shape="circle" icon="download" onClick={e => {
                    window.open(RequestFiles.onFileDownload(props.value))
                }} />
            </div>
        }


(props) => {
        if (props.value) {
            let render = props.value
            // colDef.field
            if (Regular.isHtml.test(props.value)) {
                render =
            }
            // // 前景色
            // const forecolor = lodash.get(props.data, props.colDef.field + '__forecolor');
            // // 背景色
            // const backcolor = lodash.get(props.data, props.colDef.field + '__backcolor');
            // if (forecolor || backcolor) {
            //     render =
{render}

            // }
            return render
        } else {
            return ''
        }
    }


e => {
            // 获取当前高度 ，高度 为 0 说明页面属于隐藏状态
            if (lodash.get(this.refTableBody.current, 'clientHeight', 0) > 0) {
                if (!globalConfig.tabsPage) {
                    this.onUpdateHeight(lodash.get(e, 'detail') === 'refFullscreen');
                }
                this.sizeColumnsToFit();
            }
        }


(col: ColDef) => {
            // 根据 数据 定制 样式
            col.cellStyle = col.cellStyle ||
                ((props) => {
                    if (props.data) {
                        // 前景色
                        const forecolor = lodash.get(props.data, props.colDef.field + '__forecolor');
                        // 背景色
                        const backcolor = lodash.get(props.data, props.colDef.field + '__bgcolor');
                        return { color: forecolor, backgroundColor: backcolor }
                    }
                });
            // 渲染器
            col.cellRenderer = col.cellRenderer || 'columnsRenderDefault';
            return col
        }


(props) => {
                    if (props.data) {
                        // 前景色
                        const forecolor = lodash.get(props.data, props.colDef.field + '__forecolor');
                        // 背景色
                        const backcolor = lodash.get(props.data, props.colDef.field + '__bgcolor');
                        return { color: forecolor, backgroundColor: backcolor }
                    }
                }


(rowProps) => {
                                    if (rowProps.data) {
                                        return <RowAction {...rowProps} />;
                                    }
                                    return null;
                                }


// export class AgGrid extends React.Component<ITableProps, any> {
//     /**
//      * 全屏 容器
//      */
//     refFullscreen = React.createRef<HTMLDivElement>();
//     render() {
//         let {
//             ...props
//         } = this.props;
//         return (
//             <Table {...props} />
//         );
//     }
// }
@observer
@BindAll()
export class AgGrid extends React.Component<ITableProps, any> {
    gridApi: GridApi;
    // 表格容器
    refTableBody = React.createRef<HTMLDivElement>();
    // 事件对象
    resizeEvent: Subscription;
    minHeight = 400;
    state = {
        sortable: true,
        height: this.minHeight
    }
    /**
     * 修改 高度
     * @param refFullscreen
     */
    @Debounce(200)
    onUpdateHeight(refFullscreen = false) {
        try {
            // props 中传递了 height
            if (this.props.style && this.props.style.height) {
                return
            }
            const refTable = this.refTableBody.current;//ReactDOM.findDOMNode(this.ref.current) as HTMLDivElement;
            // 60 是头部 标题栏 高度
            let height = window.innerHeight - refTable.offsetTop - 60 - 100;
            if (!globalConfig.tabsPage) {
                height += 90;
            }
            height = height < this.minHeight ? this.minHeight : height;
            if (this.state.height !== height) {
                this.gridApi.sizeColumnsToFit();
                this.setState({ height });
            }
        } catch (error) {
            console.log(error)
        }
    }
    // onGetColumnDefs() {
    //     let columnDefs = [...this.props.columnDefs];
    //     console.log(columnDefs.reduce((accumulator, currentValue) => {
    //         return accumulator.width + currentValue.w
    //     }), 0)
    //     return columnDefs;
    // }
    /**
     * 分页 参数 改变回调
     * @param current
     * @param pageSize
     */
    onChangePagination(current: number, pageSize: number) {
        console.log("TCL: App -> onChangePagination -> ", current, pageSize)
        this.props.Store.onSearch({
            Page: current,
            Limit: pageSize
        });
    }
    onSortChanged(event: SortChangedEvent) {
        const SortModel = lodash.head(event.api.getSortModel());
        this.props.Store.onSearch({
            SortInfo: SortModel && SortModel.sort && { Direction: lodash.capitalize(SortModel.sort), Property: SortModel.colId },
            Page: 1,
            Limit: this.props.Store.DataSource.searchParams.Limit
        })
    }
    /**
     * 选择的 行 数据 回调
     * @param event
     */
    onSelectionChanged(event: SelectionChangedEvent) {
        // console.log("TCL: App -> onSelectionChanged -> event", event.api.getSelectedRows())
        // event.api.getSelectedNodesById()
        this.props.Store.DataSource.selectedRowKeys = lodash.map(event.api.getSelectedRows(), 'key');
    }
    onColumnRowGroupChanged(event: ColumnRowGroupChangedEvent) {
        // this.setState({ sortable: event.columns.length > 0 })
    }
    async componentDidMount() {
        this.onUpdateHeight();
        this.resizeEvent = fromEvent(window, "resize").pipe(debounceTime(300)).subscribe(e => {
            // 获取当前高度 ，高度 为 0 说明页面属于隐藏状态
            if (lodash.get(this.refTableBody.current, 'clientHeight', 0) > 0) {
                if (!globalConfig.tabsPage) {
                    this.onUpdateHeight(lodash.get(e, 'detail') === 'refFullscreen');
                }
                this.sizeColumnsToFit();
            }
        });
        await this.props.Store.onSearch();
        this.sizeColumnsToFit()
    }
    componentWillUnmount() {
        this.resizeEvent && this.resizeEvent.unsubscribe()
    }
    sizeColumnsToFit() {
        if (lodash.get(this.refTableBody.current, 'clientHeight', 0) && this.gridApi) {
            this.gridApi.sizeColumnsToFit();
        }
    }
    onGridReady(event: GridReadyEvent) {
        this.gridApi = event.api;
        // 更新 列 大小
        event.api.sizeColumnsToFit();
    }
    public render() {
        let {
            Store,
            rowAction: RowAction,
            rowActionCol,
            paginationProps,
            style,
            theme = globalConfig.agGridTheme,//'ag-theme-balham',
            className = '',
            children,
            onGridReady,
            loading,
            defaultColDef,
            columnDefs,
            checkboxSelection = true,
            frameworkComponents,
            // rowData,
            ...props
        } = this.props;
        const { DataSource } = Store;
        const dataSource = DataSource.tableList;
        const checkboxSelectionWidth = {
            "ag-theme-balham": 40,
            "ag-theme-material": 70,
        }[theme];
        if (loading) {
            props.rowData = undefined
        } else {
            props.rowData = toJS(dataSource.Data);
        }
        // 替换默认的渲染器
        columnDefs = columnDefs.map((col: ColDef) => {
            // 根据 数据 定制 样式
            col.cellStyle = col.cellStyle ||
                ((props) => {
                    if (props.data) {
                        // 前景色
                        const forecolor = lodash.get(props.data, props.colDef.field + '__forecolor');
                        // 背景色
                        const backcolor = lodash.get(props.data, props.colDef.field + '__bgcolor');
                        return { color: forecolor, backgroundColor: backcolor }
                    }
                });
            // 渲染器
            col.cellRenderer = col.cellRenderer || 'columnsRenderDefault';
            return col
        })
        return (
            <>
                <div ref={this.refTableBody} style={{ height: this.state.height, ...style }} className={`app-ag-grid ${className} ${theme}`}


interface ITableProps extends AgGridReactProps {
    /** 状态 */
    Store: Store;
    /**
     * 行 操作
     */
    rowAction?: any;
    /**
     * 行 操作列配置
     */
    rowActionCol?: ColDef;
    /**
     * 容器样式
     */
    style?: React.CSSProperties;
    /**
     * 主题
     */
    theme?: string;
    /**
     * 样式
     */
    className?: string;
    /**
     * 分页
     */
    paginationProps?: PaginationProps | boolean;
    /**
     * 加载中
     */
    loading?: boolean;
    /**
     * 选择
     */
    checkboxSelection?: boolean;
}


/**
     * 修改 高度
     * @param refFullscreen
     */
@Debounce(200)
    onUpdateHeight(refFullscreen = false) {
        try {
            // props 中传递了 height
            if (this.props.style && this.props.style.height) {
                return
            }
            const refTable = this.refTableBody.current;//ReactDOM.findDOMNode(this.ref.current) as HTMLDivElement;
            // 60 是头部 标题栏 高度
            let height = window.innerHeight - refTable.offsetTop - 60 - 100;
            if (!globalConfig.tabsPage) {
                height += 90;
            }
            height = height < this.minHeight ? this.minHeight : height;
            if (this.state.height !== height) {
                this.gridApi.sizeColumnsToFit();
                this.setState({ height });
            }
        } catch (error) {
            console.log(error)
        }
    }


// onGetColumnDefs() {
//     let columnDefs = [...this.props.columnDefs];
//     console.log(columnDefs.reduce((accumulator, currentValue) => {
//         return accumulator.width + currentValue.w
//     }), 0)
//     return columnDefs;
// }
/**
     * 分页 参数 改变回调
     * @param current
     * @param pageSize
     */
onChangePagination(current: number, pageSize: number) {
        console.log("TCL: App -> onChangePagination -> ", current, pageSize)
        this.props.Store.onSearch({
            Page: current,
            Limit: pageSize
        });
    }


onSortChanged(event: SortChangedEvent) {
        const SortModel = lodash.head(event.api.getSortModel());
        this.props.Store.onSearch({
            SortInfo: SortModel && SortModel.sort && { Direction: lodash.capitalize(SortModel.sort), Property: SortModel.colId },
            Page: 1,
            Limit: this.props.Store.DataSource.searchParams.Limit
        })
    }


/**
     * 选择的 行 数据 回调
     * @param event
     */
onSelectionChanged(event: SelectionChangedEvent) {
        // console.log("TCL: App -> onSelectionChanged -> event", event.api.getSelectedRows())
        // event.api.getSelectedNodesById()
        this.props.Store.DataSource.selectedRowKeys = lodash.map(event.api.getSelectedRows(), 'key');
    }


onColumnRowGroupChanged(event: ColumnRowGroupChangedEvent) {
        // this.setState({ sortable: event.columns.length > 0 })
    }


async componentDidMount() {
        this.onUpdateHeight();
        this.resizeEvent = fromEvent(window, "resize").pipe(debounceTime(300)).subscribe(e => {
            // 获取当前高度 ，高度 为 0 说明页面属于隐藏状态
            if (lodash.get(this.refTableBody.current, 'clientHeight', 0) > 0) {
                if (!globalConfig.tabsPage) {
                    this.onUpdateHeight(lodash.get(e, 'detail') === 'refFullscreen');
                }
                this.sizeColumnsToFit();
            }
        });
        await this.props.Store.onSearch();
        this.sizeColumnsToFit()
    }


componentWillUnmount() {
        this.resizeEvent && this.resizeEvent.unsubscribe()
    }


sizeColumnsToFit() {
        if (lodash.get(this.refTableBody.current, 'clientHeight', 0) && this.gridApi) {
            this.gridApi.sizeColumnsToFit();
        }
    }


onGridReady(event: GridReadyEvent) {
        this.gridApi = event.api;
        // 更新 列 大小
        event.api.sizeColumnsToFit();
    }


public render() {
        let {
            Store,
            rowAction: RowAction,
            rowActionCol,
            paginationProps,
            style,
            theme = globalConfig.agGridTheme,//'ag-theme-balham',
            className = '',
            children,
            onGridReady,
            loading,
            defaultColDef,
            columnDefs,
            checkboxSelection = true,
            frameworkComponents,
            // rowData,
            ...props
        } = this.props;
        const { DataSource } = Store;
        const dataSource = DataSource.tableList;
        const checkboxSelectionWidth = {
            "ag-theme-balham": 40,
            "ag-theme-material": 70,
        }[theme];
        if (loading) {
            props.rowData = undefined
        } else {
            props.rowData = toJS(dataSource.Data);
        }
        // 替换默认的渲染器
        columnDefs = columnDefs.map((col: ColDef) => {
            // 根据 数据 定制 样式
            col.cellStyle = col.cellStyle ||
                ((props) => {
                    if (props.data) {
                        // 前景色
                        const forecolor = lodash.get(props.data, props.colDef.field + '__forecolor');
                        // 背景色
                        const backcolor = lodash.get(props.data, props.colDef.field + '__bgcolor');
                        return { color: forecolor, backgroundColor: backcolor }
                    }
                });
            // 渲染器
            col.cellRenderer = col.cellRenderer || 'columnsRenderDefault';
            return col
        })
        return (
            <>
                <div ref={this.refTableBody} style={{ height: this.state.height, ...style }}


(
  reply: FastifyReply,
  code = 'BAD_REQUEST',
  message = 'Bad Request',
): FastifyReply => reply
  .code(400)
  .type('application/json')
  .send({
    id: uuidv4(),
    code,
    message,
  })


export default function OrphanageMarker(props:OrphanageProps){

    return (
        <Marker
            icon={mapIcon}
            position={[props.latitude,props.longitude]}
        >

            <Popup
                closeButton={false}
                minWidth={240}
                maxWidth={240}
                className="map-popup"
            >
                {props.name}
                <Link to={`/orphanages/${props.id}`}


emission => {
          // If yes, we navigate away.
          if (emission?.behaviour === "Yes") {
              return true;
          }
          else {
            // Block navigation
            return false;
          }
        }


@Injectable({
  providedIn: 'root'
})
/* This class stops away navigation for routes, it is currently disabled because
there doesn't seem to be a way to cancel logout in a user clicks that. */
export class RecipeFormGuardService implements CanDeactivate<RecipeFormComponent> {

  constructor(private dialog: MatDialog) { }
    canDeactivate(component: RecipeFormComponent, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot){
      // Allow navigation only to the page associated with logout or the save button.
      // These are unlikely to be misclicks.
      if (nextState.url.includes('login') || nextState.url.includes('/recipe')) {
        return true;
      }
      // Make sure user confirms navigation away.
      let dialogRef = this.dialog.open(DangerousActionPopupComponent);
        dialogRef.componentInstance.description ="Wait!";
        dialogRef.componentInstance.question = "Are you sure you want to navigate away, your changes will not be saved!"

        // Return observable which is subscribed to by guard.
        return dialogRef.afterClosed().pipe(map(emission => {
          // If yes, we navigate away.
          if (emission?.behaviour === "Yes") {
              return true;
          }
          else {
            // Block navigation
            return false;
          }
        }));

    }
}


canDeactivate(component: RecipeFormComponent, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot){
      // Allow navigation only to the page associated with logout or the save button.
      // These are unlikely to be misclicks.
      if (nextState.url.includes('login') || nextState.url.includes('/recipe')) {
        return true;
      }
      // Make sure user confirms navigation away.
      let dialogRef = this.dialog.open(DangerousActionPopupComponent);
        dialogRef.componentInstance.description ="Wait!";
        dialogRef.componentInstance.question = "Are you sure you want to navigate away, your changes will not be saved!"

        // Return observable which is subscribed to by guard.
        return dialogRef.afterClosed().pipe(map(emission => {
          // If yes, we navigate away.
          if (emission?.behaviour === "Yes") {
              return true;
          }
          else {
            // Block navigation
            return false;
          }
        }));

    }


(debounce?: boolean, element?: ExplorerNode) =>
            this.refreshWithLog(debounce, element)


(terminalId: string, message: string) => {
            appendOutput(terminalId, message);
        }


async (node: INodeData) => {
            executeExportJarTask(node);
        }


(uri, range) =>
            window.showTextDocument(Uri.parse(uri), { selection: range })


() =>
            commands.executeCommand(Commands.JAVA_BUILD_WORKSPACE)


() =>
            commands.executeCommand(Commands.JAVA_CLEAN_WORKSPACE)


async (node: INodeData) => {
            if (!node.uri) {
                window.showErrorMessage("The URI of the project is not available, you can try to update the project by right clicking the project configuration file (pom.xml or *.gradle) from the File Explorer.");
                return;
            }
            const pattern: RelativePattern = new RelativePattern(Uri.parse(node.uri).fsPath, "{pom.xml,*.gradle}");
            const uris: Uri[] = await workspace.findFiles(pattern, null /*exclude*/, 1 /*maxResults*/);
            if (uris.length >= 1) {
                commands.executeCommand(Commands.JAVA_PROJECT_CONFIGURATION_UPDATE, uris[0]);
            }
        }


(updatedConfig, oldConfig) => {
            if (updatedConfig.refreshDelay !== oldConfig.refreshDelay) {
                this.setRefreshDelay(updatedConfig.refreshDelay);
            }
        }


() => this.refresh(debounce, element)


(node: DataNode) =>
            node.path === projectNodeData?.path && node.nodeData.name === projectNodeData?.name


(folder) => rootItems.push(new WorkspaceNode({
                        name: folder.name,
                        uri: folder.uri.toString(),
                        kind: NodeKind.Workspace,
                    }, undefined))


(project) => {
                        rootItems.push(new ProjectNode(project, undefined));
                    }


export class DependencyDataProvider implements TreeDataProvider<ExplorerNode> {

    private _onDidChangeTreeData: EventEmitter<ExplorerNode | null | undefined> = new EventEmitter<ExplorerNode | null | undefined>();

    // tslint:disable-next-line:member-ordering
    public onDidChangeTreeData: Event<ExplorerNode | null | undefined> = this._onDidChangeTreeData.event;

    private _rootItems: ExplorerNode[] | undefined = undefined;
    private _refreshDelayTrigger: _.DebouncedFunc<((element?: ExplorerNode) => void)>;

    constructor(public readonly context: ExtensionContext) {
        context.subscriptions.push(commands.registerCommand(Commands.VIEW_PACKAGE_REFRESH, (debounce?: boolean, element?: ExplorerNode) =>
            this.refreshWithLog(debounce, element)));
        context.subscriptions.push(commands.registerCommand(Commands.EXPORT_JAR_REPORT, (terminalId: string, message: string) => {
            appendOutput(terminalId, message);
        }));
        context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.VIEW_PACKAGE_EXPORT_JAR, async (node: INodeData) => {
            executeExportJarTask(node);
        }));
        context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.VIEW_PACKAGE_OUTLINE, (uri, range) =>
            window.showTextDocument(Uri.parse(uri), { selection: range })));
        context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.JAVA_PROJECT_BUILD_WORKSPACE, () =>
            commands.executeCommand(Commands.JAVA_BUILD_WORKSPACE)));
        context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.JAVA_PROJECT_CLEAN_WORKSPACE, () =>
            commands.executeCommand(Commands.JAVA_CLEAN_WORKSPACE)));
        context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.JAVA_PROJECT_UPDATE, async (node: INodeData) => {
            if (!node.uri) {
                window.showErrorMessage("The URI of the project is not available, you can try to update the project by right clicking the project configuration file (pom.xml or *.gradle) from the File Explorer.");
                return;
            }
            const pattern: RelativePattern = new RelativePattern(Uri.parse(node.uri).fsPath, "{pom.xml,*.gradle}");
            const uris: Uri[] = await workspace.findFiles(pattern, null /*exclude*/, 1 /*maxResults*/);
            if (uris.length >= 1) {
                commands.executeCommand(Commands.JAVA_PROJECT_CONFIGURATION_UPDATE, uris[0]);
            }
        }));

        Settings.registerConfigurationListener((updatedConfig, oldConfig) => {
            if (updatedConfig.refreshDelay !== oldConfig.refreshDelay) {
                this.setRefreshDelay(updatedConfig.refreshDelay);
            }
        });
        this.setRefreshDelay();
    }

    public refreshWithLog(debounce?: boolean, element?: ExplorerNode) {
        if (Settings.autoRefresh()) {
            this.refresh(debounce, element);
        } else {
            instrumentOperation(Commands.VIEW_PACKAGE_REFRESH, () => this.refresh(debounce, element))();
        }
    }

    public refresh(debounce = false, element?: ExplorerNode) {
        this._refreshDelayTrigger(element);
        if (!debounce) { // Immediately refresh
            this._refreshDelayTrigger.flush();
        }
    }

    public setRefreshDelay(wait?: number) {
        if (!wait) {
            wait = Settings.refreshDelay();
        }
        if (this._refreshDelayTrigger) {
            this._refreshDelayTrigger.cancel();
        }
        this._refreshDelayTrigger = _.debounce(this.doRefresh, wait);
    }

    public getTreeItem(element: ExplorerNode): TreeItem | Promise<TreeItem> {
        return element.getTreeItem();
    }

    public async getChildren(element?: ExplorerNode): Promise<ExplorerNode[] | undefined | null> {
        if (!await languageServerApiManager.ready()) {
            return [];
        }

        const children = (!this._rootItems || !element) ?
            await this.getRootNodes() : await element.getChildren();

        explorerNodeCache.saveNodes(children || []);
        return children;
    }

    public getParent(element: ExplorerNode): ProviderResult<ExplorerNode> {
        return element.getParent();
    }

    public async revealPaths(paths: INodeData[]): Promise<DataNode | undefined> {
        const projectNodeData = paths.shift();
        const projects = await this.getRootProjects();
        const project = projects ? <DataNode>projects.find((node: DataNode) =>
            node.path === projectNodeData?.path && node.nodeData.name === projectNodeData?.name) : undefined;
        return project?.revealPaths(paths);
    }

    public async getRootProjects(): Promise<ExplorerNode[]> {
        const rootElements = await this.getRootNodes();
        if (rootElements[0] instanceof ProjectNode) {
            return rootElements;
        } else {
            let result: ExplorerNode[] = [];
            for (const rootWorkspace of rootElements) {
                const projects = await rootWorkspace.getChildren();
                if (projects) {
                    result = result.concat(projects);
                }
            }
            return result;
        }
    }

    private doRefresh(element?: ExplorerNode): void {
        if (!element) {
            this._rootItems = undefined;
        }
        explorerNodeCache.removeNodeChildren(element);
        this._onDidChangeTreeData.fire(element);
    }

    private async getRootNodes(): Promise<ExplorerNode[]> {
        try {
            await explorerLock.acquireAsync();

            if (this._rootItems) {
                return this._rootItems;
            }

            const rootItems: ExplorerNode[] = [];
            const folders = workspace.workspaceFolders;
            if (folders && folders.length) {
                if (folders.length > 1) {
                    folders.forEach((folder) => rootItems.push(new WorkspaceNode({
                        name: folder.name,
                        uri: folder.uri.toString(),
                        kind: NodeKind.Workspace,
                    }, undefined)));
                    this._rootItems = rootItems;
                } else {
                    const result: INodeData[] = await Jdtls.getProjects(folders[0].uri.toString());
                    result.forEach((project) => {
                        rootItems.push(new ProjectNode(project, undefined));
                    });
                    this._rootItems = rootItems;
                }
            }
            contextManager.setContextValue(Context.NO_JAVA_PROJECT, _.isEmpty(rootItems));
            return rootItems;
        } finally {
            explorerLock.release();
        }
    }
}


public refreshWithLog(debounce?: boolean, element?: ExplorerNode) {
        if (Settings.autoRefresh()) {
            this.refresh(debounce, element);
        } else {
            instrumentOperation(Commands.VIEW_PACKAGE_REFRESH, () => this.refresh(debounce, element))();
        }
    }


public refresh(debounce = false, element?: ExplorerNode) {
        this._refreshDelayTrigger(element);
        if (!debounce) { // Immediately refresh
            this._refreshDelayTrigger.flush();
        }
    }


public setRefreshDelay(wait?: number) {
        if (!wait) {
            wait = Settings.refreshDelay();
        }
        if (this._refreshDelayTrigger) {
            this._refreshDelayTrigger.cancel();
        }
        this._refreshDelayTrigger = _.debounce(this.doRefresh, wait);
    }


public getTreeItem(element: ExplorerNode): TreeItem | Promise<TreeItem> {
        return element.getTreeItem();
    }


public async getChildren(element?: ExplorerNode): Promise<ExplorerNode[] | undefined | null> {
        if (!await languageServerApiManager.ready()) {
            return [];
        }

        const children = (!this._rootItems || !element) ?
            await this.getRootNodes() : await element.getChildren();

        explorerNodeCache.saveNodes(children || []);
        return children;
    }


public getParent(element: ExplorerNode): ProviderResult<ExplorerNode> {
        return element.getParent();
    }


public async revealPaths(paths: INodeData[]): Promise<DataNode | undefined> {
        const projectNodeData = paths.shift();
        const projects = await this.getRootProjects();
        const project = projects ? <DataNode>projects.find((node: DataNode) =>
            node.path === projectNodeData?.path && node.nodeData.name === projectNodeData?.name) : undefined;
        return project?.revealPaths(paths);
    }


public async getRootProjects(): Promise<ExplorerNode[]> {
        const rootElements = await this.getRootNodes();
        if (rootElements[0] instanceof ProjectNode) {
            return rootElements;
        } else {
            let result: ExplorerNode[] = [];
            for (const rootWorkspace of rootElements) {
                const projects = await rootWorkspace.getChildren();
                if (projects) {
                    result = result.concat(projects);
                }
            }
            return result;
        }
    }


private doRefresh(element?: ExplorerNode): void {
        if (!element) {
            this._rootItems = undefined;
        }
        explorerNodeCache.removeNodeChildren(element);
        this._onDidChangeTreeData.fire(element);
    }


private async getRootNodes(): Promise<ExplorerNode[]> {
        try {
            await explorerLock.acquireAsync();

            if (this._rootItems) {
                return this._rootItems;
            }

            const rootItems: ExplorerNode[] = [];
            const folders = workspace.workspaceFolders;
            if (folders && folders.length) {
                if (folders.length > 1) {
                    folders.forEach((folder) => rootItems.push(new WorkspaceNode({
                        name: folder.name,
                        uri: folder.uri.toString(),
                        kind: NodeKind.Workspace,
                    }, undefined)));
                    this._rootItems = rootItems;
                } else {
                    const result: INodeData[] = await Jdtls.getProjects(folders[0].uri.toString());
                    result.forEach((project) => {
                        rootItems.push(new ProjectNode(project, undefined));
                    });
                    this._rootItems = rootItems;
                }
            }
            contextManager.setContextValue(Context.NO_JAVA_PROJECT, _.isEmpty(rootItems));
            return rootItems;
        } finally {
            explorerLock.release();
        }
    }


function TeacherForm() {
const history = useHistory();

  const [name, setName] = useState('');
  const [avatar, setAvatar] = useState('');
  const [whatsapp, setWhatsapp] = useState('');
  const [bio, setBio] = useState('');

  const [subject, setSubject] = useState('');
  const [cost, setCost] = useState('');

  const [scheduleItems, setScheduleItems] = useState([
    { week_day: 0, from: '', to: ''}
  ]);

  function addNewScheduleItem() {
    setScheduleItems([
      ...scheduleItems,
      { week_day: 0, from: '', to: ''}
    ]);
  }

  function setScheduleItemValue( position: number, field: string, value: string) {
    const updatedScheduleItems = scheduleItems.map((scheduleItem, index) => {
      if (index === position) {
        return { ...scheduleItem, [field]: value};
      }

      return scheduleItem;
    });

    setScheduleItems(updatedScheduleItems)
  }
  function handleCreateClass(e: FormEvent){
    e.preventDefault();

    api.post('classes', {
      name,
      avatar,
      whatsapp,
      bio,
      subject,
      cost: Number(cost),
      schedule: scheduleItems
    }).then(() => {
      alert('Cadastro realizado com sucesso!');

      history.push('/');
    }).catch(() => {
      alert('Erro no cadastro!');
    })
  }

  return (
    <div id="page-teacher-form" className="container">
    <PageHeader
    title="Que incrível que você quer dar aulas."
    description = "O primeiro passo é preencher esse formulário de inscrição"
    />

    <main>
      <form onSubmit={handleCreateClass}>

        <fieldset>
          <legend>Seus dados</legend>

          <Input
            name="name"
            label="Nome completo"
            value={name}
            onChange={(e) => { setName(e.target.value)}}


function addNewScheduleItem() {
    setScheduleItems([
      ...scheduleItems,
      { week_day: 0, from: '', to: ''}
    ]);
  }


function setScheduleItemValue( position: number, field: string, value: string) {
    const updatedScheduleItems = scheduleItems.map((scheduleItem, index) => {
      if (index === position) {
        return { ...scheduleItem, [field]: value};
      }

      return scheduleItem;
    });

    setScheduleItems(updatedScheduleItems)
  }


function handleCreateClass(e: FormEvent){
    e.preventDefault();

    api.post('classes', {
      name,
      avatar,
      whatsapp,
      bio,
      subject,
      cost: Number(cost),
      schedule: scheduleItems
    }).then(() => {
      alert('Cadastro realizado com sucesso!');

      history.push('/');
    }).catch(() => {
      alert('Erro no cadastro!');
    })
  }


(scheduleItem, index) => {
      if (index === position) {
        return { ...scheduleItem, [field]: value};
      }

      return scheduleItem;
    }


() => {
      alert('Cadastro realizado com sucesso!');

      history.push('/');
    }


() => {
      alert('Erro no cadastro!');
    }


(scheduleItem, index) => {
            return (
              <div key={scheduleItem.week_day} className="schedule-item">
              <Select
                name="week-day"
                label="Dia da semana"
                value={scheduleItem.week_day}
                onChange={e => setScheduleItemValue(index, 'week_day', e.target.value


setScheduleItemValue(index, 'week_day', e


setScheduleItemValue(index, 'from', e


setScheduleItemValue(index, 'to', e


export default class ArgContainer {
    private argList: Array<Arg>;

    constructor() {
        this.argList = new Array<Arg>();
    }

    public get(): Array<Arg> {
        return this.argList;
    }

    public add(arg: Arg) {
        this.argList.push(arg);
    }
}


public get(): Array<Arg> {
        return this.argList;
    }


public add(arg: Arg) {
        this.argList.push(arg);
    }


function getExtraProductionArgument(
            prod: IProductionWithOccurrence
        ): string {
            if (prod instanceof Terminal) {
                return prod.terminalType.name
            } else if (prod instanceof NonTerminal) {
                return prod.nonTerminalName
            } else {
                return ""
            }
        }


(result, currAltPaths) => result.concat(currAltPaths)


currPath =>
                    `[${map(currPath, currTokenType =>
                        tokenLabel(currTokenType)
                    ).join(", ")}]`


currTokenType =>
                        tokenLabel(currTokenType)


(itemMsg, idx) => `  ${idx + 1}. ${itemMsg}`


currPath =>
                    `[${map(currPath, currTokenType =>
                        tokenLabel(currTokenType)
                    ).join(",")}]`


currTok =>
            tokenLabel(currTok)


currtok =>
            tokenLabel(currtok)


currRule => currRule.name


buildMismatchTokenMessage({
        expected,
        actual,
        previous,
        ruleName
    }): string {
        let hasLabel = hasTokenLabel(expected)
        let expectedMsg = hasLabel
            ? `--> ${tokenLabel(expected)} <--`
            : `token of type --> ${expected.name} <--`

        let msg = `Expecting ${expectedMsg} but found --> '${actual.image}' <--`

        return msg
    }


buildNotAllInputParsedMessage({ firstRedundant, ruleName }): string {
        return (
            "Redundant input, expecting EOF but found: " + firstRedundant.image
        )
    }


buildNoViableAltMessage({
        expectedPathsPerAlt,
        actual,
        previous,
        customUserDescription,
        ruleName
    }): string {
        let errPrefix = "Expecting: "
        // TODO: issue: No Viable Alternative Error may have incomplete details. #502
        let actualText = first(actual).image
        let errSuffix = "\nbut found: '" + actualText + "'"

        if (customUserDescription) {
            return errPrefix + customUserDescription + errSuffix
        } else {
            let allLookAheadPaths = reduce(
                expectedPathsPerAlt,
                (result, currAltPaths) => result.concat(currAltPaths),
                []
            )
            let nextValidTokenSequences = map(
                allLookAheadPaths,
                currPath =>
                    `[${map(currPath, currTokenType =>
                        tokenLabel(currTokenType)
                    ).join(", ")}]`
            )
            let nextValidSequenceItems = map(
                nextValidTokenSequences,
                (itemMsg, idx) => `  ${idx + 1}. ${itemMsg}`
            )
            let calculatedDescription = `one of these possible Token sequences:\n${nextValidSequenceItems.join(
                "\n"
            )}`

            return errPrefix + calculatedDescription + errSuffix
        }
    }


buildEarlyExitMessage({
        expectedIterationPaths,
        actual,
        customUserDescription,
        ruleName
    }): string {
        let errPrefix = "Expecting: "
        // TODO: issue: No Viable Alternative Error may have incomplete details. #502
        let actualText = first(actual).image
        let errSuffix = "\nbut found: '" + actualText + "'"

        if (customUserDescription) {
            return errPrefix + customUserDescription + errSuffix
        } else {
            let nextValidTokenSequences = map(
                expectedIterationPaths,
                currPath =>
                    `[${map(currPath, currTokenType =>
                        tokenLabel(currTokenType)
                    ).join(",")}]`
            )
            let calculatedDescription =
                `expecting at least one iteration which starts with one of these possible Token sequences::\n  ` +
                `<${nextValidTokenSequences.join(" ,")}>`

            return errPrefix + calculatedDescription + errSuffix
        }
    }


buildRuleNotFoundError(
        topLevelRule: Rule,
        undefinedRule: NonTerminal
    ): string {
        const msg =
            "Invalid grammar, reference to a rule which is not defined: ->" +
            undefinedRule.nonTerminalName +
            "<-\n" +
            "inside top level rule: ->" +
            topLevelRule.name +
            "<-"
        return msg
    }


buildDuplicateFoundError(
        topLevelRule: Rule,
        duplicateProds: IProductionWithOccurrence[]
    ): string {
        function getExtraProductionArgument(
            prod: IProductionWithOccurrence
        ): string {
            if (prod instanceof Terminal) {
                return prod.terminalType.name
            } else if (prod instanceof NonTerminal) {
                return prod.nonTerminalName
            } else {
                return ""
            }
        }

        const topLevelName = topLevelRule.name
        const duplicateProd = first(duplicateProds)
        const index = duplicateProd.idx
        const dslName = getProductionDslName(duplicateProd)
        let extraArgument = getExtraProductionArgument(duplicateProd)

        const hasExplicitIndex = index > 0
        let msg = `->${dslName}${hasExplicitIndex ? index : ""}<- ${
            extraArgument ? `with argument: ->${extraArgument}<-` : ""
        }
                  appears more than once (${
                      duplicateProds.length
                  } times) in the top level rule: ->${topLevelName}<-.
                  For further details see: https://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES
                  `

        // white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings...
        msg = msg.replace(/[ \t]+/g, " ")
        msg = msg.replace(/\s\s+/g, "\n")

        return msg
    }


buildInvalidNestedRuleNameError(
        topLevelRule: Rule,
        nestedProd: IOptionallyNamedProduction
    ): string {
        const msg =
            `Invalid nested rule name: ->${nestedProd.name}<- inside rule: ->${topLevelRule.name}<-\n` +
            `it must match the pattern: ->${validNestedRuleName.toString()}<-.\n` +
            `Note that this means a nested rule name must start with the '$'(dollar) sign.`

        return msg
    }


buildDuplicateNestedRuleNameError(
        topLevelRule: Rule,
        nestedProd: IOptionallyNamedProduction[]
    ): string {
        const duplicateName = first(nestedProd).name
        const errMsg =
            `Duplicate nested rule name: ->${duplicateName}<- inside rule: ->${topLevelRule.name}<-\n` +
            `A nested name must be unique in the scope of a top level grammar rule.`

        return errMsg
    }


buildNamespaceConflictError(rule: Rule): string {
        const errMsg =
            `Namespace conflict found in grammar.\n` +
            `The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${rule.name}>.\n` +
            `To resolve this make sure each Terminal and Non-Terminal names are unique\n` +
            `This is easy to accomplish by using the convention that Terminal names start with an uppercase letter\n` +
            `and Non-Terminal names start with a lower case letter.`

        return errMsg
    }


buildAlternationPrefixAmbiguityError(options: {
        topLevelRule: Rule
        prefixPath: TokenType[]
        ambiguityIndices: number[]
        alternation: Alternation
    }): string {
        const pathMsg = map(options.prefixPath, currTok =>
            tokenLabel(currTok)
        ).join(", ")
        const occurrence =
            options.alternation.idx === 0 ? "" : options.alternation.idx
        const errMsg =
            `Ambiguous alternatives: <${options.ambiguityIndices.join(
                " ,"
            )}> due to common lookahead prefix\n` +
            `in <OR${occurrence}> inside <${options.topLevelRule.name}> Rule,\n` +
            `<${pathMsg}> may appears as a prefix path in all these alternatives.\n` +
            `See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\n` +
            `For Further details.`

        return errMsg
    }


buildAlternationAmbiguityError(options: {
        topLevelRule: Rule
        prefixPath: TokenType[]
        ambiguityIndices: number[]
        alternation: Alternation
    }): string {
        let pathMsg = map(options.prefixPath, currtok =>
            tokenLabel(currtok)
        ).join(", ")
        let occurrence =
            options.alternation.idx === 0 ? "" : options.alternation.idx
        let currMessage =
            `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(
                " ,"
            )}> in <OR${occurrence}>` +
            ` inside <${options.topLevelRule.name}> Rule,\n` +
            `<${pathMsg}> may appears as a prefix path in all these alternatives.\n`

        currMessage =
            currMessage +
            `See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\n` +
            `For Further details.`
        return currMessage
    }


buildEmptyRepetitionError(options: {
        topLevelRule: Rule
        repetition: IProductionWithOccurrence
    }): string {
        let dslName = getProductionDslName(options.repetition)
        if (options.repetition.idx !== 0) {
            dslName += options.repetition.idx
        }

        const errMsg =
            `The repetition <${dslName}> within Rule <${options.topLevelRule.name}> can never consume any tokens.\n` +
            `This could lead to an infinite loop.`

        return errMsg
    }


buildTokenNameError(options: {
        tokenType: TokenType
        expectedPattern: RegExp
    }): string {
        const tokTypeName = options.tokenType.name
        const errMsg = `Invalid Grammar Token name: ->${tokTypeName}<- it must match the pattern: ->${options.expectedPattern.toString()}<-`
        return errMsg
    }


buildEmptyAlternationError(options: {
        topLevelRule: Rule
        alternation: Alternation
        emptyChoiceIdx: number
    }): string {
        const errMsg =
            `Ambiguous empty alternative: <${options.emptyChoiceIdx + 1}>` +
            ` in <OR${options.alternation.idx}> inside <${options.topLevelRule.name}> Rule.\n` +
            `Only the last alternative may be an empty alternative.`

        return errMsg
    }


buildTooManyAlternativesError(options: {
        topLevelRule: Rule
        alternation: Alternation
    }): string {
        const errMsg =
            `An Alternation cannot have more than 256 alternatives:\n` +
            `<OR${options.alternation.idx}> inside <${
                options.topLevelRule.name
            }> Rule.\n has ${options.alternation.definition.length +
                1} alternatives.`

        return errMsg
    }


buildLeftRecursionError(options: {
        topLevelRule: Rule
        leftRecursionPath: Rule[]
    }): string {
        const ruleName = options.topLevelRule.name
        let pathNames = utils.map(
            options.leftRecursionPath,
            currRule => currRule.name
        )
        let leftRecursivePath = `${ruleName} --> ${pathNames
            .concat([ruleName])
            .join(" --> ")}`
        let errMsg =
            `Left Recursion found in grammar.\n` +
            `rule: <${ruleName}> can be invoked from itself (directly or indirectly)\n` +
            `without consuming any Tokens. The grammar path that causes this is: \n ${leftRecursivePath}\n` +
            ` To fix this refactor your grammar to remove the left recursion.\n` +
            `see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.`

        return errMsg
    }


buildInvalidRuleNameError(options: {
        topLevelRule: Rule
        expectedPattern: RegExp
    }): string {
        const ruleName = options.topLevelRule.name
        const expectedPatternString = options.expectedPattern.toString()
        const errMsg = `Invalid grammar rule name: ->${ruleName}<- it must match the pattern: ->${expectedPatternString}<-`
        return errMsg
    }


buildDuplicateRuleNameError(options: {
        topLevelRule: Rule | string
        grammarName: string
    }): string {
        let ruleName
        if (options.topLevelRule instanceof Rule) {
            ruleName = options.topLevelRule.name
        } else {
            ruleName = options.topLevelRule
        }

        const errMsg = `Duplicate definition, rule: ->${ruleName}<- is already defined in the grammar: ->${options.grammarName}<-`

        return errMsg
    }


function calculatePrizeForTierPercentage(
    tierIndex: number,
    tierValue: BigNumberish,
    bitRangeSize: number,
    prizeAmount: BigNumber
): BigNumber {
    const numberOfPrizes = calculateNumberOfPrizesForTierIndex(
        bitRangeSize,
        tierIndex
    );
    const fractionOfPrize = calculateFractionOfPrize(numberOfPrizes, tierValue);
    let expectedPrizeAmount: BigNumber = prizeAmount.mul(fractionOfPrize);
    expectedPrizeAmount = expectedPrizeAmount.div(
        BigNumber.from('1000000000000000000')
    );
    return expectedPrizeAmount;
}


export interface IQuoteRequestRejectNoQuoteQualifiers {
    QuoteQualifier?: string;
}


(appendToObject: JQuery) => {

        var textNode: Text = document.createTextNode(this.text);
        if(this.style){
            var newSpan: HTMLSpanElement = document.createElement('span');
            if(this.style.getFont()) newSpan.style.font = this.style.getFont();
            if(this.style.getFontSize() != null) newSpan.style.fontSize = this.style.getFontSize() + "pt";
            if(this.style.getUnderline() != null) newSpan.style.textDecoration='underline';
            if(this.style.getColor()) newSpan.style.color = this.style.getColor();
            if(this.style.getMarginTop()) newSpan.style.marginTop = this.style.getMarginTop() + "px";
            if(this.style.getMarginBottom()) newSpan.style.marginBottom = this.style.getMarginBottom() + "px";
            if(this.style.getMarginLeft()) newSpan.style.marginLeft = this.style.getMarginLeft() + "px";
            if(this.style.getMarginRight()) newSpan.style.marginRight = this.style.getMarginRight() + "px";

            newSpan.appendChild(textNode);
            appendToObject.append(newSpan);
        } else {
            var newSpan: HTMLSpanElement = document.createElement('span');
            //appendToObject.append(textNode);
            newSpan.appendChild(textNode);
            appendToObject.append(newSpan);
        }
    }


/*
 *
 *  * Copyright 2016 Skymind,Inc.
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *        http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */
/// <reference path="../../api/Component.ts" />
/// <reference path="../../api/Margin.ts" />
/// <reference path="../../util/TSUtils.ts" />
class ComponentText extends Component implements Renderable {

    private text: string;
    private style: StyleText;

    constructor(jsonStr: string){
        super(ComponentType.ComponentText);
        var json = JSON.parse(jsonStr);
        if(!json["componentType"]) json = json[ComponentType[ComponentType.ComponentText]];

        this.text = json['text'];

        if(json['style']) this.style = new StyleText(json['style']);
    }

    render = (appendToObject: JQuery) => {

        var textNode: Text = document.createTextNode(this.text);
        if(this.style){
            var newSpan: HTMLSpanElement = document.createElement('span');
            if(this.style.getFont()) newSpan.style.font = this.style.getFont();
            if(this.style.getFontSize() != null) newSpan.style.fontSize = this.style.getFontSize() + "pt";
            if(this.style.getUnderline() != null) newSpan.style.textDecoration='underline';
            if(this.style.getColor()) newSpan.style.color = this.style.getColor();
            if(this.style.getMarginTop()) newSpan.style.marginTop = this.style.getMarginTop() + "px";
            if(this.style.getMarginBottom()) newSpan.style.marginBottom = this.style.getMarginBottom() + "px";
            if(this.style.getMarginLeft()) newSpan.style.marginLeft = this.style.getMarginLeft() + "px";
            if(this.style.getMarginRight()) newSpan.style.marginRight = this.style.getMarginRight() + "px";

            newSpan.appendChild(textNode);
            appendToObject.append(newSpan);
        } else {
            var newSpan: HTMLSpanElement = document.createElement('span');
            //appendToObject.append(textNode);
            newSpan.appendChild(textNode);
            appendToObject.append(newSpan);
        }
    }

}


function formatResponse(
  response: LedgerEntryResponse
): FormattedPaymentChannel {
  if (response.node === undefined ||
    response.node.LedgerEntryType !== 'PayChannel') {
    throw new NotFoundError('Payment channel ledger entry not found')
  }
  return parsePaymentChannel(response.node)
}


async function getPaymentChannel(
  this: RippleAPI, id: string
): Promise<FormattedPaymentChannel> {
  // 1. Validate
  validate.getPaymentChannel({id})
  // 2. Make Request
  const response = await this.request('ledger_entry', {
    index: id,
    binary: false,
    ledger_index: 'validated'
  })
  // 3. Return Formatted Response
  return formatResponse(response)
}


() => {
    it("should return 4 space indentation correctly", () => {
        const result = getDefaultIndentation(true, 4);

        expect(result).to.equal("    ");
    });

    it("should return 2 space indentation correctly", () => {
        const result = getDefaultIndentation(true, 2);

        expect(result).to.equal("  ");
    });

    it("should return tab indentation correctly", () => {
        let result = getDefaultIndentation(false, 4);

        expect(result).to.equal("\t");

        result = getDefaultIndentation(false, 8);

        expect(result).to.equal("\t");
    });
}


() => {
        const result = getDefaultIndentation(true, 4);

        expect(result).to.equal("    ");
    }


() => {
        const result = getDefaultIndentation(true, 2);

        expect(result).to.equal("  ");
    }


() => {
        let result = getDefaultIndentation(false, 4);

        expect(result).to.equal("\t");

        result = getDefaultIndentation(false, 8);

        expect(result).to.equal("\t");
    }