@Component({
  selector: 'app-home-index',
  template: `
    <ui-page>
      <ui-page-title title="Dashboard"></ui-page-title>

          <ui-dashboard-stats number="43" title="New Tickets" percentage=6></ui-dashboard-stats>

          <ui-dashboard-stats number="17" title="Closed Today" percentage=-3></ui-dashboard-stats>

          <ui-dashboard-stats number="7" title="New Replies" percentage=9></ui-dashboard-stats>

          <ui-dashboard-stats number="27.3K" title="Followers" percentage=3></ui-dashboard-stats>

          <ui-dashboard-stats number="$95" title="Daily Earnings" percentage=-2></ui-dashboard-stats>

          <ui-dashboard-stats number="621" title="Products" percentage=-1></ui-dashboard-stats>

          <app-development-activity
            [purchases]="demoService.purchases"
            [users]="demoService.users">
          </app-development-activity>

            Are you in trouble?
            Read our documentation with code samples.

            Angular-Tabler works great with Firebase!

              Check the example

            and the

              source code

              <ui-dashboard-chart title="Chart title" [data]="demoService.donut" [doughnut]="true"></ui-dashboard-chart>

              <ui-dashboard-chart title="Chart title" [data]="demoService.pie"></ui-dashboard-chart>

              <ui-dashboard-digit color="red" title="New fedbacks" digit="62" width="28%"></ui-dashboard-digit>

              <ui-dashboard-digit color="green" title="Today profit" digit="$652" width="84%"></ui-dashboard-digit>

              <ui-dashboard-digit color="yellow" title="Users online" digit="76" width="34%"></ui-dashboard-digit>

          <ui-dashboard-icon-box
            color="blue"
            icon="fe fe-dollar-sign"
            value="132"
            description="Sales"
            subtitle="12 waiting payments"></ui-dashboard-icon-box>

          <ui-dashboard-icon-box
            color="green"
            icon="fe fe-shopping-cart"
            value="78"
            description="Orders"
            subtitle="32 shipped"></ui-dashboard-icon-box>

          <ui-dashboard-icon-box
            color="red"
            icon="fe fe-users"
            value="1,352"
            description="Members"
            subtitle="163 registered today"></ui-dashboard-icon-box>

          <ui-dashboard-icon-box
            color="yellow"
            icon="fe fe-message-square"
            value="132"
            description="Comments"
            subtitle="16 waiting"></ui-dashboard-icon-box>

          <app-table-users [users]="demoService.users"></app-table-users>

          <ui-card-browser-stats></ui-card-browser-stats>

          <ui-card-projects></ui-card-projects>

          <ui-card-members [users]="demoService.users"></ui-card-members>

              <ui-dashboard-chart-bg title="423" description="Users online" color="blue" rate="+5%"></ui-dashboard-chart-bg>

              <ui-dashboard-chart-bg title="423" description="Users online" color="red" rate="-3%"></ui-dashboard-chart-bg>

              <ui-dashboard-chart-bg title="423" description="Users online" color="green" rate="-3%"></ui-dashboard-chart-bg>

              <ui-dashboard-chart-bg title="423" description="Users online" color="yellow" rate="9%"></ui-dashboard-chart-bg>

          <app-table-invoices [invoices]="demoService.invoices"></app-table-invoices>

    </ui-page>
  `,
  styles: [],
})
export class HomeIndexComponent {
  constructor(public demoService: DemoService) {}
}


function getSelectionContextSyncEventIds(): string[] {
  return [SyncUiEventId.SelectionSetChanged, SyncUiEventId.ActiveContentChanged, SyncUiEventId.ActiveViewportChanged, SessionStateActionId.SetNumItemsSelected];
}


function isSelectionSetEmpty(): boolean {
  const activeContentControl = ContentViewManager.getActiveContentControl();
  let selectionCount = 0;
  if (!UiFramework.frameworkStateKey)
    selectionCount = UiFramework.store.getState()[UiFramework.frameworkStateKey].frameworkState.sessionState.numItemsSelected;

  if (activeContentControl && activeContentControl.viewport
    && (activeContentControl.viewport.view.iModel.selectionSet.size > 0 || selectionCount > 0))
    return false;
  return true;
}


function selectionContextStateFunc(state: Readonly<BaseItemState>): BaseItemState {
  const isVisible = !isSelectionSetEmpty();
  return { ...state, isVisible };
}


function getIsHiddenIfSelectionNotActive(): ConditionalBooleanValue {
  return new ConditionalBooleanValue(isSelectionSetEmpty, getSelectionContextSyncEventIds());
}


() => {
        const iModelConnection = UiFramework.getIModelConnection();
        if (iModelConnection) {
          iModelConnection.selectionSet.emptyAll();
        }
        const tool = IModelApp.toolAdmin.primitiveTool;
        if (tool)
          tool.onRestartTool();
        else
          IModelApp.toolAdmin.startDefaultTool();
      }


/* eslint-disable react/jsx-key, deprecation/deprecation */
export class Frontstage2 extends FrontstageProvider {

  public get frontstage(): React.ReactElement<FrontstageProps> {
    const contentLayoutDef: ContentLayoutDef = new ContentLayoutDef(
      { // Four Views, two stacked on the left, two stacked on the right.
        descriptionKey: "SampleApp:ContentLayoutDef.FourQuadrants",
        verticalSplit: {
          percentage: 0.50,
          minSizeLeft: 100, minSizeRight: 100,
          left: { horizontalSplit: { percentage: 0.50, top: 0, bottom: 1, minSizeTop: 100, minSizeBottom: 100 } },
          right: { horizontalSplit: { percentage: 0.50, top: 2, bottom: 3, minSizeTop: 100, minSizeBottom: 100 } },
        },
      },
    );

    const myContentGroup: ContentGroup = new ContentGroup(
      {
        contents: [
          {
            classId: "UiFramework.IModelViewportControl",
            applicationData: { label: "Content 1a", bgColor: "black" },
          },
          {
            classId: TreeExampleContentControl,
            applicationData: { label: "Content 2a", bgColor: "black" },
          },
          {
            classId: "TestApp.IModelViewport",
            applicationData: { label: "Content 3a", bgColor: "black" },
          },
          {
            classId: HorizontalPropertyGridContentControl,
            applicationData: { label: "Content 4a", bgColor: "black" },
          },
        ],
      },
    );

    return (
      <Frontstage id="Test2"
        defaultTool={CoreTools.selectElementCommand}
        defaultLayout={contentLayoutDef} contentGroup={myContentGroup}
        isInFooterMode={false} applicationData={{ key: "value" }}

        contentManipulationTools={
          <Zone
            widgets={[
              <Widget isFreeform={true} element={<FrontstageToolWidget />} />,
            ]}


/** Define a ToolWidget with Buttons to display in the TopLeft zone.
 */
class FrontstageToolWidget extends React.Component {
  // example toolbar item that hides/shows based on selection set
  public get myClearSelectionItemDef() {
    return new CommandItemDef({
      commandId: "UiFramework.ClearSelection",
      iconSpec: "icon-selection-clear",
      labelKey: "UiFramework:buttons.clearSelection",
      stateSyncIds: getSelectionContextSyncEventIds(), /* only used when in ui 1.0 mode */
      stateFunc: selectionContextStateFunc,  /* only used when in ui 1.0 mode */
      isHidden: getIsHiddenIfSelectionNotActive(),  /* only used when in ui 2.0 mode */
      execute: () => {
        const iModelConnection = UiFramework.getIModelConnection();
        if (iModelConnection) {
          iModelConnection.selectionSet.emptyAll();
        }
        const tool = IModelApp.toolAdmin.primitiveTool;
        if (tool)
          tool.onRestartTool();
        else
          IModelApp.toolAdmin.startDefaultTool();
      },
    });
  }

  private get _horizontalToolbarItems(): ItemList {
    const items = new ItemList([
      SelectionContextToolDefinitions.clearHideIsolateEmphasizeElementsItemDef,
      SelectionContextToolDefinitions.hideSectionToolGroup,
      SelectionContextToolDefinitions.isolateSelectionToolGroup,
      SelectionContextToolDefinitions.emphasizeElementsItemDef,
      AppTools.item1,
      AppTools.item2,
      new GroupItemDef({
        groupId: "SampleApp:buttons-toolGroup",
        labelKey: "SampleApp:buttons.toolGroup",
        iconSpec: "icon-symbol",
        items: [AppTools.tool1, AppTools.tool2],
        itemsInColumn: 7,
      }),
    ]);
    return items;
  }

  private get _verticalToolbarItems(): ItemList {
    const items = new ItemList([AppTools.item3, AppTools.item4, AppTools.item5, AppTools.item6, AppTools.item7, AppTools.item8]);
    return items;
  }

  public override render() {
    return (
      <ToolWidget
        appButton={AppTools.backstageToggleCommand}
        horizontalItems={this._horizontalToolbarItems}
        verticalItems={this._verticalToolbarItems}
      />
    );
  }
}


/** Define a NavigationWidget with Buttons to display in the TopRight zone.
 */
class FrontstageNavigationWidget extends React.Component {
  public override render() {
    const horizontalItems = new ItemList([
      CoreTools.fitViewCommand,
      CoreTools.windowAreaCommand,
      CoreTools.zoomViewCommand,
      CoreTools.panViewCommand,
      CoreTools.rotateViewCommand,
    ]);

    const verticalItems = new ItemList([
      CoreTools.toggleCameraViewCommand,
    ]);

    return (
      <NavigationWidget
        horizontalItems={horizontalItems}
        verticalItems={verticalItems}
      />
    );
  }
}


public override render() {
    return (
      <ToolWidget
        appButton={AppTools.backstageToggleCommand}
        horizontalItems={this._horizontalToolbarItems}
        verticalItems={this._verticalToolbarItems}
      />
    );
  }


public override render() {
    const horizontalItems = new ItemList([
      CoreTools.fitViewCommand,
      CoreTools.windowAreaCommand,
      CoreTools.zoomViewCommand,
      CoreTools.panViewCommand,
      CoreTools.rotateViewCommand,
    ]);

    const verticalItems = new ItemList([
      CoreTools.toggleCameraViewCommand,
    ]);

    return (
      <NavigationWidget
        horizontalItems={horizontalItems}
        verticalItems={verticalItems}
      />
    );
  }


<T, ListFilter extends Record<string, any> = Record<string, any>>({
    apiKey,
    apiMethod,
    linkedId,
    itemsPerPage = 30,
    filters = {} as ListFilter,
    enabled = true,
}: Params<T, ListFilter>): AllPagesReturn<T> => {
    const [currentPage, setCurrentPage] = useState(0);
    const [loading, setLoading] = useState(true);
    const [stateFilters, setFilters] = useState<ListFilter>(filters);
    const [allData, setAllData] = useState<Array<T>>([]);
    const client = useQueryClient();

    useEffect(() => {
        let unmounted = false;
        client.getMutationCache().subscribe((mutation) => {
            if (
                mutation?.options.mutationKey === apiKey ||
                -1 < (mutation?.options.mutationKey || []).indexOf(apiKey) ||
                (linkedId && -1 < (mutation?.options.mutationKey || []).indexOf(linkedId))
            ) {
                if (!unmounted) {
                    setCurrentPage(0);
                }
            }
        });

        return (): any => (unmounted = true);
    }, []);

    const { data, lastPage } = useQueryCollection<T>(
        [apiKey, { currentPage, itemsPerPage, stateFilters, linkedId }],
        () => apiMethod(currentPage, itemsPerPage, stateFilters),
        {
            enabled: enabled && 0 < currentPage,
        },
    );

    useEffect(() => {
        let unmounted = false;
        if (data) {
            setAllData([...(1 === currentPage ? [] : allData), ...data]);
            if (currentPage < lastPage) {
                if (!unmounted) {
                    setCurrentPage(currentPage + 1);
                }
            } else {
                if (!unmounted) {
                    setLoading(false);
                }
            }
        }

        return (): any => (unmounted = true);
    }, [currentPage, data, lastPage]);

    useEffect(() => {
        let unmounted = false;
        if (enabled && 0 === currentPage && !unmounted) {
            setCurrentPage(currentPage + 1);
        }

        return (): any => (unmounted = true);
    }, [enabled, currentPage]);

    useEffect(() => {
        let unmounted = false;
        if (JSON.stringify(stateFilters) !== JSON.stringify(filters)) {
            if (!unmounted) {
                setFilters(filters);
            }
        }
        return (): any => (unmounted = true);
    }, [filters]);

    return {
        isLoading: loading,
        data: allData,
    };
}


() => {
        let unmounted = false;
        client.getMutationCache().subscribe((mutation) => {
            if (
                mutation?.options.mutationKey === apiKey ||
                -1 < (mutation?.options.mutationKey || []).indexOf(apiKey) ||
                (linkedId && -1 < (mutation?.options.mutationKey || []).indexOf(linkedId))
            ) {
                if (!unmounted) {
                    setCurrentPage(0);
                }
            }
        });

        return (): any => (unmounted = true);
    }


(mutation) => {
            if (
                mutation?.options.mutationKey === apiKey ||
                -1 < (mutation?.options.mutationKey || []).indexOf(apiKey) ||
                (linkedId && -1 < (mutation?.options.mutationKey || []).indexOf(linkedId))
            ) {
                if (!unmounted) {
                    setCurrentPage(0);
                }
            }
        }


(): any => (unmounted = true)


() => apiMethod(currentPage, itemsPerPage, stateFilters)


() => {
        let unmounted = false;
        if (data) {
            setAllData([...(1 === currentPage ? [] : allData), ...data]);
            if (currentPage < lastPage) {
                if (!unmounted) {
                    setCurrentPage(currentPage + 1);
                }
            } else {
                if (!unmounted) {
                    setLoading(false);
                }
            }
        }

        return (): any => (unmounted = true);
    }


() => {
        let unmounted = false;
        if (enabled && 0 === currentPage && !unmounted) {
            setCurrentPage(currentPage + 1);
        }

        return (): any => (unmounted = true);
    }


() => {
        let unmounted = false;
        if (JSON.stringify(stateFilters) !== JSON.stringify(filters)) {
            if (!unmounted) {
                setFilters(filters);
            }
        }
        return (): any => (unmounted = true);
    }


type AllPagesReturn<T> = {
    isLoading: boolean;
    data: Array<T>;
};


type Params<T, ListFilter extends Record<string, any> = Record<string, any>> = {
    apiKey: string;
    apiMethod: ResourceApi<T>['fetchPage'];
    linkedId?: string;
    itemsPerPage?: number;
    filters?: ListFilter;
    enabled?: boolean;
};


export interface IPositionQtyNoPositions {
  PosType?: string// 703
  LongQty?: number// 704
  ShortQty?: number// 705
  PosQtyStatus?: number// 706
  NestedParties: INestedParties
}


export class Asserts
{

	/**
	 * Throw an error if the condition is false.
	 */
	public static Assert( condition: boolean, message?: string ): asserts condition
	{
		if( !condition )
		{
			throw new Error( message );
		}
	}

	/**
	 * Throw an error if mightBeUndefined is undefined.
	 */
	public static AssertDefined< T >( mightBeUndefined: T | undefined, message?: string ): asserts mightBeUndefined is Exclude< T, null >
	{
		Asserts.Assert( mightBeUndefined !== undefined, message );
	}

	/**
	 * Throw an error if mightBeUndefinedOrNull is undefined or null.
	 */
	public static AssertNotNull< T >( mightBeUndefinedOrNull: T | undefined, message?: string ): asserts mightBeUndefinedOrNull is NonNullable< T >
	{
		Asserts.Assert( mightBeUndefinedOrNull !== undefined && mightBeUndefinedOrNull !== null, message );
	}

	/**
	 * Throw an error if the function is called.
	 */
	public static Fail(): never
	{
		throw new Error( "This function should not be called" );
	}
}


/**
	 * Throw an error if the condition is false.
	 */
public static Assert( condition: boolean, message?: string ): asserts condition
	{
		if( !condition )
		{
			throw new Error( message );
		}
	}


/**
	 * Throw an error if mightBeUndefined is undefined.
	 */
public static AssertDefined< T >( mightBeUndefined: T | undefined, message?: string ): asserts mightBeUndefined is Exclude< T, null >
	{
		Asserts.Assert( mightBeUndefined !== undefined, message );
	}


/**
	 * Throw an error if mightBeUndefinedOrNull is undefined or null.
	 */
public static AssertNotNull< T >( mightBeUndefinedOrNull: T | undefined, message?: string ): asserts mightBeUndefinedOrNull is NonNullable< T >
	{
		Asserts.Assert( mightBeUndefinedOrNull !== undefined && mightBeUndefinedOrNull !== null, message );
	}


/**
	 * Throw an error if the function is called.
	 */
public static Fail(): never
	{
		throw new Error( "This function should not be called" );
	}


() => {
      // Email sent.
    }


(error) => {
      // An error happened.
    }


@Injectable()
export class UserService {

  private tabelPrefix: string = tenant.tenants['default'].databasePrefix;

  constructor(private alertService: AlertService) {}

  public saveUserInfo(uid: string, name: string, email: string): Promise<string> {
    return firebase.database().ref().child(this.tabelPrefix + 'users/' + uid).set({
      name: name,
      email: email
    });
  }

  public updateUserInfo(uid: string, displayName: string, bio: string): Promise<string> {
    return firebase.database().ref().child(this.tabelPrefix + 'users/' + uid).update({
      displayName: displayName,
      bio: bio
    });
  }

  public keepInTouch(email: string) {
    this.alertService.showToaster('Your email is saved');
    return firebase.database().ref().child(this.tabelPrefix + 'touch/').push({
      email: email
    });
  }

  public contactFormSend(
    company: string,
    firstname: string,
    lastname: string,
    address: string,
    city: string,
    postal: string,
    message: string
  ) {
    this.alertService.showToaster('This contact form is saved');
    return firebase.database().ref().child(this.tabelPrefix + 'contactform/').push({
      company: company,
      firstname: firstname,
      lastname: lastname,
      address: address,
      city: city,
      postal: postal,
      message: message
    });
  }

  public getUserProfileInformation(): void {
    const user = firebase.auth().currentUser;
    let name, email, photoUrl, uid, emailVerified;

    if (user != null) {
      name = user.displayName;
      email = user.email;
      photoUrl = user.photoURL;
      emailVerified = user.emailVerified;
      uid = user.uid;
    }
  }

  public verificationUserEmail(): Promise<void> {
    return firebase.auth().currentUser.sendEmailVerification().then(() => {
      // Email sent.
    }, (error) => {
      // An error happened.
    });
  }

  public sendUserPasswordResetEmail(): Promise<void> {
    return firebase.auth().sendPasswordResetEmail(firebase.auth().currentUser.email).then(() => {
      // Email sent.
    }, (error) => {
      // An error happened.
    });
  }

}


public saveUserInfo(uid: string, name: string, email: string): Promise<string> {
    return firebase.database().ref().child(this.tabelPrefix + 'users/' + uid).set({
      name: name,
      email: email
    });
  }


public updateUserInfo(uid: string, displayName: string, bio: string): Promise<string> {
    return firebase.database().ref().child(this.tabelPrefix + 'users/' + uid).update({
      displayName: displayName,
      bio: bio
    });
  }


public keepInTouch(email: string) {
    this.alertService.showToaster('Your email is saved');
    return firebase.database().ref().child(this.tabelPrefix + 'touch/').push({
      email: email
    });
  }


public contactFormSend(
    company: string,
    firstname: string,
    lastname: string,
    address: string,
    city: string,
    postal: string,
    message: string
  ) {
    this.alertService.showToaster('This contact form is saved');
    return firebase.database().ref().child(this.tabelPrefix + 'contactform/').push({
      company: company,
      firstname: firstname,
      lastname: lastname,
      address: address,
      city: city,
      postal: postal,
      message: message
    });
  }


public getUserProfileInformation(): void {
    const user = firebase.auth().currentUser;
    let name, email, photoUrl, uid, emailVerified;

    if (user != null) {
      name = user.displayName;
      email = user.email;
      photoUrl = user.photoURL;
      emailVerified = user.emailVerified;
      uid = user.uid;
    }
  }


public verificationUserEmail(): Promise<void> {
    return firebase.auth().currentUser.sendEmailVerification().then(() => {
      // Email sent.
    }, (error) => {
      // An error happened.
    });
  }


public sendUserPasswordResetEmail(): Promise<void> {
    return firebase.auth().sendPasswordResetEmail(firebase.auth().currentUser.email).then(() => {
      // Email sent.
    }, (error) => {
      // An error happened.
    });
  }


@NgModule({
    imports: [
        CommonModule,
        BrowserAnimationsModule,
        FormsModule,
        RouterModule,
        ComponentsModule,
        NgxSiemaModule.forRoot(),
    ],
    declarations: [ HomeComponent, LandingComponent ],
    exports:[ HomeComponent ],
    providers: [
    ]
})
export class HomeModule { }


interface Foo {
    varWithoutTypeAnnotation;
    varAsAny: any;
    varAsNumber: number;
    varAsBoolean: boolean;
    varAsString: string;
}


interface Bar {
        name: string;
    }


/**
   * Tenant access metadata
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param [options] The optional parameters
   * @returns Promise<Models.TenantAccessGetEntityTagResponse>
   */
getEntityTag(resourceGroupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<Models.TenantAccessGetEntityTagResponse>;


/**
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param callback The callback
   */
getEntityTag(resourceGroupName: string, serviceName: string, callback: msRest.ServiceCallback<void>): void;


/**
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param options The optional parameters
   * @param callback The callback
   */
getEntityTag(resourceGroupName: string, serviceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;


getEntityTag(resourceGroupName: string, serviceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<Models.TenantAccessGetEntityTagResponse> {
    return this.client.sendOperationRequest(
      {
        resourceGroupName,
        serviceName,
        options
      },
      getEntityTagOperationSpec,
      callback) as Promise<Models.TenantAccessGetEntityTagResponse>;
  }


/**
   * Get tenant access information details
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param [options] The optional parameters
   * @returns Promise<Models.TenantAccessGetResponse>
   */
get(resourceGroupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<Models.TenantAccessGetResponse>;


/**
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param callback The callback
   */
get(resourceGroupName: string, serviceName: string, callback: msRest.ServiceCallback<Models.AccessInformationContract>): void;


/**
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param options The optional parameters
   * @param callback The callback
   */
get(resourceGroupName: string, serviceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AccessInformationContract>): void;


get(resourceGroupName: string, serviceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AccessInformationContract>, callback?: msRest.ServiceCallback<Models.AccessInformationContract>): Promise<Models.TenantAccessGetResponse> {
    return this.client.sendOperationRequest(
      {
        resourceGroupName,
        serviceName,
        options
      },
      getOperationSpec,
      callback) as Promise<Models.TenantAccessGetResponse>;
  }


/**
   * Update tenant access information details.
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param parameters Parameters supplied to retrieve the Tenant Access Information.
   * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
   * response of the GET request or it should be * for unconditional update.
   * @param [options] The optional parameters
   * @returns Promise<msRest.RestResponse>
   */
update(resourceGroupName: string, serviceName: string, parameters: Models.AccessInformationUpdateParameters, ifMatch: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;


/**
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param parameters Parameters supplied to retrieve the Tenant Access Information.
   * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
   * response of the GET request or it should be * for unconditional update.
   * @param callback The callback
   */
update(resourceGroupName: string, serviceName: string, parameters: Models.AccessInformationUpdateParameters, ifMatch: string, callback: msRest.ServiceCallback<void>): void;


/**
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param parameters Parameters supplied to retrieve the Tenant Access Information.
   * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
   * response of the GET request or it should be * for unconditional update.
   * @param options The optional parameters
   * @param callback The callback
   */
update(resourceGroupName: string, serviceName: string, parameters: Models.AccessInformationUpdateParameters, ifMatch: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;


update(resourceGroupName: string, serviceName: string, parameters: Models.AccessInformationUpdateParameters, ifMatch: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
    return this.client.sendOperationRequest(
      {
        resourceGroupName,
        serviceName,
        parameters,
        ifMatch,
        options
      },
      updateOperationSpec,
      callback);
  }


/**
   * Regenerate primary access key
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param [options] The optional parameters
   * @returns Promise<msRest.RestResponse>
   */
regeneratePrimaryKey(resourceGroupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;


/**
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param callback The callback
   */
regeneratePrimaryKey(resourceGroupName: string, serviceName: string, callback: msRest.ServiceCallback<void>): void;


/**
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param options The optional parameters
   * @param callback The callback
   */
regeneratePrimaryKey(resourceGroupName: string, serviceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;


regeneratePrimaryKey(resourceGroupName: string, serviceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
    return this.client.sendOperationRequest(
      {
        resourceGroupName,
        serviceName,
        options
      },
      regeneratePrimaryKeyOperationSpec,
      callback);
  }


/**
   * Regenerate secondary access key
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param [options] The optional parameters
   * @returns Promise<msRest.RestResponse>
   */
regenerateSecondaryKey(resourceGroupName: string, serviceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;


/**
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param callback The callback
   */
regenerateSecondaryKey(resourceGroupName: string, serviceName: string, callback: msRest.ServiceCallback<void>): void;


/**
   * @param resourceGroupName The name of the resource group.
   * @param serviceName The name of the API Management service.
   * @param options The optional parameters
   * @param callback The callback
   */
regenerateSecondaryKey(resourceGroupName: string, serviceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;


regenerateSecondaryKey(resourceGroupName: string, serviceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
    return this.client.sendOperationRequest(
      {
        resourceGroupName,
        serviceName,
        options
      },
      regenerateSecondaryKeyOperationSpec,
      callback);
  }


/**
 * \@author Sandeep.Mantha
 * \@whatItDoes
 *
 * \@howToUse
 *
 */
export class LoggerService {

    public info(message:string) {
        this.write(message,LogLevel.info);
    }

    public warn(message:string) {
        this.write(message,LogLevel.warn);
    }

    public error(message:string) {
        this.write(message,LogLevel.error)
    }

    public debug(message:string) {
        this.write(message,LogLevel.debug)
    }

    public trace(message:string) {
        this.write(message,LogLevel.trace)
    }

    public write(logMessage: string, logLevel: LogLevel) {

        let logEntry = new LogEntry(logMessage,new Date(), logLevel);
        console.log(logEntry.message + logEntry.time + logEntry.level);
    }

}


public info(message:string) {
        this.write(message,LogLevel.info);
    }


public warn(message:string) {
        this.write(message,LogLevel.warn);
    }


public error(message:string) {
        this.write(message,LogLevel.error)
    }


public debug(message:string) {
        this.write(message,LogLevel.debug)
    }


public trace(message:string) {
        this.write(message,LogLevel.trace)
    }


public write(logMessage: string, logLevel: LogLevel) {

        let logEntry = new LogEntry(logMessage,new Date(), logLevel);
        console.log(logEntry.message + logEntry.time + logEntry.level);
    }


function _max<T extends number | string | Date>(a: T, b: T) {
  return a > b ? a : b
}


// @types
type Max_2<T extends number | string | Date> = (b: T) => T


type Max_1<T extends number | string | Date> = (a: T) => T


// prettier-ignore
type _Max<T extends number | string | Date> =
  & ((a: T, b?: PH) => Max_2<T>)
  & ((a: PH, b: T) => Max_1<T>)
  & ((a: T, b: T) => T)


type Max = _Max<number> & _Max<string> & _Max<Date>


(props: NavProps) => {
	const { active } = props
	const [user, loading] = useAuthState()
	const router = useRouter()

	return (

				<Image
					src="/icon.png"
					alt="Site Icon"
					width={30}
					height={30}
					className={style.button}
					onClick={()


async ()


export class Option {

    wrappedOption: IOption;

    disabled: boolean;
    highlighted: boolean;
    selected: boolean;
    shown: boolean;
    group: boolean;

    constructor(option: IOption) {
        this.wrappedOption = option;

        this.disabled = false;
        this.highlighted = false;
        this.selected = false;
        this.shown = true;
        this.group = false;
    }

    get value(): string {
        return this.wrappedOption.value;
    }

    get label(): string {
        return this.wrappedOption.label;
    }

    get icon(): string {
        if(this.wrappedOption.icon !== "" && this.wrappedOption.icon !== undefined) {
            return this.wrappedOption.icon;
        } else {
            return "";
        }

    }
}


export declare class ShapeUtils {
    static wrapToShape(obj: any): AShape;
}


static wrapToShape(obj: any): AShape;


export interface ITextData {
	formats: TextFormat[],
	elementFormats: ElementFormat[],
	formatIndices: number[],
	text: string,
	processedIdx: number,
	creationResult: string,
	spaces: NumberMap<boolean>,
	lineBreaks: NumberMap<number>,
	charWidths: number[],
}


const enum CHAR_CODES {
	TAB = 9,
	LF = 10,
	CR = 13,
	SPACE = 32,
	BS = 92,
	N = 110,
	R = 114,
}


public setTextDataDirty() {
		this._textData = null;
	}


private _convertContentToTextData() {
		if (this._textData) {
			return this._textData;
		}
		this._textData = {
			text: '',
			formats: [],
			elementFormats: [],
			formatIndices: [],
			processedIdx: 0,
			creationResult: null,
			spaces: {},
			lineBreaks: {},
			charWidths: []
		};
		this.resolveGroupElements(this._content);

		if (this._textData.formatIndices[this._textData.formatIndices.length - 1] != this._textData.text.length)
			this._textData.formatIndices.push(this._textData.text.length);

		const formats = this._textData.formats;
		const formatsIndicies = this._textData.formatIndices;
		/*if (this._textData.text.charCodeAt(this._textData.text.length - 1) == 8233) {
			this._textData.text = this._textData.text.substring(0, this._textData.text.length - 1);
		}*/
		const text = this._textData.text;
		this._content.rawText = text;
		const spaces = this._textData.spaces;
		const lineBreaks = this._textData.lineBreaks;
		const charWidths = this._textData.charWidths;

		let c = 0;
		const form_len = formats.length;
		for (let f = 0; f < form_len; f++) {

			const tf = formats[f];
			tf.font_table.initFontSize(tf.size);
			const lastChar = formatsIndicies[f];
			for (c; c <= lastChar; c++) {
				const char_code = text.charCodeAt(c);
				const isLineBreak = char_code === CHAR_CODES.LF || char_code === 8233;
				if (isLineBreak) {
					lineBreaks[c] = 1;
					charWidths[charWidths.length] = 0;
				} else {
					charWidths[charWidths.length] = tf.font_table.getCharWidth(char_code.toString());
					const isSpace = char_code == CHAR_CODES.TAB || char_code == CHAR_CODES.SPACE;
					if (isSpace) {
						spaces[c] = true;
					}
				}
			}
		}
	}


private resolveGroupElements(content: ContentElement) {

		if (content.axClassName == 'flash.text.engine.TextElement') {
			const text = content.text;
			const elementFormat = content.elementFormat;
			let tf;
			if (elementFormat)
				tf = elementFormat.createAwayTextformat();
			else {
				tf = new TextFormat();
			}
			this._textData.text += text ? text : '';
			this._textData.formats.push(tf);
			this._textData.elementFormats.push(elementFormat);
			this._textData.formatIndices.push(this._textData.text.length);
		}
		if (content.axClassName == 'flash.text.engine.GroupElement') {
			const group = <GroupElement><any>content;
			//noLogs || console.log('resolve GroupElement', group.elementCount);
			for (let i = 0; i < group.elementCount; i++) {
				this.resolveGroupElements(group.getElementAt(i));
			}
		}
	}


public createTextLine(
		previousLine?: TextLine,
		width?: number,
		lineOffset?: number,
		fitSomething?: boolean): TextLine {

		if (!this._textData) {
			this._textLines = [];
			this._convertContentToTextData();
		}

		if (this._tabStops && this._tabStops.buffer.length > 0) {
			console.warn('this._tabStops is not []', this._tabStops);
		}
		if (this._textJustifier && this._textJustifier.lineJustification != 'unjustified') {
			console.warn('lineJustification is not unjustified', this._textJustifier.lineJustification);
		}
		if (this._textJustifier && (<any> this._textJustifier).letterSpacing != 0) {
			console.warn('letterSpacing is not 0', (<any> this._textJustifier).letterSpacing);
		}
		if (this._baselineZero != TextBaseline.ROMAN) {
			console.warn('_baselineZero is not "roman"', this._baselineZero);
		}

		noLogs || console.log('[TextBlock]  ' + this._id + '   - text',
			this._textData.text);
		noLogs || console.log('[TextBlock]  ' + this._id + '   - createTextLine',
			'\n		width', width,
			'\n		previousLine', previousLine,
			'\n		lineOffset', lineOffset,
			'\n		fitSomething', fitSomething,
			'\n		processedIdx', this._textData.processedIdx);

		const text = this._textData.text;
		let processedIdx = this._textData.processedIdx;
		if (processedIdx > text.length) {
			this._creationResult = TextLineCreationResult.COMPLETE;
			noLogs || console.log('[TextBlock]  ' + this._id + '   - all textlines already complete',
				processedIdx, text.length);
			return null;
		}
		const formats = this._textData.formats;
		const elementFormats = this._textData.elementFormats;
		const formatsIndicies = this._textData.formatIndices;
		const spaces = this._textData.spaces;
		const lineBreaks = this._textData.lineBreaks;
		const charWidths = this._textData.charWidths;

		const form_len = formats.length;
		let c = processedIdx;
		let newText = '';
		let newWord = '';
		let newCharCnt = 0;
		const newFormats = [];
		const newElementFormats = [];
		const newFormatindices = [];
		let result = TextLineCreationResult.EMERGENCY; // is valid if its a linebreak or at least one word that fits
		let textWidth = 0;
		let defaultFormat;
		let defaultElementFormat;
		loop1:
		for (let f = 0; f < form_len; f++) {
			if (processedIdx > formatsIndicies[f]) {
				continue;
			}
			const format = formats[f];
			defaultFormat = format;
			newFormats[newFormats.length] = format;
			newElementFormats[newElementFormats.length] = elementFormats[f];
			defaultElementFormat = elementFormats[f];
			newFormatindices[newFormatindices.length] = 0;
			const lastChar = formatsIndicies[f];
			for (c; c <= lastChar; c++) {
				if (lineBreaks[c] === 1) {
					noLogs || console.log('lineBreaks', result, c, text[c]);
					newText += newWord;
					newCharCnt += newWord.length + 1;
					result = TextLineCreationResult.SUCCESS;
					this._textData.processedIdx = c;
					// remove the linebreak marker so we not stuck in infinite loop
					lineBreaks[c] = 2;
					break loop1;
				}
				if (spaces[c]) {
					noLogs || console.log('space', result, c, text[c], newWord);
					result = TextLineCreationResult.SUCCESS;
					newText += newWord;
					newCharCnt += newWord.length;
					newWord = '';
					this._textData.processedIdx = c;
				}
				if (newWord.length == 1 &&
					(newWord.charCodeAt(0) == CHAR_CODES.SPACE || newWord.charCodeAt(0) == CHAR_CODES.TAB)) {
					result = TextLineCreationResult.SUCCESS;
					newText += newWord;
					newCharCnt += newWord.length;
					newWord = '';
					this._textData.processedIdx = c;
				}
				textWidth += charWidths[c];
				if (textWidth > width - 2) {
					noLogs || console.log('text is to wide', 'textWidth', textWidth,
						'width', width, newText, result, text[c], newWord);
					if (result == TextLineCreationResult.SUCCESS) {
						break loop1;
					}
					newText += newWord;
					newCharCnt += newWord.length;
					this._textData.processedIdx = c;
					break loop1;

				}
				if (c == text.length) {
					newText += newWord;
					newCharCnt += newWord.length;
					this._textData.processedIdx = c + 1;
					break loop1;
				}
				if (!lineBreaks[c]) {
					newWord += text[c];
				} else {
					newWord += text[c];
					processedIdx++;
				}
			}
			newFormatindices[newFormatindices.length - 1] = newText.length + newWord.length - 1;
		}
		newFormatindices[newFormatindices.length - 1] = newText.length;
		if (this._textData.processedIdx >= text.length) {
			noLogs || console.log('[TextBlock]  ' + this._id + '   - all text processed',
				this._textData.processedIdx, text.length);
			this._textData.processedIdx++;
			result = TextLineCreationResult.COMPLETE;
		}

		noLogs || console.log('[TextBlock]  ' + this._id + '   - textline prepared',
			this._textData.processedIdx, `"${newText}"`);
		noLogs || console.log('[TextBlock]  ' + this._id + '   - all text length',
			text.length, 'newCharCnt', newCharCnt, 'processedIdx', processedIdx);

		//this._textData.processedIdx = text.length + 1;

		if (newFormats.length == 0) {
			newFormats[0] = defaultFormat;
			newElementFormats[0] = defaultElementFormat;
		}

		let textLine: TextLine;
		for (let c = 0; c < textLinePool.length; c++) {
			if (!textLinePool[c].parent && textLinePool[c].free) {
				textLine = textLinePool[c];
				break;

			}
		}
		if (textLine) {
			textLine.setPreviousLine(null);
			textLine.setNextLine(null);
			textLine['$BguserData'] = null;
			(<any> textLine).free = false;
			textLine.reUseTextLine(
				previousLine,
				width,
				lineOffset,
				fitSomething,
				newText, newFormats, newFormatindices,
				processedIdx, newCharCnt, newElementFormats);
		} else {
			textLine = new (<any> this.sec).flash.text.engine.TextLine(
				previousLine,
				width,
				lineOffset,
				fitSomething,
				newText, newFormats, newFormatindices,
				processedIdx, newCharCnt, newElementFormats);
		}

		this._creationResult = result;
		textLine.setTextBlock(this);
		this._textLines.push(textLine);
		return textLine;
	}


public recreateTextLine(textLine: TextLine,
		previousLine?: TextLine,
		width?: number,
		lineOffset?: number,
		fitSomething?: boolean): TextLine {
		// @todo
		Debug.throwPIR('playerglobals/text/engine/TextBlock', 'recreateTextLine', '');
		return new (<any> this.sec).flash.text.engine.TextLine();
	}


public findNextAtomBoundary(afterCharIndex: number /*int*/): number /*int*/ {
		// @todo
		Debug.throwPIR('playerglobals/text/engine/TextBlock', 'findNextAtomBoundary', '');
		return null;
	}


public findPreviousAtomBoundary(beforeCharIndex: number /*int*/): number /*int*/ {
		// @todo
		Debug.throwPIR('playerglobals/text/engine/TextBlock', 'findPreviousAtomBoundary', '');
		return null;
	}


public findNextWordBoundary(afterCharIndex: number /*int*/): number /*int*/ {
		// @todo
		Debug.throwPIR('playerglobals/text/engine/TextBlock', 'findNextWordBoundary', '');
		return null;
	}


public findPreviousWordBoundary(beforeCharIndex: number /*int*/): number /*int*/ {
		// @todo
		Debug.throwPIR('playerglobals/text/engine/TextBlock', 'findPreviousWordBoundary', '');
		return null;
	}


public getTextLineAtCharIndex(charIndex: number /*int*/): TextLine {
		// @todo
		Debug.throwPIR('playerglobals/text/engine/TextBlock', 'getTextLineAtCharIndex', '');
		return null;
	}


public releaseLineCreationData(): void {
		// @todo
		Debug.throwPIR('playerglobals/text/engine/TextBlock', 'releaseLineCreationData', '');
	}


public releaseLines(firstLine: TextLine, lastLine: TextLine): void {
		//console.warn('[TextBlock]  ' + this._id + '   - releaseLines not implemented');
		if (this._textLines.length == 0)
			return;
		if (firstLine == this._textLines[0] && lastLine == this._textLines[this._textLines.length - 1]) {
			if (textLinePool.length < 100) {
				for (let i = 0; i < this._textLines.length; i++) {
					(<any> this._textLines[i]).free = true;
					if (textLinePool.indexOf(this._textLines[i]) <= 0)
						textLinePool.push(this._textLines[i]);
				}
			}
			this._textLines.length = 0;
			return;
		}
		while (firstLine) {
			const idx = this._textLines.indexOf(firstLine);
			if (idx >= 0) {
				this._textLines.splice(idx, 1);
			}
			(<any> firstLine).free = true;
			if (textLinePool.indexOf(firstLine) <= 0)
				textLinePool.push(firstLine);
			if (firstLine != lastLine)
				firstLine = firstLine.nextLine;
			else
				firstLine = null;
		}
	}


public dump(): string {
		// @todo
		Debug.throwPIR('playerglobals/text/engine/TextBlock', 'dump', '');
		return null;
	}


public DoCreateTextLine(
		previousLine: TextLine,
		width: number,
		lineOffset: number = 0,
		fitSomething: boolean = false,
		reuseLine: TextLine = null): TextLine {
		// @todo
		Debug.throwPIR('playerglobals/text/engine/TextBlock', 'DoCreateTextLine', '');
		return null;
	}


public getTabStops(): any/*ASVector<flash.text.engine.TabStop>*/ {
		noLogs || console.log('[TextBlock]  ' + this._id + '   - getTabStops', this._tabStops);
		return this._tabStops;
	}


public setTabStops(value: any/*ASVector<flash.text.engine.TabStop>*/) {
		noLogs || console.log('[TextBlock]  ' + this._id + '   - setTabStops not implemented', value);
		this._tabStops = value;
	}


public getTextJustifier(): TextJustifier {
		noLogs || console.log('[TextBlock]  ' + this._id + '   - getTextJustifier', this._textJustifier);
		return this._textJustifier;
	}


public setTextJustifier(value: TextJustifier) {
		noLogs || console.log('[TextBlock]  ' + this._id + '   - setTextJustifier', value);
		this._textJustifier = value;
	}


(role) => {
      this.userRole = role;
    }


@Component({
  selector: 'app-user-view',
  templateUrl: './user-view.component.html',
  styleUrls: ['./user-view.component.css']
})
export class UserViewComponent implements AfterViewInit {
  userRole :string;

  constructor(private router: Router, private userService: UserService) {
    this.userService.getUserRole().then((role) => {
      this.userRole = role;
    })
  }

  ngAfterViewInit(){
  	this.router.navigate(['dashboard/map']);
  }

  logout(){
  	this.userService.logout();
  	this.router.navigate(['login']);
  }
}


ngAfterViewInit(){
  	this.router.navigate(['dashboard/map']);
  }


logout(){
  	this.userService.logout();
  	this.router.navigate(['login']);
  }


interface Channels$SelectableChannelCloser {
      implCloseChannel(arg0: java.nio.channels.SelectableChannel): void
      implReleaseChannel(arg0: java.nio.channels.SelectableChannel): void
    }


resolve => {
      process.stdin.once('data', (data) => {
        const input = data.toString()

        // special keys
        switch (input) {
          case '\u001B\u005B\u0041': return resolve(GameInput.UP)
          case '\u001B\u005B\u0042': return resolve(GameInput.DOWN)
          case '\u001B\u005B\u0043': return resolve(GameInput.MORE)
          case '\u001B\u005B\u0044': return resolve(GameInput.LESS)
          case '\u000A':
          case '\u000D': return resolve(GameInput.SUBMIT)
          case '\u007F': return resolve(GameInput.BACKSPACE)
        }

        // Ctrl+C -> quit program
        if (input === '\u0003') {
          term.processExit(0)
        }

        // allowed keyboard input (used for player names)
        if (input.length === 1 && ('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_+= ').includes(input)) {
          return resolve(input)
        }

        return resolve(GameInput.UNKNOWN)
      })
    }


(data) => {
        const input = data.toString()

        // special keys
        switch (input) {
          case '\u001B\u005B\u0041': return resolve(GameInput.UP)
          case '\u001B\u005B\u0042': return resolve(GameInput.DOWN)
          case '\u001B\u005B\u0043': return resolve(GameInput.MORE)
          case '\u001B\u005B\u0044': return resolve(GameInput.LESS)
          case '\u000A':
          case '\u000D': return resolve(GameInput.SUBMIT)
          case '\u007F': return resolve(GameInput.BACKSPACE)
        }

        // Ctrl+C -> quit program
        if (input === '\u0003') {
          term.processExit(0)
        }

        // allowed keyboard input (used for player names)
        if (input.length === 1 && ('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_+= ').includes(input)) {
          return resolve(input)
        }

        return resolve(GameInput.UNKNOWN)
      }


() => this.draw()


enum UIStep {
  TITLE_SCREEN,
  OPTIONS,
  IN_GAME,
  GAME_SUMMARY
}


enum GameOption {
  PLAYER_1_NAME,
  PLAYER_2_NAME,
  STACKS_COUNT,
  MAX_STICKS_PER_TURN,
  SUBMIT
}


// get
private async getGameInput (): Promise<Symbol | string> {
    return new Promise(resolve => {
      process.stdin.once('data', (data) => {
        const input = data.toString()

        // special keys
        switch (input) {
          case '\u001B\u005B\u0041': return resolve(GameInput.UP)
          case '\u001B\u005B\u0042': return resolve(GameInput.DOWN)
          case '\u001B\u005B\u0043': return resolve(GameInput.MORE)
          case '\u001B\u005B\u0044': return resolve(GameInput.LESS)
          case '\u000A':
          case '\u000D': return resolve(GameInput.SUBMIT)
          case '\u007F': return resolve(GameInput.BACKSPACE)
        }

        // Ctrl+C -> quit program
        if (input === '\u0003') {
          term.processExit(0)
        }

        // allowed keyboard input (used for player names)
        if (input.length === 1 && ('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_+= ').includes(input)) {
          return resolve(input)
        }

        return resolve(GameInput.UNKNOWN)
      })
    })
  }


// reset the screen, used before each UI draw
private reset (): void {
    term.clear().move(2, 2)
    term.styleReset().bold.cyan('Nim Game').styleReset('\n\n')
  }


// title screen
private async printTitleScreen (): Promise<void> {
    this.reset()

    term(' Press any key to start...')

    await this.getGameInput()

    this.step = UIStep.OPTIONS
  }


// print option and its current value on screen
// applies special styling whener or not the option is selected
private printOption (id: GameOption, name: string, value: number | string): void {
    term.styleReset()

    if (this.curGameOption === id) {
      term('\n ').bgBrightBlue(name).styleReset(': ')
    } else {
      term('\n ' + name + ': ')
    }

    term.styleReset().red(value)
  }


// changes a numeric option like stack count or max sticks per turn
// left arrow to increment by one
// right arrow to decrement by one
private updateNumericOption (action: Symbol): void {
    const delta = action === GameInput.MORE ? 1 : -1

    if (this.curGameOption === GameOption.STACKS_COUNT) {
      const newValue = this.stacksCount + delta

      if (OPTION_BOUNDARIES.stacksCount.max >= newValue && newValue >= OPTION_BOUNDARIES.stacksCount.min) {
        this.stacksCount = newValue
      }
    } else if (this.curGameOption === GameOption.MAX_STICKS_PER_TURN) {
      const newValue = this.maxSticksPerTurn + delta

      if (OPTION_BOUNDARIES.maxSticksPerTurn.max >= newValue && newValue >= OPTION_BOUNDARIES.maxSticksPerTurn.min) {
        this.maxSticksPerTurn = newValue
      }
    }
  }


// draws the options UI to let users set player names and other options for the game
private async drawOptionsScreen (): Promise<void> {
    this.reset()

    term.bold(' * Game Options *')
    term.styleReset('\n Use UP and DOWN to move between options, RIGHT and LEFT to change numeric values, and regular keyboard (A-Z, a-z, spaces, and -_+=) for player names')

    this.printOption(GameOption.PLAYER_1_NAME, 'Player #1', this.players[0])
    this.printOption(GameOption.PLAYER_2_NAME, 'Player #2', this.players[1])
    this.printOption(GameOption.STACKS_COUNT, 'Stacks', this.stacksCount)
    this.printOption(GameOption.MAX_STICKS_PER_TURN, 'Max Sticks per Turn', this.maxSticksPerTurn)

    term.styleReset('\n\n')

    if (this.curGameOption === GameOption.SUBMIT) {
      term('   ').bgGreen('[Submit]')
    } else {
      term(' [ Submit ]')
    }

    const input = await this.getGameInput()

    switch (input) {
      case GameInput.UP: // move up in the options list
        this.curGameOption = Math.max(0, this.curGameOption - 1)
        break
      case GameInput.DOWN: // move down
        this.curGameOption = Math.min(GameOption.SUBMIT, this.curGameOption + 1)
        break
      case GameInput.MORE: // increment/decrement numeric values
      case GameInput.LESS:
        this.updateNumericOption(input)
        break
      case GameInput.BACKSPACE:
        if (this.curGameOption === GameOption.PLAYER_1_NAME) {
          this.players[0] = this.players[0].slice(0, -1)
        } else if (this.curGameOption === GameOption.PLAYER_2_NAME) {
          this.players[1] = this.players[1].slice(0, -1)
        }
        break
      case GameInput.SUBMIT: // start game!
        if (!GameOption.SUBMIT) {
          break
        }

        // player names may not have been set
        if (this.players[0].length < OPTION_BOUNDARIES.players.min || this.players[1].length < OPTION_BOUNDARIES.players.min) {
          break
        }

        this.game = new Game({
          players: this.players,
          maxTakesByTurn: this.maxSticksPerTurn,
          boardProperties: {
            stacks: this.stacksCount
          }
        })

        this.step = UIStep.IN_GAME
        break
      case GameInput.UNKNOWN: // non-allowed character, just ignore
        break
      default: // dealing with characters (player names)
        if (this.curGameOption === GameOption.PLAYER_1_NAME && this.players[0].length < OPTION_BOUNDARIES.players.max) {
          this.players[0] += input
        } else if (this.curGameOption === GameOption.PLAYER_2_NAME && this.players[1].length < OPTION_BOUNDARIES.players.max) {
          this.players[1] += input
        }
    }
  }


// print UI during game
private async gameTurn (): Promise<void> {
    this.reset()

    const { board, waitingFor: player } = this.game.getGameState()

    this.selectedStickCount = Math.min(board[this.selectedStack], this.selectedStickCount)

    term(' Select the stack with UP/DOWN and select the number of sticks to take with RIGHT/LEFT. Press ENTER to submit\n\n')

    term(' Current player: ').red(player).styleReset('\n\n')

    // drawing board, applying special styling to selected stack and sticks
    for (let i = 0; i < board.length; i++) {
      if (this.selectedStack === i) {
        term.yellow(' ' + (i + 1).toString().padStart(2, ' ')).cyan(' | ')
        term.yellow('I '.repeat(this.selectedStickCount))
        term.magenta('I '.repeat(board[i] - this.selectedStickCount))
      } else {
        term.magenta(' ' + (i + 1).toString().padStart(2, ' ')).cyan(' | ')
        term.magenta('I '.repeat(board[i]))
      }

      term('\n')
    }

    const input = await this.getGameInput()

    switch (input) {
      case GameInput.UP: // move up in stacks list
        this.selectedStack = Math.max(0, this.selectedStack - 1)
        // also update stick count
        this.selectedStickCount = Math.min(board[this.selectedStack], this.selectedStickCount)
        break
      case GameInput.DOWN: // move down
        this.selectedStack = Math.min(board.length - 1, this.selectedStack + 1)
        this.selectedStickCount = Math.min(board[this.selectedStack], this.selectedStickCount)
        break
      case GameInput.MORE: // add one to the number of selected sticks
        this.selectedStickCount = Math.min(board[this.selectedStack], this.maxSticksPerTurn, this.selectedStickCount + 1)
        break
      case GameInput.LESS: // remove one
        this.selectedStickCount = Math.max(1, this.selectedStickCount - 1)
        break
      case GameInput.SUBMIT: // confirm move
        if (!this.game.isMoveValid(this.selectedStack, this.selectedStickCount)) {
          break
        }

        const nextPlayer = this.game.play(this.selectedStack, this.selectedStickCount)

        // the game ended
        if (nextPlayer === null) {
          this.step = UIStep.GAME_SUMMARY
        }

        break
    }
  }


// prints the summary UI
private async summary (): Promise<void> {
    this.reset()

    const winner = this.game.getWinner()

    term(' Winner: ').bold.yellow(winner)
    term('\n\n Press Ctrl+C to exit or any other key to play again')

    await this.getGameInput()

    this.step = UIStep.OPTIONS
  }


// main draw routine, called at most every `this.clockSpeed` ms
private async draw (): Promise<void> {
    try {
      switch (this.step) {
        case UIStep.TITLE_SCREEN:
          await this.printTitleScreen()
          break
        case UIStep.OPTIONS:
          await this.drawOptionsScreen()
          break
        case UIStep.IN_GAME:
          await this.gameTurn()
          break
        case UIStep.GAME_SUMMARY:
          await this.summary()
          break
        default:
          throw new Error('Unknown state: ' + this.step)
      }

      setTimeout(() => this.draw(), this.clockSpeed)
    } catch (e) {
      console.error('Game failed')
      console.error(e)
    }
  }


start (): void {
    this.draw()
  }


async (request, config) => {
  const validator = new Validator(request, customParams)
  if (validator.error) throw validator.error

  const jobRunID = validator.validated.id
  const eventId = validator.validated.data.eventId
  const url = `/events/${eventId}`

  const reqConfig = {
    ...config.api,
    headers: {
      ...config.api.headers,
      'x-rapidapi-key': config.apiKey,
    },
    params: {
      include: 'scores',
    },
    url,
  }

  const response = await Requester.request(reqConfig)
  response.data.result = response.data

  return Requester.success(jobRunID, response, config.verbose)
}


() => {
  const dispatch = useDispatch();
  const [confirmClearDialogOpen, setConfirmClearDialogOpen] = useState(false);
  const ideas = useSelector(
    (state: RootState) => state.games.startStopContinue.ideas
  );

  const exportIdeas = () => {
    const fileName = "startstopcontinue.txt";
    const text = getCategories()
      .map(
        (category) =>
          `* ${category}\n` +
          ideasByCategory(ideas, category)
            .map((idea) => `    * ${idea.payload.message}\n`)
            .join("")
      )
      .join("");
    const fileToSave = new Blob([text], {
      type: "plain/text",
    });
    saveAs(fileToSave, fileName);
  };

  return (
    <>
      <ListItem>
        <Button onClick={()


(state: RootState) => state.games.startStopContinue.ideas


() => {
    const fileName = "startstopcontinue.txt";
    const text = getCategories()
      .map(
        (category) =>
          `* ${category}\n` +
          ideasByCategory(ideas, category)
            .map((idea) => `    * ${idea.payload.message}\n`)
            .join("")
      )
      .join("");
    const fileToSave = new Blob([text], {
      type: "plain/text",
    });
    saveAs(fileToSave, fileName);
  }


(category) =>
          `* ${category}\n` +
          ideasByCategory(ideas, category)
            .map((idea) => `    * ${idea.payload.message}\n`)
            .join("")


(idea) => `    * ${idea.payload.message}\n`


() => setConfirmClearDialogOpen(true)


(jsonValue) => V1QueueFromJSON(jsonValue)


(jsonValue) => V1ListQueuesResponseFromJSON(jsonValue)


export interface CreateQueueRequest {
    owner: string;
    agent: string;
    body: V1Queue;
}


export interface DeleteQueueRequest {
    owner: string;
    agent: string;
    uuid: string;
}


export interface GetQueueRequest {
    owner: string;
    agent: string;
    uuid: string;
}


export interface ListOrganizationQueueNamesRequest {
    owner: string;
    offset?: number;
    limit?: number;
    sort?: string;
    query?: string;
}


export interface ListOrganizationQueuesRequest {
    owner: string;
    offset?: number;
    limit?: number;
    sort?: string;
    query?: string;
}


export interface ListQueueNamesRequest {
    owner: string;
    agent: string;
    offset?: number;
    limit?: number;
    sort?: string;
    query?: string;
}


export interface ListQueuesRequest {
    owner: string;
    agent: string;
    offset?: number;
    limit?: number;
    sort?: string;
    query?: string;
}


export interface PatchQueueRequest {
    owner: string;
    queueAgent: string;
    queueUuid: string;
    body: V1Queue;
}


export interface UpdateQueueRequest {
    owner: string;
    queueAgent: string;
    queueUuid: string;
    body: V1Queue;
}


/**
     * Create queue
     */
async createQueueRaw(requestParameters: CreateQueueRequest): Promise<runtime.ApiResponse<V1Queue>> {
        if (requestParameters.owner === null || requestParameters.owner === undefined) {
            throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling createQueue.');
        }

        if (requestParameters.agent === null || requestParameters.agent === undefined) {
            throw new runtime.RequiredError('agent','Required parameter requestParameters.agent was null or undefined when calling createQueue.');
        }

        if (requestParameters.body === null || requestParameters.body === undefined) {
            throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createQueue.');
        }

        const queryParameters: runtime.HTTPQuery = {};

        const headerParameters: runtime.HTTPHeaders = {};

        headerParameters['Content-Type'] = 'application/json';

        if (this.configuration && this.configuration.apiKey) {
            headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
        }

        const response = await this.request({
            path: `/api/v1/orgs/{owner}/agents/{agent}/queues`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"agent"}}`, encodeURIComponent(String(requestParameters.agent))),
            method: 'POST',
            headers: headerParameters,
            query: queryParameters,
            body: V1QueueToJSON(requestParameters.body),
        });

        return new runtime.JSONApiResponse(response, (jsonValue) => V1QueueFromJSON(jsonValue));
    }


/**
     * Create queue
     */
async createQueue(requestParameters: CreateQueueRequest): Promise<V1Queue> {
        const response = await this.createQueueRaw(requestParameters);
        return await response.value();
    }


/**
     * Delete queue
     */
async deleteQueueRaw(requestParameters: DeleteQueueRequest): Promise<runtime.ApiResponse<void>> {
        if (requestParameters.owner === null || requestParameters.owner === undefined) {
            throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling deleteQueue.');
        }

        if (requestParameters.agent === null || requestParameters.agent === undefined) {
            throw new runtime.RequiredError('agent','Required parameter requestParameters.agent was null or undefined when calling deleteQueue.');
        }

        if (requestParameters.uuid === null || requestParameters.uuid === undefined) {
            throw new runtime.RequiredError('uuid','Required parameter requestParameters.uuid was null or undefined when calling deleteQueue.');
        }

        const queryParameters: runtime.HTTPQuery = {};

        const headerParameters: runtime.HTTPHeaders = {};

        if (this.configuration && this.configuration.apiKey) {
            headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
        }

        const response = await this.request({
            path: `/api/v1/orgs/{owner}/agents/{agent}/queues/{uuid}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"agent"}}`, encodeURIComponent(String(requestParameters.agent))).replace(`{${"uuid"}}`, encodeURIComponent(String(requestParameters.uuid))),
            method: 'DELETE',
            headers: headerParameters,
            query: queryParameters,
        });

        return new runtime.VoidApiResponse(response);
    }


/**
     * Delete queue
     */
async deleteQueue(requestParameters: DeleteQueueRequest): Promise<void> {
        await this.deleteQueueRaw(requestParameters);
    }


/**
     * Get queue
     */
async getQueueRaw(requestParameters: GetQueueRequest): Promise<runtime.ApiResponse<V1Queue>> {
        if (requestParameters.owner === null || requestParameters.owner === undefined) {
            throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling getQueue.');
        }

        if (requestParameters.agent === null || requestParameters.agent === undefined) {
            throw new runtime.RequiredError('agent','Required parameter requestParameters.agent was null or undefined when calling getQueue.');
        }

        if (requestParameters.uuid === null || requestParameters.uuid === undefined) {
            throw new runtime.RequiredError('uuid','Required parameter requestParameters.uuid was null or undefined when calling getQueue.');
        }

        const queryParameters: runtime.HTTPQuery = {};

        const headerParameters: runtime.HTTPHeaders = {};

        if (this.configuration && this.configuration.apiKey) {
            headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
        }

        const response = await this.request({
            path: `/api/v1/orgs/{owner}/agents/{agent}/queues/{uuid}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"agent"}}`, encodeURIComponent(String(requestParameters.agent))).replace(`{${"uuid"}}`, encodeURIComponent(String(requestParameters.uuid))),
            method: 'GET',
            headers: headerParameters,
            query: queryParameters,
        });

        return new runtime.JSONApiResponse(response, (jsonValue) => V1QueueFromJSON(jsonValue));
    }


/**
     * Get queue
     */
async getQueue(requestParameters: GetQueueRequest): Promise<V1Queue> {
        const response = await this.getQueueRaw(requestParameters);
        return await response.value();
    }


/**
     * List organization level queues names
     */
async listOrganizationQueueNamesRaw(requestParameters: ListOrganizationQueueNamesRequest): Promise<runtime.ApiResponse<V1ListQueuesResponse>> {
        if (requestParameters.owner === null || requestParameters.owner === undefined) {
            throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling listOrganizationQueueNames.');
        }

        const queryParameters: runtime.HTTPQuery = {};

        if (requestParameters.offset !== undefined) {
            queryParameters['offset'] = requestParameters.offset;
        }

        if (requestParameters.limit !== undefined) {
            queryParameters['limit'] = requestParameters.limit;
        }

        if (requestParameters.sort !== undefined) {
            queryParameters['sort'] = requestParameters.sort;
        }

        if (requestParameters.query !== undefined) {
            queryParameters['query'] = requestParameters.query;
        }

        const headerParameters: runtime.HTTPHeaders = {};

        if (this.configuration && this.configuration.apiKey) {
            headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
        }

        const response = await this.request({
            path: `/api/v1/orgs/{owner}/queues/names`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))),
            method: 'GET',
            headers: headerParameters,
            query: queryParameters,
        });

        return new runtime.JSONApiResponse(response, (jsonValue) => V1ListQueuesResponseFromJSON(jsonValue));
    }


/**
     * List organization level queues names
     */
async listOrganizationQueueNames(requestParameters: ListOrganizationQueueNamesRequest): Promise<V1ListQueuesResponse> {
        const response = await this.listOrganizationQueueNamesRaw(requestParameters);
        return await response.value();
    }


/**
     * List organization level queues
     */
async listOrganizationQueuesRaw(requestParameters: ListOrganizationQueuesRequest): Promise<runtime.ApiResponse<V1ListQueuesResponse>> {
        if (requestParameters.owner === null || requestParameters.owner === undefined) {
            throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling listOrganizationQueues.');
        }

        const queryParameters: runtime.HTTPQuery = {};

        if (requestParameters.offset !== undefined) {
            queryParameters['offset'] = requestParameters.offset;
        }

        if (requestParameters.limit !== undefined) {
            queryParameters['limit'] = requestParameters.limit;
        }

        if (requestParameters.sort !== undefined) {
            queryParameters['sort'] = requestParameters.sort;
        }

        if (requestParameters.query !== undefined) {
            queryParameters['query'] = requestParameters.query;
        }

        const headerParameters: runtime.HTTPHeaders = {};

        if (this.configuration && this.configuration.apiKey) {
            headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
        }

        const response = await this.request({
            path: `/api/v1/orgs/{owner}/queues`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))),
            method: 'GET',
            headers: headerParameters,
            query: queryParameters,
        });

        return new runtime.JSONApiResponse(response, (jsonValue) => V1ListQueuesResponseFromJSON(jsonValue));
    }


/**
     * List organization level queues
     */
async listOrganizationQueues(requestParameters: ListOrganizationQueuesRequest): Promise<V1ListQueuesResponse> {
        const response = await this.listOrganizationQueuesRaw(requestParameters);
        return await response.value();
    }


/**
     * List queues names
     */
async listQueueNamesRaw(requestParameters: ListQueueNamesRequest): Promise<runtime.ApiResponse<V1ListQueuesResponse>> {
        if (requestParameters.owner === null || requestParameters.owner === undefined) {
            throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling listQueueNames.');
        }

        if (requestParameters.agent === null || requestParameters.agent === undefined) {
            throw new runtime.RequiredError('agent','Required parameter requestParameters.agent was null or undefined when calling listQueueNames.');
        }

        const queryParameters: runtime.HTTPQuery = {};

        if (requestParameters.offset !== undefined) {
            queryParameters['offset'] = requestParameters.offset;
        }

        if (requestParameters.limit !== undefined) {
            queryParameters['limit'] = requestParameters.limit;
        }

        if (requestParameters.sort !== undefined) {
            queryParameters['sort'] = requestParameters.sort;
        }

        if (requestParameters.query !== undefined) {
            queryParameters['query'] = requestParameters.query;
        }

        const headerParameters: runtime.HTTPHeaders = {};

        if (this.configuration && this.configuration.apiKey) {
            headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
        }

        const response = await this.request({
            path: `/api/v1/orgs/{owner}/agents/{agent}/queues/names`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"agent"}}`, encodeURIComponent(String(requestParameters.agent))),
            method: 'GET',
            headers: headerParameters,
            query: queryParameters,
        });

        return new runtime.JSONApiResponse(response, (jsonValue) => V1ListQueuesResponseFromJSON(jsonValue));
    }


/**
     * List queues names
     */
async listQueueNames(requestParameters: ListQueueNamesRequest): Promise<V1ListQueuesResponse> {
        const response = await this.listQueueNamesRaw(requestParameters);
        return await response.value();
    }


/**
     * List queues
     */
async listQueuesRaw(requestParameters: ListQueuesRequest): Promise<runtime.ApiResponse<V1ListQueuesResponse>> {
        if (requestParameters.owner === null || requestParameters.owner === undefined) {
            throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling listQueues.');
        }

        if (requestParameters.agent === null || requestParameters.agent === undefined) {
            throw new runtime.RequiredError('agent','Required parameter requestParameters.agent was null or undefined when calling listQueues.');
        }

        const queryParameters: runtime.HTTPQuery = {};

        if (requestParameters.offset !== undefined) {
            queryParameters['offset'] = requestParameters.offset;
        }

        if (requestParameters.limit !== undefined) {
            queryParameters['limit'] = requestParameters.limit;
        }

        if (requestParameters.sort !== undefined) {
            queryParameters['sort'] = requestParameters.sort;
        }

        if (requestParameters.query !== undefined) {
            queryParameters['query'] = requestParameters.query;
        }

        const headerParameters: runtime.HTTPHeaders = {};

        if (this.configuration && this.configuration.apiKey) {
            headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
        }

        const response = await this.request({
            path: `/api/v1/orgs/{owner}/agents/{agent}/queues`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"agent"}}`, encodeURIComponent(String(requestParameters.agent))),
            method: 'GET',
            headers: headerParameters,
            query: queryParameters,
        });

        return new runtime.JSONApiResponse(response, (jsonValue) => V1ListQueuesResponseFromJSON(jsonValue));
    }


/**
     * List queues
     */
async listQueues(requestParameters: ListQueuesRequest): Promise<V1ListQueuesResponse> {
        const response = await this.listQueuesRaw(requestParameters);
        return await response.value();
    }


/**
     * Patch queue
     */
async patchQueueRaw(requestParameters: PatchQueueRequest): Promise<runtime.ApiResponse<V1Queue>> {
        if (requestParameters.owner === null || requestParameters.owner === undefined) {
            throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling patchQueue.');
        }

        if (requestParameters.queueAgent === null || requestParameters.queueAgent === undefined) {
            throw new runtime.RequiredError('queueAgent','Required parameter requestParameters.queueAgent was null or undefined when calling patchQueue.');
        }

        if (requestParameters.queueUuid === null || requestParameters.queueUuid === undefined) {
            throw new runtime.RequiredError('queueUuid','Required parameter requestParameters.queueUuid was null or undefined when calling patchQueue.');
        }

        if (requestParameters.body === null || requestParameters.body === undefined) {
            throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling patchQueue.');
        }

        const queryParameters: runtime.HTTPQuery = {};

        const headerParameters: runtime.HTTPHeaders = {};

        headerParameters['Content-Type'] = 'application/json';

        if (this.configuration && this.configuration.apiKey) {
            headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
        }

        const response = await this.request({
            path: `/api/v1/orgs/{owner}/agents/{queue.agent}/queues/{queue.uuid}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"queue.agent"}}`, encodeURIComponent(String(requestParameters.queueAgent))).replace(`{${"queue.uuid"}}`, encodeURIComponent(String(requestParameters.queueUuid))),
            method: 'PATCH',
            headers: headerParameters,
            query: queryParameters,
            body: V1QueueToJSON(requestParameters.body),
        });

        return new runtime.JSONApiResponse(response, (jsonValue) => V1QueueFromJSON(jsonValue));
    }


/**
     * Patch queue
     */
async patchQueue(requestParameters: PatchQueueRequest): Promise<V1Queue> {
        const response = await this.patchQueueRaw(requestParameters);
        return await response.value();
    }


/**
     * Update queue
     */
async updateQueueRaw(requestParameters: UpdateQueueRequest): Promise<runtime.ApiResponse<V1Queue>> {
        if (requestParameters.owner === null || requestParameters.owner === undefined) {
            throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling updateQueue.');
        }

        if (requestParameters.queueAgent === null || requestParameters.queueAgent === undefined) {
            throw new runtime.RequiredError('queueAgent','Required parameter requestParameters.queueAgent was null or undefined when calling updateQueue.');
        }

        if (requestParameters.queueUuid === null || requestParameters.queueUuid === undefined) {
            throw new runtime.RequiredError('queueUuid','Required parameter requestParameters.queueUuid was null or undefined when calling updateQueue.');
        }

        if (requestParameters.body === null || requestParameters.body === undefined) {
            throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateQueue.');
        }

        const queryParameters: runtime.HTTPQuery = {};

        const headerParameters: runtime.HTTPHeaders = {};

        headerParameters['Content-Type'] = 'application/json';

        if (this.configuration && this.configuration.apiKey) {
            headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
        }

        const response = await this.request({
            path: `/api/v1/orgs/{owner}/agents/{queue.agent}/queues/{queue.uuid}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"queue.agent"}}`, encodeURIComponent(String(requestParameters.queueAgent))).replace(`{${"queue.uuid"}}`, encodeURIComponent(String(requestParameters.queueUuid))),
            method: 'PUT',
            headers: headerParameters,
            query: queryParameters,
            body: V1QueueToJSON(requestParameters.body),
        });

        return new runtime.JSONApiResponse(response, (jsonValue) => V1QueueFromJSON(jsonValue));
    }


/**
     * Update queue
     */
async updateQueue(requestParameters: UpdateQueueRequest): Promise<V1Queue> {
        const response = await this.updateQueueRaw(requestParameters);
        return await response.value();
    }


async function testPromisify() {
    const rd = util.promisify(fs.readdir);
    let listS: string[];
    listS = await rd('path');
    listS = await rd('path', 'utf8');
    listS = await rd('path', null);
    listS = await rd('path', undefined);
    listS = await rd('path', { encoding: 'utf8' });
    listS = await rd('path', { encoding: null });
    listS = await rd('path', { encoding: null, withFileTypes: false });
    listS = await rd('path', { encoding: 'utf8', withFileTypes: false });
    const listDir: fs.Dirent[] = await rd('path', { withFileTypes: true });
    const listDir2: Buffer[] = await rd('path', { withFileTypes: false, encoding: 'buffer' });
    const listDir3: fs.Dirent[] = await rd('path', { encoding: 'utf8', withFileTypes: true });

    const ln = util.promisify(fs.link);
    // $ExpectType Promise<void>
    ln("abc", "def");
}


(err, data) => content = data


(err, data) => stringOrBuffer = data


(err, data) => buffer = data


(err: NodeJS.ErrnoException | null, bytesRead: number, buffer: DataView) => { }


(err, data) => {
        if (err && err.errno) {
            errno = err.errno;
        }
    }


(err: NodeJS.ErrnoException | null, files: fs.Dirent[]) => { }


(err, folder) => {
        console.log(folder);
        // Prints: /tmp/foo-itXde2
    }


(event, filename) => {
        console.log(event, filename);
    }


(current, previous) => {
        console.log(current, previous);
    }


(err) => { }


(error?: Error | null) => { }


(err, linkString) => s = linkString


(err, linkString) => b = linkString


(err, resolvedPath) => s = resolvedPath


(err, resolvedPath) => b = resolvedPath


(err) => console.error(err)


(err, path) => {
        err; // $ExpectType ErrnoException | null
        path; // $ExpectType string | undefined
    }


(err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => {
    }


async () => {
    try {
        await fs.promises.rmdir('some/test/path');
        await fs.promises.rmdir('some/test/path', { maxRetries: 123, retryDelay: 123, recursive: true });
    } catch (e) { }

    try {
        await fs.promises.rmdir('some/test/file');
        await fs.promises.rmdir('some/test/file', { maxRetries: 123, retryDelay: 123 });
    } catch (e) { }
}


async (err, dir) => {
        const dirEnt: fs.Dirent | null = await dir.read();
    }


async () => {
        // tslint:disable-next-line: await-promise
        for await (const thing of dir) {
        }
        // tslint:disable-next-line: await-promise
        for await (const thing of dirBuffer) {
        }
        // tslint:disable-next-line: await-promise
        for await (const thing of dirUrl) {
        }
    }


async () => {
    const handle: FileHandle = await openAsync('test', 'r');
    const writeStream = fs.createWriteStream('./index.d.ts', {
        fd: handle,
    });
    const _wom = writeStream.writableObjectMode; // $ExpectType boolean

    const readStream = fs.createReadStream('./index.d.ts', {
        fd: handle,
    });
    const _rom = readStream.readableObjectMode; // $ExpectType boolean

    (await handle.read()).buffer; // $ExpectType Buffer
    (await handle.read({
        buffer: new Uint32Array(),
        offset: 1,
        position: 2,
        length: 3,
    })).buffer; // $ExpectType Uint32Array

    await handle.write('hurr', 0, 'utf-8');
    await handle.write(Buffer.from('hurr'), 0, 42, 10);
}


async () => {
    await writeFileAsync('test', 'test');
    await writeFileAsync('test',  Buffer.from('test'));
    await writeFileAsync('test',  ['test', 'test2']);
    await writeFileAsync('test',  async function *() { yield 'yeet'; }());
    await writeFileAsync('test', process.stdin);
}


(err?: NodeJS.ErrnoException | null) => {}


(err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => {
    }


(err, st: fs.Stats) => { }


(err, st: fs.BigIntStats) => { }


(err, st) => {
        st; // $ExpectType Stats | BigIntStats
    }


(err: Error | null) => {}


(fd) => {
        // Create a stream from some character device.
        const stream = fd.createReadStream(); // $ExpectType ReadStream
        stream.close();
        stream.push(null);
        stream.read(0);
    }


(fd) => {
        // Create a stream from some character device.
        const stream = fd.createWriteStream(); // $ExpectType WriteStream
        stream.close();
    }


filter(src, dst) {
            return src !== 'node_modules' && dst !== 'something';
        }


async (id : number) => {
  const patient = await Patient.db
    .select(selectList)
    .where('patients.id', id)
    .join('users', 'users.id', '=', 'patients.userId');

  if (!patient || !patient[0]) { throw new AppError('Patient with the given id is not found', status.NOT_FOUND); }

  return patient[0];
}


async (limit : number, offset : number, searchProps: PatientSearchProps) => {
  const query = Patient.db
    .select(selectList)
    .join('users', 'users.id', '=', 'patients.userId');

  // handle name search
  if (searchProps.name) {
    query.where('name', 'like', `${searchProps.name}%`);
  }

  // handle area search
  if (searchProps.area) {
    query
      .join('patient_areas', 'patient_areas.patientId', '=', 'patients.id')
      .where('patient_areas.areaId', '=', searchProps.area);
  }

  // handle insurance search
  if (searchProps.insurance) {
    query
      .join('patient_insurances', 'patient_insurances.patientId', '=', 'patients.id')
      .where('patient_insurances.insuranceId', '=', searchProps.insurance);
  }

  // handle specialization search
  if (searchProps.specialization) {
    query
      .join('patient_specializations', 'patient_specializations.patientId', '=', 'patients.id')
      .where('patient_specializations.specializationId', '=', searchProps.specialization);
  }

  const [patients, total] : any = await Promise.all([
    query.offset(offset).limit(limit),
    Patient.db.count(),
  ]);

  return { patients, total: parseInt(total[0].count, 10) };
}


async (userId : number) : Promise<PatientInterface> => {
  const patient = await Patient.db
    .select(selectList)
    .where('patients.userId', userId)
    .join('users', 'users.id', '=', 'patients.userId');

  if (!patient || !patient[0]) { throw new AppError('Patient with the given id is not found', status.NOT_FOUND); }

  return patient[0];
}


interface PatientSearchProps {
  name?: string;
  area?: number;
  insurance?: number;
  specialization?: number;
}


/**
 * Form Context
 * Set top form style and pass to Form Item usage.
 */
export interface FormContextProps extends Callbacks {
    name?: string;
    vertical?: boolean;
    preserve?: boolean;
    form?: FormInstance;
}


/**
 * @author bbrown@google.com (Brian Brown)
 */
export default class BitMatrixParser {
    private mappingBitMatrix;
    private readMappingMatrix;
    private version;
    /**
     * @param bitMatrix {@link BitMatrix} to parse
     * @throws FormatException if dimension is < 8 or > 144 or not 0 mod 2
     */
    constructor(bitMatrix: BitMatrix);
    getVersion(): Version;
    /**
     *
Creates the version object based on the dimension of the original bit matrix from
     * the datamatrix code.

     *
     *
See ISO 16022:2006 Table 7 - ECC 200 symbol attributes

     *
     * @param bitMatrix Original {@link BitMatrix} including alignment patterns
     * @return {@link Version} encapsulating the Data Matrix Code's "version"
     * @throws FormatException if the dimensions of the mapping matrix are not valid
     * Data Matrix dimensions.
     */
    static readVersion(bitMatrix: BitMatrix): Version;
    /**
     *
Reads the bits in the {@link BitMatrix} representing the mapping matrix (No alignment patterns)
     * in the correct order in order to reconstitute the codewords bytes contained within the
     * Data Matrix Code.

     *
     * @return bytes encoded within the Data Matrix Code
     * @throws FormatException if the exact number of bytes expected is not read
     */
    readCodewords(): Int8Array;
    /**
     *
Reads a bit of the mapping matrix accounting for boundary wrapping.

     *
     * @param row Row to read in the mapping matrix
     * @param column Column to read in the mapping matrix
     * @param numRows Number of rows in the mapping matrix
     * @param numColumns Number of columns in the mapping matrix
     * @return value of the given bit in the mapping matrix
     */
    private readModule;
    /**
     *
Reads the 8 bits of the standard Utah-shaped pattern.

     *
     *
See ISO 16022:2006, 5.8.1 Figure 6

     *
     * @param row Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern
     * @param column Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern
     * @param numRows Number of rows in the mapping matrix
     * @param numColumns Number of columns in the mapping matrix
     * @return byte from the utah shape
     */
    private readUtah;
    /**
     *
Reads the 8 bits of the special corner condition 1.

     *
     *
See ISO 16022:2006, Figure F.3

     *
     * @param numRows Number of rows in the mapping matrix
     * @param numColumns Number of columns in the mapping matrix
     * @return byte from the Corner condition 1
     */
    private readCorner1;
    /**
     *
Reads the 8 bits of the special corner condition 2.

     *
     *
See ISO 16022:2006, Figure F.4

     *
     * @param numRows Number of rows in the mapping matrix
     * @param numColumns Number of columns in the mapping matrix
     * @return byte from the Corner condition 2
     */
    private readCorner2;
    /**
     *
Reads the 8 bits of the special corner condition 3.

     *
     *
See ISO 16022:2006, Figure F.5

     *
     * @param numRows Number of rows in the mapping matrix
     * @param numColumns Number of columns in the mapping matrix
     * @return byte from the Corner condition 3
     */
    private readCorner3;
    /**
     *
Reads the 8 bits of the special corner condition 4.

     *
     *
See ISO 16022:2006, Figure F.6

     *
     * @param numRows Number of rows in the mapping matrix
     * @param numColumns Number of columns in the mapping matrix
     * @return byte from the Corner condition 4
     */
    private readCorner4;
    /**
     *
Extracts the data region from a {@link BitMatrix} that contains
     * alignment patterns.

     *
     * @param bitMatrix Original {@link BitMatrix} with alignment patterns
     * @return BitMatrix that has the alignment patterns removed
     */
    private extractDataRegion;
}


getVersion(): Version;


/**
     *
Creates the version object based on the dimension of the original bit matrix from
     * the datamatrix code.

     *
     *
See ISO 16022:2006 Table 7 - ECC 200 symbol attributes

     *
     * @param bitMatrix Original {@link BitMatrix} including alignment patterns
     * @return {@link Version} encapsulating the Data Matrix Code's "version"
     * @throws FormatException if the dimensions of the mapping matrix are not valid
     * Data Matrix dimensions.
     */
static readVersion(bitMatrix: BitMatrix): Version;


/**
     *
Reads the bits in the {@link BitMatrix} representing the mapping matrix (No alignment patterns)
     * in the correct order in order to reconstitute the codewords bytes contained within the
     * Data Matrix Code.

     *
     * @return bytes encoded within the Data Matrix Code
     * @throws FormatException if the exact number of bytes expected is not read
     */
readCodewords(): Int8Array;


/**
 * Get artifacts for single project build
 *
 * @see https://circleci.com/docs/api/v1-reference/#build-artifacts
 * @example /project/:vcs-type/:username/:project/:build_num/artifacts
 *
 * @param token - CircleCI API token
 * @param vcs - Project's git information
 * @param buildNumber - Target build number
 * @returns Promise of an array of build artifacs
 */
export function getBuildArtifacts(
  token: string,
  vcs: GitInfo,
  buildNumber: number
): Promise<ArtifactResponse> {
  const url = `${createVcsUrl(vcs)}/${buildNumber}/artifacts`;
  return client(token).get<ArtifactResponse>(url);
}


/**
 * Get the latest build artifacts for a project
 *
 * @example branch - The branch you would like to look in for the latest build. Returns artifacts for latest build in entire project if omitted.
 * @example filter - Restricts which builds are returned. Set to "completed", "successful", "failed", "running"
 *
 * @see https://circleci.com/docs/api/v1-reference/#build-artifacts-latest
 * @example GET - /project/:vcs-type/:username/:project/latest/artifacts?branch=:branch&filter=:filter
 * @param token - CircleCI API token
 * @param vcs - Project's git information
 * @param options - Query parameters
 */
export function getLatestArtifacts(
  token: string,
  { vcs, options = {} }: GitRequiredRequest
): Promise<ArtifactResponse> {
  const { branch, filter } = options;
  const url = `${createVcsUrl(vcs)}/latest/artifacts${queryParams({
    branch,
    filter
  })}`;
  return client(token).get<ArtifactResponse>(url);
}


(subjectName: string): string | undefined =>
  subjectName.match(/CN=(.+?)(?:,|$)/)?.[1]


async ({
  callES,
  dynamicSettings,
}) => {
  const callAsCurrentUser: APICaller = async (
    endpoint: string,
    clientParams: Record<string, any> = {},
    options?: CallAPIOptions
  ) => callES(endpoint, clientParams, options);
  const indexPatternsFetcher = new IndexPatternsFetcher(callAsCurrentUser);

  // Since `getDynamicIndexPattern` is called in setup_request (and thus by every endpoint)
  // and since `getFieldsForWildcard` will throw if the specified indices don't exist,
  // we have to catch errors here to avoid all endpoints returning 500 for users without APM data
  // (would be a bad first time experience)
  try {
    const fields = await indexPatternsFetcher.getFieldsForWildcard({
      pattern: dynamicSettings.heartbeatIndices,
    });

    const indexPattern: IIndexPattern = {
      fields,
      title: dynamicSettings.heartbeatIndices,
    };

    return indexPattern;
  } catch (e) {
    const notExists = e.output?.statusCode === 404;
    if (notExists) {
      // eslint-disable-next-line no-console
      console.error(
        `Could not get dynamic index pattern because indices "${dynamicSettings.heartbeatIndices}" don't exist`
      );
      return;
    }

    // re-throw
    throw e;
  }
}


async (
    endpoint: string,
    clientParams: Record<string, any> = {},
    options?: CallAPIOptions
  ) => callES(endpoint, clientParams, options)


export class ItemProperty {
    constructor(
        public id: string,
        public name: Text[] = [],
        // value bir dil icin birden fazla deger olabilir. Yani su sekilde olacak (ornegin name = [ color , renk ]):
        // value = [ tr:kirmizi, tr:mavi, en:red, en: blue ]
        public value: Text[] = [],
        public valueDecimal: number[],
        public valueQuantity: Quantity[],
        public valueBinary: BinaryObject[],
        public valueQualifier: PropertyValueQualifier,
        public itemClassificationCode: Code,
        public uri: string,
        public associatedCatalogueLineID: number[], // hjids of catalogue lines
        public required:boolean = false, // whether this property is required or not (does not exist in the backend data model and used only in the UI)
        public options:Text[] = [] // available options to be selected as a value for the item property (does not exist in the backend data model and used only in the UI)
    ) { }
}


async (req: NextApiRequest, res: NextApiResponse) => {
    const credential = await useCredential()
    if (
        credential.accessToken == null ||
        credential.refreshToken == null ||
        credential.accessToken.length <= 0 ||
        credential.refreshToken.length <= 0
    ) return res.status(401)

    const fitbit = useFitbit()

    fetch(credential, fitbit).then((activity) => {
        res.json(JSON.stringify(activity))
    })
}


(activity) => {
        res.json(JSON.stringify(activity))
    }


async function addStatusLogEntry(): Promise<void> {
  await connect();
  await Status.logStatus();
  await disconnect();
}


(søknad: ISøknad) => {
    const fraOmDeg = [
        søknad.søker.oppholdsland.svar,
        søknad.søker.arbeidsland.svar,
        søknad.søker.pensjonsland.svar,
    ];
    const fraOmBarnet = søknad.barnInkludertISøknaden.flatMap((barn: IBarnMedISøknad) => [
        barn.oppholdsland.svar,
        barn.barnetrygdFraEøslandHvilketLand.svar,
        barn.andreForelderArbeidUtlandetHvilketLand.svar,
        barn.andreForelderPensjonHvilketLand.svar,
    ]);
    return fraOmDeg.concat(fraOmBarnet);
}


(barn: IBarnMedISøknad) => [
        barn.oppholdsland.svar,
        barn.barnetrygdFraEøslandHvilketLand.svar,
        barn.andreForelderArbeidUtlandetHvilketLand.svar,
        barn.andreForelderPensjonHvilketLand.svar,
    ]


(søknad: ISøknad) =>
    søknad.mottarBarnetrygdForBarnFraAnnetEøsland.svar === ESvar.JA


async function loadArtistsByGroupIds(ids: GroupId[]) {
  const rows = await ArtistModel.find({ groupId: { $in: ids } });

  return ids.map((id) => (
    rows.filter((x) => (
      x.groupId.toString() === id.toString()
    ))
  ));
}


async function loadArtistByIds(ids: ArtistId[]) {
  const rows = await ArtistModel.find({ _id: { $in: ids } });

  return ids.map((id) => (
    rows.filter((x) => (
      x._id.toString() === id.toString()
    ))
  ));
}


(id) => (
    rows.filter((x) => (
      x.groupId.toString() === id.toString()
    ))
  )


(x) => (
      x.groupId.toString() === id.toString()
    )


(id) => (
    rows.filter((x) => (
      x._id.toString() === id.toString()
    ))
  )


(x) => (
      x._id.toString() === id.toString()
    )


export function install(registers: EChartsExtensionInstallRegisters) {
    registers.registerChartView(PieView);
    registers.registerSeriesModel(PieSeriesModel);

    createLegacyDataSelectAction('pie', registers.registerAction);

    registers.registerLayout(curry(pieLayout, 'pie'));
    registers.registerProcessor(dataFilter('pie'));
}


({ resource }) => (
  <ActivityProgress title={`Demo activity for node ${getName(resource)}`


() => (
  <ActivityItem>Demo


getName(resource)


getNamespace(resource)


(props: IIblisReactNativeUndrawProps & SvgProps) => (
  <Svg data-name="Layer 1"


export type Contact = {
  id: string;
  online?: boolean;
  trueName: string;
  customName?: string;
  isUntrustworthy?: boolean;
  blocked?: boolean;
  isFriend?: boolean;
};


export type Contacts = {
  [id: string]: Contact;
};


// TODO: Make this return an array of DependencyManagers when we add runtimes with multiple dependency managers
export function getDependencyManager(runtime: Runtime): DependencyManager {
    if (nodeJsRuntimes.has(runtime)) {
        return 'npm'
    } else if (pythonRuntimes.has(runtime)) {
        return 'pip'
    } else if (dotNetRuntimes.has(runtime)) {
        return 'cli-package'
    }
    throw new Error(`Runtime ${runtime} does not have an associated DependencyManager`)
}


export function getFamily(runtime: string): RuntimeFamily {
    if (nodeJsRuntimes.has(runtime)) {
        return RuntimeFamily.NodeJS
    } else if (pythonRuntimes.has(runtime)) {
        return RuntimeFamily.Python
    } else if (dotNetRuntimes.has(runtime)) {
        return RuntimeFamily.DotNetCore
    }
    return RuntimeFamily.Unknown
}


function getSortableCompareText(runtime: Runtime): string {
    return runtimeCompareText.get(runtime) || runtime.toString()
}


/**
 * Sorts runtimes from lowest value to greatest value, helpful for outputting alphabetized lists of runtimes
 * Differs from normal sorting as it numbers into account: e.g. nodeJs8.10 < nodeJs10.x
 */
export function compareSamLambdaRuntime(a: Runtime, b: Runtime): number {
    return getSortableCompareText(a).localeCompare(getSortableCompareText(b))
}


/**
 * Maps vscode document languageId to `RuntimeFamily`.
 */
export function getRuntimeFamily(langId: string): RuntimeFamily {
    switch (langId) {
        case 'typescript':
        case 'javascript':
            return RuntimeFamily.NodeJS
        case 'csharp':
            return RuntimeFamily.DotNetCore
        case 'python':
            return RuntimeFamily.Python
        default:
            return RuntimeFamily.Unknown
    }
}