function jsonRpcResult(resultDescription: any) {
  const jsonRpcVersion = struct.literal('2.0');
  return struct.union([
    struct({
      jsonrpc: jsonRpcVersion,
      id: 'string',
      error: 'any',
    }),
    struct({
      jsonrpc: jsonRpcVersion,
      id: 'string',
      error: 'null?',
      result: resultDescription,
    }),
  ]);
}


function jsonRpcResultAndContext(resultDescription: any) {
  return jsonRpcResult({
    context: struct({
      slot: 'number',
    }),
    value: resultDescription,
  });
}


export async function getMultipleSolanaAccounts(
  connection: Connection,
  publicKeys: PublicKey[],
): Promise<
  RpcResponseAndContext<{ [key: string]: AccountInfo<Buffer> | null }>
> {
  const args = [publicKeys.map((k) => k.toBase58()), { commitment: 'recent' }];
  // @ts-ignore
  const unsafeRes = await connection._rpcRequest('getMultipleAccounts', args);
  const res = GetMultipleAccountsAndContextRpcResult(unsafeRes);
  if (res.error) {
    throw new Error(
      'failed to get info about accounts ' +
        publicKeys.map((k) => k.toBase58()).join(', ') +
        ': ' +
        res.error.message,
    );
  }
  assert(typeof res.result !== 'undefined');
  const accounts: Array<{
    executable: any;
    owner: PublicKey;
    lamports: any;
    data: Buffer;
  } | null> = [];
  for (const account of res.result.value) {
    let value: {
      executable: any;
      owner: PublicKey;
      lamports: any;
      data: Buffer;
    } | null = null;
    if (res.result.value) {
      const { executable, owner, lamports, data } = account;
      assert(data[1] === 'base64');
      value = {
        executable,
        owner: new PublicKey(owner),
        lamports,
        data: Buffer.from(data[0], 'base64'),
      };
    }
    accounts.push(value);
  }
  return {
    context: {
      slot: res.result.context.slot,
    },
    value: Object.fromEntries(
      accounts.map((account, i) => [publicKeys[i].toBase58(), account]),
    ),
  };
}


/** Copy of Connection.simulateTransaction that takes a commitment parameter. */
async function simulateTransaction(
  connection: Connection,
  transaction: Transaction,
  commitment: Commitment,
): Promise<RpcResponseAndContext<SimulatedTransactionResponse>> {
  // @ts-ignore
  transaction.recentBlockhash = await connection._recentBlockhash(
    // @ts-ignore
    connection._disableBlockhashCaching,
  );

  const signData = transaction.serializeMessage();
  // @ts-ignore
  const wireTransaction = transaction._serialize(signData);
  const encodedTransaction = wireTransaction.toString('base64');
  const config: any = { encoding: 'base64', commitment };
  const args = [encodedTransaction, config];

  // @ts-ignore
  const res = await connection._rpcRequest('simulateTransaction', args);
  if (res.error) {
    throw new Error('failed to simulate transaction: ' + res.error.message);
  }
  return res.result;
}


({ name }) => name === 'USDT'


({ name }) => name === 'USDC'


(cumulative, m) => {
      // @ts-ignore
      cumulative.push(m._programId);
      return cumulative;
    }


(programId) => {
      if (!programIds.find((p) => p.equals(programId))) {
        programIds.push(programId);
      }
    }


(p) => p.equals(programId)


async (programId) => {
    const openOrdersAccounts = await OpenOrders.findForOwner(
      connection,
      wallet.publicKey,
      programId,
    );
    return openOrdersAccounts.filter(
      (openOrders) =>
        openOrders.baseTokenFree.toNumber() ||
        openOrders.quoteTokenFree.toNumber(),
    );
  }


(openOrders) =>
        openOrders.baseTokenFree.toNumber() ||
        openOrders.quoteTokenFree.toNumber()


(programId) => getOpenOrdersAccountsForProgramId(programId)


(accounts, current) => accounts.concat(current)


(openOrdersAccount) => {
        const market = markets.find((m) =>
          // @ts-ignore
          m._decoded?.ownAddress?.equals(openOrdersAccount.market),
        );
        if (
          openOrdersAccount.baseTokenFree.isZero() &&
          openOrdersAccount.quoteTokenFree.isZero()
        ) {
          // nothing to settle for this market.
          return null;
        }
        const baseMint = market?.baseMintAddress;
        const quoteMint = market?.quoteMintAddress;

        const selectedBaseTokenAccount = getSelectedTokenAccountForMint(
          tokenAccounts,
          baseMint,
          baseMint &&
            selectedTokenAccounts &&
            selectedTokenAccounts[baseMint.toBase58()],
        )?.pubkey;
        const selectedQuoteTokenAccount = getSelectedTokenAccountForMint(
          tokenAccounts,
          quoteMint,
          quoteMint &&
            selectedTokenAccounts &&
            selectedTokenAccounts[quoteMint.toBase58()],
        )?.pubkey;
        if (!selectedBaseTokenAccount || !selectedQuoteTokenAccount) {
          return null;
        }
        return (
          market &&
          market.makeSettleFundsTransaction(
            connection,
            openOrdersAccount,
            selectedBaseTokenAccount,
            selectedQuoteTokenAccount,
          )
        );
      }


(m) =>
          // @ts-ignore
          m._decoded?.ownAddress?.equals(openOrdersAccount.market)


(
      x,
    ): x is {
      signers: Account[];
      transaction: Transaction;
      payer: PublicKey;
    } => !!x


(t) => t.transaction


(cumulative: Array<Account>, t) => cumulative.concat(t.signers)


(signer) => {
      if (!signers.find((s) => s.publicKey.equals(signer.publicKey))) {
        signers.push(signer);
      }
    }


(s) => s.publicKey.equals(signer.publicKey)


(order) => {
    transaction.add(
      market.makeCancelOrderInstruction(connection, wallet.publicKey, order),
    );
  }


(num, step) =>
    Math.abs((num / step) % 1) < 1e-5 ||
    Math.abs(((num / step) % 1) - 1) < 1e-5


() => {
  return new Date().getTime() / 1000;
}


(s) => s.publicKey


({ transaction, signers = [] }) => {
    transaction.recentBlockhash = blockhash;
    transaction.setSigners(
      wallet.publicKey,
      ...signers.map((s) => s.publicKey),
    );
    if (signers?.length > 0) {
      transaction.partialSign(...signers);
    }
  }


({ transaction }) => transaction


async () => {
    while (!done && getUnixTs() - startTime < timeout) {
      connection.sendRawTransaction(rawTransaction, {
        skipPreflight: true,
      });
      await sleep(300);
    }
  }


(resolve, reject) => {
    (async () => {
      setTimeout(() => {
        if (done) {
          return;
        }
        done = true;
        console.log('Timed out for txid', txid);
        reject({ timeout: true });
      }, timeout);
      try {
        connection.onSignature(
          txid,
          (result) => {
            console.log('WS confirmed', txid, result);
            done = true;
            if (result.err) {
              reject(result.err);
            } else {
              resolve(result);
            }
          },
          'recent',
        );
        console.log('Set up WS connection', txid);
      } catch (e) {
        done = true;
        console.log('WS error in setup', txid, e);
      }
      while (!done) {
        // eslint-disable-next-line no-loop-func
        (async () => {
          try {
            const signatureStatuses = await connection.getSignatureStatuses([
              txid,
            ]);
            const result = signatureStatuses && signatureStatuses.value[0];
            if (!done) {
              if (!result) {
                console.log('REST null result for', txid, result);
              } else if (result.err) {
                console.log('REST error for', txid, result);
                done = true;
                reject(result.err);
              } else if (!result.confirmations) {
                console.log('REST no confirmations for', txid, result);
              } else {
                console.log('REST confirmation for', txid, result);
                done = true;
                resolve(result);
              }
            }
          } catch (e) {
            if (!done) {
              console.log('REST connection error: txid', txid, e);
            }
          }
        })();
        await sleep(300);
      }
    })();
  }


async () => {
      setTimeout(() => {
        if (done) {
          return;
        }
        done = true;
        console.log('Timed out for txid', txid);
        reject({ timeout: true });
      }, timeout);
      try {
        connection.onSignature(
          txid,
          (result) => {
            console.log('WS confirmed', txid, result);
            done = true;
            if (result.err) {
              reject(result.err);
            } else {
              resolve(result);
            }
          },
          'recent',
        );
        console.log('Set up WS connection', txid);
      } catch (e) {
        done = true;
        console.log('WS error in setup', txid, e);
      }
      while (!done) {
        // eslint-disable-next-line no-loop-func
        (async () => {
          try {
            const signatureStatuses = await connection.getSignatureStatuses([
              txid,
            ]);
            const result = signatureStatuses && signatureStatuses.value[0];
            if (!done) {
              if (!result) {
                console.log('REST null result for', txid, result);
              } else if (result.err) {
                console.log('REST error for', txid, result);
                done = true;
                reject(result.err);
              } else if (!result.confirmations) {
                console.log('REST no confirmations for', txid, result);
              } else {
                console.log('REST confirmation for', txid, result);
                done = true;
                resolve(result);
              }
            }
          } catch (e) {
            if (!done) {
              console.log('REST connection error: txid', txid, e);
            }
          }
        })();
        await sleep(300);
      }
    }


() => {
        if (done) {
          return;
        }
        done = true;
        console.log('Timed out for txid', txid);
        reject({ timeout: true });
      }


(result) => {
            console.log('WS confirmed', txid, result);
            done = true;
            if (result.err) {
              reject(result.err);
            } else {
              resolve(result);
            }
          }


async () => {
          try {
            const signatureStatuses = await connection.getSignatureStatuses([
              txid,
            ]);
            const result = signatureStatuses && signatureStatuses.value[0];
            if (!done) {
              if (!result) {
                console.log('REST null result for', txid, result);
              } else if (result.err) {
                console.log('REST error for', txid, result);
                done = true;
                reject(result.err);
              } else if (!result.confirmations) {
                console.log('REST no confirmations for', txid, result);
              } else {
                console.log('REST confirmation for', txid, result);
                done = true;
                resolve(result);
              }
            }
          } catch (e) {
            if (!done) {
              console.log('REST connection error: txid', txid, e);
            }
          }
        }


(t): t is Transaction => t !== undefined


(t) => {
      transaction.add(t);
    }


(k) => k.toBase58()


(account, i) => [publicKeys[i].toBase58(), account]


export enum Goal {
    DarkGaia = 0,
    RedJewelHunt = 1,
    ApocalypseGaia = 2,
    RandomGaia = 3,
}


() => {
    describe('Criar transacao mínima', () => {
        let transacaoMinima = buildTransacaoInicialMinima('434535345');

        it('Transação deve ser criada', () => {
            assert.equal(transacaoMinima == undefined, false);
        });

        it('Transação mínima deve ser R$ 50,00', () => {
            assert.equal(transacaoMinima.valor, DEPOSITO_INICIAL_MINIMO);
        });
    });

    describe('Criar transacao inicial com valor', () => {
        let transacaoInicial = buildTransacaoInicialComValor('434535345', 50000);

        it('Transação deve ser criada com o valor informado', () => {
            assert.equal(transacaoInicial == undefined, false);
            assert.equal(transacaoInicial.valor, 50000);
        });
    });
}


() => {
        let transacaoMinima = buildTransacaoInicialMinima('434535345');

        it('Transação deve ser criada', () => {
            assert.equal(transacaoMinima == undefined, false);
        });

        it('Transação mínima deve ser R$ 50,00', () => {
            assert.equal(transacaoMinima.valor, DEPOSITO_INICIAL_MINIMO);
        });
    }


() => {
            assert.equal(transacaoMinima == undefined, false);
        }


() => {
            assert.equal(transacaoMinima.valor, DEPOSITO_INICIAL_MINIMO);
        }


() => {
        let transacaoInicial = buildTransacaoInicialComValor('434535345', 50000);

        it('Transação deve ser criada com o valor informado', () => {
            assert.equal(transacaoInicial == undefined, false);
            assert.equal(transacaoInicial.valor, 50000);
        });
    }


() => {
            assert.equal(transacaoInicial == undefined, false);
            assert.equal(transacaoInicial.valor, 50000);
        }


export async function openStore(ctx: Context, storage: EntityStorage): Promise<Store> {
    const eventFactory = new EventFactory();
    let RangeIndexPromise = RangeIndexFactory.open(ctx, storage);
    let RangeIndexConditionalPromise = RangeIndexConditionalFactory.open(ctx, storage);
    return {
        storage,
        eventFactory,
        RangeIndex: await RangeIndexPromise,
        RangeIndexConditional: await RangeIndexConditionalPromise,
    };
}


async (ctx: Context, range1: number) => {
            return (await this._query(ctx, this.descriptor.secondaryIndexes[0], [range1])).items;
        }


(ctx: Context, range1: number, opts?: RangeQueryOptions<number>) => {
            return this._query(ctx, this.descriptor.secondaryIndexes[0], [range1], { limit: opts && opts.limit, reverse: opts && opts.reverse, after: opts && opts.after ? [opts.after] : undefined, afterCursor: opts && opts.afterCursor ? opts.afterCursor : undefined });
        }


(range1: number, opts?: StreamProps) => {
            return this._createStream(this.descriptor.secondaryIndexes[0], [range1], opts);
        }


(ctx: Context, range1: number, opts?: StreamProps) => {
            return this._createLiveStream(ctx, this.descriptor.secondaryIndexes[0], [range1], opts);
        }


(src) => src.range1 === 0


export class RangeIndex extends Entity<RangeIndexShape> {
    get id(): number { return this._rawValue.id; }
    get range1(): number { return this._rawValue.range1; }
    set range1(value: number) {
        let normalized = this.descriptor.codec.fields.range1.normalize(value);
        if (this._rawValue.range1 !== normalized) {
            this._rawValue.range1 = normalized;
            this._updatedValues.range1 = normalized;
            this.invalidate();
        }
    }
    get range2(): number { return this._rawValue.range2; }
    set range2(value: number) {
        let normalized = this.descriptor.codec.fields.range2.normalize(value);
        if (this._rawValue.range2 !== normalized) {
            this._rawValue.range2 = normalized;
            this._updatedValues.range2 = normalized;
            this.invalidate();
        }
    }

    delete(ctx: Context) {
        return this._delete(ctx);
    }
}


export class RangeIndexFactory extends EntityFactory<RangeIndexShape, RangeIndex> {

    static async open(ctx: Context, storage: EntityStorage) {
        let subspace = await storage.resolveEntityDirectory(ctx, 'rangeIndex');
        let secondaryIndexes: SecondaryIndexDescriptor[] = [];
        secondaryIndexes.push({ name: 'ranges', storageKey: 'ranges', type: { type: 'range', fields: [{ name: 'range1', type: 'integer' }, { name: 'range2', type: 'integer' }] }, subspace: await storage.resolveEntityIndexDirectory(ctx, 'rangeIndex', 'ranges'), condition: undefined });
        let primaryKeys: PrimaryKeyDescriptor[] = [];
        primaryKeys.push({ name: 'id', type: 'integer' });
        let fields: FieldDescriptor[] = [];
        fields.push({ name: 'range1', type: { type: 'integer' }, secure: false });
        fields.push({ name: 'range2', type: { type: 'integer' }, secure: false });
        let codec = c.struct({
            id: c.integer,
            range1: c.integer,
            range2: c.integer,
        });
        let descriptor: EntityDescriptor<RangeIndexShape> = {
            name: 'RangeIndex',
            storageKey: 'rangeIndex',
            allowDelete: true,
            subspace, codec, secondaryIndexes, storage, primaryKeys, fields
        };
        return new RangeIndexFactory(descriptor);
    }

    private constructor(descriptor: EntityDescriptor<RangeIndexShape>) {
        super(descriptor);
    }

    readonly ranges = Object.freeze({
        findAll: async (ctx: Context, range1: number) => {
            return (await this._query(ctx, this.descriptor.secondaryIndexes[0], [range1])).items;
        },
        query: (ctx: Context, range1: number, opts?: RangeQueryOptions<number>) => {
            return this._query(ctx, this.descriptor.secondaryIndexes[0], [range1], { limit: opts && opts.limit, reverse: opts && opts.reverse, after: opts && opts.after ? [opts.after] : undefined, afterCursor: opts && opts.afterCursor ? opts.afterCursor : undefined });
        },
        stream: (range1: number, opts?: StreamProps) => {
            return this._createStream(this.descriptor.secondaryIndexes[0], [range1], opts);
        },
        liveStream: (ctx: Context, range1: number, opts?: StreamProps) => {
            return this._createLiveStream(ctx, this.descriptor.secondaryIndexes[0], [range1], opts);
        },
    });

    create(ctx: Context, id: number, src: RangeIndexCreateShape): Promise<RangeIndex> {
        return this._create(ctx, [id], this.descriptor.codec.normalize({ id, ...src }));
    }

    create_UNSAFE(ctx: Context, id: number, src: RangeIndexCreateShape): RangeIndex {
        return this._create_UNSAFE(ctx, [id], this.descriptor.codec.normalize({ id, ...src }));
    }

    findById(ctx: Context, id: number): Promise<RangeIndex | null> | RangeIndex | null {
        return this._findById(ctx, [id]);
    }

    findByIdOrFail(ctx: Context, id: number): Promise<RangeIndex> | RangeIndex {
        return this._findByIdOrFail(ctx, [id]);
    }

    watch(ctx: Context, id: number): Watch {
        return this._watch(ctx, [id]);
    }

    protected _createEntityInstance(ctx: Context, value: ShapeWithMetadata<RangeIndexShape>): RangeIndex {
        return new RangeIndex([value.id], value, this.descriptor, this._flush, this._delete, ctx);
    }
}


export class RangeIndexConditional extends Entity<RangeIndexConditionalShape> {
    get id(): number { return this._rawValue.id; }
    get range1(): number { return this._rawValue.range1; }
    set range1(value: number) {
        let normalized = this.descriptor.codec.fields.range1.normalize(value);
        if (this._rawValue.range1 !== normalized) {
            this._rawValue.range1 = normalized;
            this._updatedValues.range1 = normalized;
            this.invalidate();
        }
    }
    get range2(): number { return this._rawValue.range2; }
    set range2(value: number) {
        let normalized = this.descriptor.codec.fields.range2.normalize(value);
        if (this._rawValue.range2 !== normalized) {
            this._rawValue.range2 = normalized;
            this._updatedValues.range2 = normalized;
            this.invalidate();
        }
    }

    delete(ctx: Context) {
        return this._delete(ctx);
    }
}


export class RangeIndexConditionalFactory extends EntityFactory<RangeIndexConditionalShape, RangeIndexConditional> {

    static async open(ctx: Context, storage: EntityStorage) {
        let subspace = await storage.resolveEntityDirectory(ctx, 'rangeIndexConditional');
        let secondaryIndexes: SecondaryIndexDescriptor[] = [];
        secondaryIndexes.push({ name: 'ranges', storageKey: 'ranges', type: { type: 'range', fields: [{ name: 'range1', type: 'integer' }, { name: 'range2', type: 'integer' }] }, subspace: await storage.resolveEntityIndexDirectory(ctx, 'rangeIndexConditional', 'ranges'), condition: (src) => src.range1 === 0 });
        let primaryKeys: PrimaryKeyDescriptor[] = [];
        primaryKeys.push({ name: 'id', type: 'integer' });
        let fields: FieldDescriptor[] = [];
        fields.push({ name: 'range1', type: { type: 'integer' }, secure: false });
        fields.push({ name: 'range2', type: { type: 'integer' }, secure: false });
        let codec = c.struct({
            id: c.integer,
            range1: c.integer,
            range2: c.integer,
        });
        let descriptor: EntityDescriptor<RangeIndexConditionalShape> = {
            name: 'RangeIndexConditional',
            storageKey: 'rangeIndexConditional',
            allowDelete: true,
            subspace, codec, secondaryIndexes, storage, primaryKeys, fields
        };
        return new RangeIndexConditionalFactory(descriptor);
    }

    private constructor(descriptor: EntityDescriptor<RangeIndexConditionalShape>) {
        super(descriptor);
    }

    readonly ranges = Object.freeze({
        findAll: async (ctx: Context, range1: number) => {
            return (await this._query(ctx, this.descriptor.secondaryIndexes[0], [range1])).items;
        },
        query: (ctx: Context, range1: number, opts?: RangeQueryOptions<number>) => {
            return this._query(ctx, this.descriptor.secondaryIndexes[0], [range1], { limit: opts && opts.limit, reverse: opts && opts.reverse, after: opts && opts.after ? [opts.after] : undefined, afterCursor: opts && opts.afterCursor ? opts.afterCursor : undefined });
        },
        stream: (range1: number, opts?: StreamProps) => {
            return this._createStream(this.descriptor.secondaryIndexes[0], [range1], opts);
        },
        liveStream: (ctx: Context, range1: number, opts?: StreamProps) => {
            return this._createLiveStream(ctx, this.descriptor.secondaryIndexes[0], [range1], opts);
        },
    });

    create(ctx: Context, id: number, src: RangeIndexConditionalCreateShape): Promise<RangeIndexConditional> {
        return this._create(ctx, [id], this.descriptor.codec.normalize({ id, ...src }));
    }

    create_UNSAFE(ctx: Context, id: number, src: RangeIndexConditionalCreateShape): RangeIndexConditional {
        return this._create_UNSAFE(ctx, [id], this.descriptor.codec.normalize({ id, ...src }));
    }

    findById(ctx: Context, id: number): Promise<RangeIndexConditional | null> | RangeIndexConditional | null {
        return this._findById(ctx, [id]);
    }

    findByIdOrFail(ctx: Context, id: number): Promise<RangeIndexConditional> | RangeIndexConditional {
        return this._findByIdOrFail(ctx, [id]);
    }

    watch(ctx: Context, id: number): Watch {
        return this._watch(ctx, [id]);
    }

    protected _createEntityInstance(ctx: Context, value: ShapeWithMetadata<RangeIndexConditionalShape>): RangeIndexConditional {
        return new RangeIndexConditional([value.id], value, this.descriptor, this._flush, this._delete, ctx);
    }
}


export interface RangeIndexShape {
    id: number;
    range1: number;
    range2: number;
}


export interface RangeIndexCreateShape {
    range1: number;
    range2: number;
}


export interface RangeIndexConditionalShape {
    id: number;
    range1: number;
    range2: number;
}


export interface RangeIndexConditionalCreateShape {
    range1: number;
    range2: number;
}


export interface Store extends BaseStore {
    readonly RangeIndex: RangeIndexFactory;
    readonly RangeIndexConditional: RangeIndexConditionalFactory;
}


delete(ctx: Context) {
        return this._delete(ctx);
    }


static async open(ctx: Context, storage: EntityStorage) {
        let subspace = await storage.resolveEntityDirectory(ctx, 'rangeIndex');
        let secondaryIndexes: SecondaryIndexDescriptor[] = [];
        secondaryIndexes.push({ name: 'ranges', storageKey: 'ranges', type: { type: 'range', fields: [{ name: 'range1', type: 'integer' }, { name: 'range2', type: 'integer' }] }, subspace: await storage.resolveEntityIndexDirectory(ctx, 'rangeIndex', 'ranges'), condition: undefined });
        let primaryKeys: PrimaryKeyDescriptor[] = [];
        primaryKeys.push({ name: 'id', type: 'integer' });
        let fields: FieldDescriptor[] = [];
        fields.push({ name: 'range1', type: { type: 'integer' }, secure: false });
        fields.push({ name: 'range2', type: { type: 'integer' }, secure: false });
        let codec = c.struct({
            id: c.integer,
            range1: c.integer,
            range2: c.integer,
        });
        let descriptor: EntityDescriptor<RangeIndexShape> = {
            name: 'RangeIndex',
            storageKey: 'rangeIndex',
            allowDelete: true,
            subspace, codec, secondaryIndexes, storage, primaryKeys, fields
        };
        return new RangeIndexFactory(descriptor);
    }


create(ctx: Context, id: number, src: RangeIndexCreateShape): Promise<RangeIndex> {
        return this._create(ctx, [id], this.descriptor.codec.normalize({ id, ...src }));
    }


create_UNSAFE(ctx: Context, id: number, src: RangeIndexCreateShape): RangeIndex {
        return this._create_UNSAFE(ctx, [id], this.descriptor.codec.normalize({ id, ...src }));
    }


findById(ctx: Context, id: number): Promise<RangeIndex | null> | RangeIndex | null {
        return this._findById(ctx, [id]);
    }


findByIdOrFail(ctx: Context, id: number): Promise<RangeIndex> | RangeIndex {
        return this._findByIdOrFail(ctx, [id]);
    }


watch(ctx: Context, id: number): Watch {
        return this._watch(ctx, [id]);
    }


protected _createEntityInstance(ctx: Context, value: ShapeWithMetadata<RangeIndexShape>): RangeIndex {
        return new RangeIndex([value.id], value, this.descriptor, this._flush, this._delete, ctx);
    }


static async open(ctx: Context, storage: EntityStorage) {
        let subspace = await storage.resolveEntityDirectory(ctx, 'rangeIndexConditional');
        let secondaryIndexes: SecondaryIndexDescriptor[] = [];
        secondaryIndexes.push({ name: 'ranges', storageKey: 'ranges', type: { type: 'range', fields: [{ name: 'range1', type: 'integer' }, { name: 'range2', type: 'integer' }] }, subspace: await storage.resolveEntityIndexDirectory(ctx, 'rangeIndexConditional', 'ranges'), condition: (src) => src.range1 === 0 });
        let primaryKeys: PrimaryKeyDescriptor[] = [];
        primaryKeys.push({ name: 'id', type: 'integer' });
        let fields: FieldDescriptor[] = [];
        fields.push({ name: 'range1', type: { type: 'integer' }, secure: false });
        fields.push({ name: 'range2', type: { type: 'integer' }, secure: false });
        let codec = c.struct({
            id: c.integer,
            range1: c.integer,
            range2: c.integer,
        });
        let descriptor: EntityDescriptor<RangeIndexConditionalShape> = {
            name: 'RangeIndexConditional',
            storageKey: 'rangeIndexConditional',
            allowDelete: true,
            subspace, codec, secondaryIndexes, storage, primaryKeys, fields
        };
        return new RangeIndexConditionalFactory(descriptor);
    }


create(ctx: Context, id: number, src: RangeIndexConditionalCreateShape): Promise<RangeIndexConditional> {
        return this._create(ctx, [id], this.descriptor.codec.normalize({ id, ...src }));
    }


create_UNSAFE(ctx: Context, id: number, src: RangeIndexConditionalCreateShape): RangeIndexConditional {
        return this._create_UNSAFE(ctx, [id], this.descriptor.codec.normalize({ id, ...src }));
    }


findById(ctx: Context, id: number): Promise<RangeIndexConditional | null> | RangeIndexConditional | null {
        return this._findById(ctx, [id]);
    }


findByIdOrFail(ctx: Context, id: number): Promise<RangeIndexConditional> | RangeIndexConditional {
        return this._findByIdOrFail(ctx, [id]);
    }


protected _createEntityInstance(ctx: Context, value: ShapeWithMetadata<RangeIndexConditionalShape>): RangeIndexConditional {
        return new RangeIndexConditional([value.id], value, this.descriptor, this._flush, this._delete, ctx);
    }


(cancel) => (this.Canceler = cancel)


(progressEvent: ProgressEvent) => {
        this._onProgress && this._onProgress(this.transformData(progressEvent));
      }


(item, index, array) => {
        if (this.file[index] instanceof File) {
          data.append(`file${index}`, this.file[index]);
        }
      }


(onfulfilled) => this._onSuccess && this._onSuccess(onfulfilled.data)


(error: Error) => this._onError && this._onError(error)


export default class FileProgressRequest {
  private file: UploadFileTypes;
  private _onProgress;
  private _onSuccess;
  private _onError;
  private Canceler?: Canceler;
  private DefaultOptions: AxiosRequestConfig;
  constructor(file: UploadFileTypes, options?: AxiosRequestConfig) {
    this.file = file;
    this.DefaultOptions = {
      /** */
      method: 'post',
      // 默认上报地址
      url: '/upload',
      cancelToken: new axiosSource.CancelToken((cancel) => (this.Canceler = cancel)),
      headers: { 'Content-Type': 'multipart/form-data' },
      onUploadProgress: (progressEvent: ProgressEvent) => {
        this._onProgress && this._onProgress(this.transformData(progressEvent));
      },
      ...(options ?? {})
    };
  }
  public upload(): this {
    let data = new FormData();
    if (this.file instanceof FileList) {
      Array.prototype.forEach.call(this.file, (item, index, array) => {
        if (this.file[index] instanceof File) {
          data.append(`file${index}`, this.file[index]);
        }
      });
    }
    if (this.file instanceof File) {
      data.append('file0', this.file);
    }
    if (this.file instanceof FormData) {
      data = this.file;
    }
    this.DefaultOptions.data = data;
    axios
      .request(this.DefaultOptions)
      .then((onfulfilled) => this._onSuccess && this._onSuccess(onfulfilled.data))
      .catch((error: Error) => this._onError && this._onError(error));
    return this;
  }
  private transformData(e: ProgressEvent): ProgressType {
    return {
      progress: e.total ? Math.floor((e.loaded / e.total) * 100) : 0,
      loaded: e.loaded,
      total: e.total,
      timeStamp: e.timeStamp
    };
  }
  public onProgress(callback?: (progressEvent: ProgressType) => void): this {
    this._onProgress = callback;
    return this;
  }
  public onSuccess<T extends { hasError?: boolean }>(callback?: (response: AxiosResponse<T>) => void): this {
    this._onSuccess = callback;
    return this;
  }
  public onCatch(callback?: (error: Error) => void): this {
    this._onError = callback;
    return this;
  }
  cancel(message?: string): void {
    this.Canceler && this.Canceler(message);
    this.Canceler = undefined;
  }
}


export interface ProgressType {
  progress: number;
  loaded: number;
  total: number;
  timeStamp: number;
}


export type UploadFileTypes = File | FileList | FormData;


public upload(): this {
    let data = new FormData();
    if (this.file instanceof FileList) {
      Array.prototype.forEach.call(this.file, (item, index, array) => {
        if (this.file[index] instanceof File) {
          data.append(`file${index}`, this.file[index]);
        }
      });
    }
    if (this.file instanceof File) {
      data.append('file0', this.file);
    }
    if (this.file instanceof FormData) {
      data = this.file;
    }
    this.DefaultOptions.data = data;
    axios
      .request(this.DefaultOptions)
      .then((onfulfilled) => this._onSuccess && this._onSuccess(onfulfilled.data))
      .catch((error: Error) => this._onError && this._onError(error));
    return this;
  }


private transformData(e: ProgressEvent): ProgressType {
    return {
      progress: e.total ? Math.floor((e.loaded / e.total) * 100) : 0,
      loaded: e.loaded,
      total: e.total,
      timeStamp: e.timeStamp
    };
  }


public onProgress(callback?: (progressEvent: ProgressType) => void): this {
    this._onProgress = callback;
    return this;
  }


public onSuccess<T extends { hasError?: boolean }>(callback?: (response: AxiosResponse<T>) => void): this {
    this._onSuccess = callback;
    return this;
  }


public onCatch(callback?: (error: Error) => void): this {
    this._onError = callback;
    return this;
  }


cancel(message?: string): void {
    this.Canceler && this.Canceler(message);
    this.Canceler = undefined;
  }


@Injectable()
export class TwofaService {
  constructor(private readonly usersService: AuthService) {}

  async generateTwoFASecret(user: UserEntity) {
    if (user.twoFAThrottleTime > new Date()) {
      throw new CustomHttpException(
        `tooManyRequest-{"second":"${this.differentBetweenDatesInSec(
          user.twoFAThrottleTime,
          new Date()
        )}"}`,
        HttpStatus.TOO_MANY_REQUESTS,
        StatusCodesList.TooManyTries
      );
    }
    const secret = authenticator.generateSecret();
    const otpauthUrl = authenticator.keyuri(
      user.email,
      TwofaConfig.authenticationAppNAme,
      secret
    );
    await this.usersService.setTwoFactorAuthenticationSecret(secret, user.id);
    return {
      secret,
      otpauthUrl
    };
  }

  isTwoFACodeValid(twoFASecret: string, user: UserEntity) {
    return authenticator.verify({
      token: twoFASecret,
      secret: user.twoFASecret
    });
  }

  async pipeQrCodeStream(stream: Response, otpauthUrl: string) {
    return toFileStream(stream, otpauthUrl);
  }

  async qrDataToUrl(otpauthUrl: string): Promise<string> {
    return toDataURL(otpauthUrl);
  }

  differentBetweenDatesInSec(initialDate: Date, endDate: Date): number {
    const diffInSeconds = Math.abs(initialDate.getTime() - endDate.getTime());
    return Math.round(diffInSeconds / 1000);
  }
}


async generateTwoFASecret(user: UserEntity) {
    if (user.twoFAThrottleTime > new Date()) {
      throw new CustomHttpException(
        `tooManyRequest-{"second":"${this.differentBetweenDatesInSec(
          user.twoFAThrottleTime,
          new Date()
        )}"}`,
        HttpStatus.TOO_MANY_REQUESTS,
        StatusCodesList.TooManyTries
      );
    }
    const secret = authenticator.generateSecret();
    const otpauthUrl = authenticator.keyuri(
      user.email,
      TwofaConfig.authenticationAppNAme,
      secret
    );
    await this.usersService.setTwoFactorAuthenticationSecret(secret, user.id);
    return {
      secret,
      otpauthUrl
    };
  }


isTwoFACodeValid(twoFASecret: string, user: UserEntity) {
    return authenticator.verify({
      token: twoFASecret,
      secret: user.twoFASecret
    });
  }


async pipeQrCodeStream(stream: Response, otpauthUrl: string) {
    return toFileStream(stream, otpauthUrl);
  }


async qrDataToUrl(otpauthUrl: string): Promise<string> {
    return toDataURL(otpauthUrl);
  }


differentBetweenDatesInSec(initialDate: Date, endDate: Date): number {
    const diffInSeconds = Math.abs(initialDate.getTime() - endDate.getTime());
    return Math.round(diffInSeconds / 1000);
  }


/**
 * surgipal_dev
 * API
 *
 * OpenAPI spec version: 1.5
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */
export interface Item92 {
  id: number;
  name?: string;
  managerName?: string;
  managerPhone?: string;
  managerPager?: string;
  managerEmail?: string;
  address?: string;
  suite?: string;
  city?: string;
  postalCode?: string;
  stateId?: number;
  countryId?: number;
  stateTyped?: string;
  userRole?: string;
  phone?: string;
  pager?: string;
}


async (options: ListOptions) => {
    try {
        const { defaultRuntime } = getSettings();
        let runtimes = await getInstalledRuntimes();
        runtimes = [ { name: 'empty', version: '' }, ...runtimes ];
        for (const runtime of runtimes) {
            console.log(chalk`${ defaultRuntime === runtime.name || !defaultRuntime && runtime.name === 'empty' ? chalk.green('*') : ' ' } ${runtime.name} {italic.gray runtime}`);
        }
        console.log();
    } catch (error) {
        console.error(error);
        process.exit(-1);
    }

}


export interface ListOptions {
}


() => {
  return (

        Remember Commnad

        @remember command All rights reserved

          <svg
            className="w-5 h-5 fill-current"
            fill="#000000"
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 50 50"
            width="50px"
            height="50px"
          >
            {' '}
            <path d="M25,2C12.317,2,2,12.317,2,25s10.317,23,23,23s23-10.317,23-23S37.683,2,25,2z M36.237,20.524 c0.01,0.236,0.016,0.476,0.016,0.717C36.253,28.559,30.68,37,20.491,37c-3.128,0-6.041-0.917-8.491-2.489 c0.433,0.052,0.872,0.077,1.321,0.077c2.596,0,4.985-0.884,6.879-2.37c-2.424-0.044-4.468-1.649-5.175-3.847 c0.339,0.065,0.686,0.1,1.044,0.1c0.505,0,0.995-0.067,1.458-0.195c-2.532-0.511-4.441-2.747-4.441-5.432c0-0.024,0-0.047,0-0.07 c0.747,0.415,1.6,0.665,2.509,0.694c-1.488-0.995-2.464-2.689-2.464-4.611c0-1.015,0.272-1.966,0.749-2.786 c2.733,3.351,6.815,5.556,11.418,5.788c-0.095-0.406-0.145-0.828-0.145-1.262c0-3.059,2.48-5.539,5.54-5.539 c1.593,0,3.032,0.672,4.042,1.749c1.261-0.248,2.448-0.709,3.518-1.343c-0.413,1.292-1.292,2.378-2.437,3.064 c1.122-0.136,2.188-0.432,3.183-0.873C38.257,18.766,37.318,19.743,36.237,20.524z" />
          </svg>

          <svg
            className="w-5 h-5 fill-current"
            viewBox="0 0 24 24"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path d="M12.026 2C7.13295 1.99937 2.96183 5.54799 2.17842 10.3779C1.395 15.2079 4.23061 19.893 8.87302 21.439C9.37302 21.529 9.55202 21.222 9.55202 20.958C9.55202 20.721 9.54402 20.093 9.54102 19.258C6.76602 19.858 6.18002 17.92 6.18002 17.92C5.99733 17.317 5.60459 16.7993 5.07302 16.461C4.17302 15.842 5.14202 15.856 5.14202 15.856C5.78269 15.9438 6.34657 16.3235 6.66902 16.884C6.94195 17.3803 7.40177 17.747 7.94632 17.9026C8.49087 18.0583 9.07503 17.99 9.56902 17.713C9.61544 17.207 9.84055 16.7341 10.204 16.379C7.99002 16.128 5.66202 15.272 5.66202 11.449C5.64973 10.4602 6.01691 9.5043 6.68802 8.778C6.38437 7.91731 6.42013 6.97325 6.78802 6.138C6.78802 6.138 7.62502 5.869 9.53002 7.159C11.1639 6.71101 12.8882 6.71101 14.522 7.159C16.428 5.868 17.264 6.138 17.264 6.138C17.6336 6.97286 17.6694 7.91757 17.364 8.778C18.0376 9.50423 18.4045 10.4626 18.388 11.453C18.388 15.286 16.058 16.128 13.836 16.375C14.3153 16.8651 14.5612 17.5373 14.511 18.221C14.511 19.555 14.499 20.631 14.499 20.958C14.499 21.225 14.677 21.535 15.186 21.437C19.8265 19.8884 22.6591 15.203 21.874 10.3743C21.089 5.54565 16.9181 1.99888 12.026 2Z"></path>
          </svg>


(): void => {

    // Automatically expand the video to fit the page up to 1200px x 720px

    //first post width:

    let firstPostWidth = document.getElementById('firstPost')?.clientWidth;

    this.videoWidth = firstPostWidth ? firstPostWidth * 0.93 : 480;

    this.videoHeight = this.videoWidth * 0.6;

    // this.cdr.detectChanges();

  }


@Component({
  selector: 'app-wafrn-youtube-player',
  templateUrl: './wafrn-youtube-player.component.html',
  styleUrls: ['./wafrn-youtube-player.component.scss']
})
export class WafrnYoutubePlayerComponent implements OnInit {

  @Input() video!: string;
  videoWidth: number = 0;
  videoHeight: number = 0;

  constructor() { }

  ngOnInit(): void {

    this.onResize();

    window.addEventListener('resize', this.onResize);
  }

  onResize = (): void => {

    // Automatically expand the video to fit the page up to 1200px x 720px

    //first post width:

    let firstPostWidth = document.getElementById('firstPost')?.clientWidth;

    this.videoWidth = firstPostWidth ? firstPostWidth * 0.93 : 480;

    this.videoHeight = this.videoWidth * 0.6;

    // this.cdr.detectChanges();

  }

  ngOnDestroy(): void {

    window.removeEventListener('resize', this.onResize);

  }

}


ngOnInit(): void {

    this.onResize();

    window.addEventListener('resize', this.onResize);
  }


ngOnDestroy(): void {

    window.removeEventListener('resize', this.onResize);

  }


// Return a list of all stash, controller pairs associated with the given (local) addresses
export async function findStakedAccounts (
  api: ApiPromise,
  addresses: string[]
): Promise<Map<string, StakePair>> {
  const stakePairs: Map<string, StakePair> = new Map();

  // Key is `stashAddress-controllerAddress`, use map to deduplicate
  await Promise.all(addresses.map(
    (address) =>
      new Promise<void>(async (resolve) => {
        const controllerAddress = await getControllerByStash(address, api);

        if (controllerAddress !== null) {
          stakePairs.set(`${address}-${controllerAddress}`, {
            stashAddress: address,
            controllerAddress: controllerAddress
          });
        }

        const stashAddress = await getStashByController(address, api);

        if (stashAddress !== null) {
          stakePairs.set(`${stashAddress}-${address}`, {
            stashAddress: stashAddress,
            controllerAddress: address
          });
        }

        resolve();
      })
  ));

  return stakePairs;
}


/**
 * Return null if there is no stake with this stash account address
 * @param address
 */
export async function getControllerByStash (
  address: string,
  api: ApiPromise
): Promise<string | null> {
  const controllerAddressOption: Option<AccountId32> = await api.query.staking.bonded(
    address
  ) as Option<AccountId32>;

  if (controllerAddressOption.isNone) {
    return null;
  }

  return controllerAddressOption.toString();
}


/**
 * Return null if there is no stake with this controller account address
 */
export async function getStashByController (
  address: string,
  api: ApiPromise
): Promise<string | null> {
  const ledgerOption: Option<any> = await api.query.staking.ledger(address) as Option<any>;

  if (ledgerOption.isNone) {
    return null;
  }

  return ledgerOption.unwrapOrDefault().stash.toString();
}


// Get the nominated validator stash addresses for stashAddress
export async function getNominationDetails (
  nominatedStashes: Nominations,
  stashAddress: string,
  api: ApiPromise,
  eraIndex: EraIndex
): Promise<Nomination[]> {
  const nominations: Nomination[] = [];
  const nominated =
    nominatedStashes && nominatedStashes.targets
      ? (nominatedStashes.targets.toJSON() as string[])
      : [];
  const submittedEraIndex = nominatedStashes.submittedIn;

  // For each nominator calculate the stashes share of stake
  await Promise.all(
    nominated.map(
      async (nominateToAddress) =>
        new Promise<void>(async (resolve) => {
          const { stakeRaw, stakeShare, state } = await getStakeShare(
            eraIndex,
            submittedEraIndex,
            nominateToAddress,
            stashAddress,
            api
          );

          nominations.push({
            nominateToAddress,
            stakeRaw,
            stakeShare,
            state
          });

          resolve();
        })
    )
  );

  return nominations;
}


// Reference: https://github.com/cennznet/cennznet/wiki/Validator-Guide#rewards
// Reference 2: cennznet/crml/staking/src/rewars/mod.rs/fn enqueue_reward_payouts&calculate_npos_payouts
export async function getNextRewardEstimate (
  stashAddress: string,
  api: ApiPromise
): Promise<BigNumber> {
  // @ts-ignore
  return await api.rpc.staking.accruedPayout(stashAddress);
}


// Return info on the stake contributed by [[stashAddress]] to [[nominatedAddress]]
export async function getStakeShare (
  eraIndex: EraIndex,
  submittedEraIndex: EraIndex,
  nominatedAddress: string,
  stashAddress: string,
  api: ApiPromise
): Promise<{ stakeShare: BigNumber; stakeRaw: BigNumber; state: NominationState }> {
  // TODO: cache these exposures
  const eraKey = `${nominatedAddress}-${eraIndex}`;
  const stakers = exposures.get(eraKey) || (await api.query.staking.erasStakers(eraIndex, nominatedAddress)) as Exposure;

  exposures.set(eraKey, stakers);

  const totalStakeAmount = new BigNumber(stakers.total.toString());

  // unclipped
  const exposure = stakers.others.find(
    (other) => other.who.toString() === stashAddress
  );

  if (exposure === undefined) {
    // nominator is not exposed, it may have been reallocated OR the nomination will apply in the next era
    return {
      stakeShare: new BigNumber(0),
      stakeRaw: new BigNumber(0),
      state: submittedEraIndex.toNumber() >= eraIndex.toNumber() ? NominationState.Pending : NominationState.ActiveReallocated
    };
  }

  const stakersClipped = exposuresClipped.get(eraKey) || (await api.query.staking.erasStakersClipped(eraIndex, nominatedAddress)) as Exposure;

  exposuresClipped.set(eraKey, stakersClipped);

  // clipped
  const exposureClipped = stakersClipped.others.find(
    (other) => other.who.toString() === stashAddress
  );
  const stashAccountStakeAmount = new BigNumber(exposure.value.toString());

  return {
    stakeRaw: stashAccountStakeAmount,
    stakeShare: stashAccountStakeAmount.div(totalStakeAmount),
    // this nomination is outside of the rewarded nominators set
    state: exposureClipped === undefined ? NominationState.ActiveOversubscribed : NominationState.ActiveStaked
  };
}


(address) =>
      new Promise<void>(async (resolve) => {
        const controllerAddress = await getControllerByStash(address, api);

        if (controllerAddress !== null) {
          stakePairs.set(`${address}-${controllerAddress}`, {
            stashAddress: address,
            controllerAddress: controllerAddress
          });
        }

        const stashAddress = await getStashByController(address, api);

        if (stashAddress !== null) {
          stakePairs.set(`${stashAddress}-${address}`, {
            stashAddress: stashAddress,
            controllerAddress: address
          });
        }

        resolve();
      })


async (resolve) => {
        const controllerAddress = await getControllerByStash(address, api);

        if (controllerAddress !== null) {
          stakePairs.set(`${address}-${controllerAddress}`, {
            stashAddress: address,
            controllerAddress: controllerAddress
          });
        }

        const stashAddress = await getStashByController(address, api);

        if (stashAddress !== null) {
          stakePairs.set(`${stashAddress}-${address}`, {
            stashAddress: stashAddress,
            controllerAddress: address
          });
        }

        resolve();
      }


async (nominateToAddress) =>
        new Promise<void>(async (resolve) => {
          const { stakeRaw, stakeShare, state } = await getStakeShare(
            eraIndex,
            submittedEraIndex,
            nominateToAddress,
            stashAddress,
            api
          );

          nominations.push({
            nominateToAddress,
            stakeRaw,
            stakeShare,
            state
          });

          resolve();
        })


async (resolve) => {
          const { stakeRaw, stakeShare, state } = await getStakeShare(
            eraIndex,
            submittedEraIndex,
            nominateToAddress,
            stashAddress,
            api
          );

          nominations.push({
            nominateToAddress,
            stakeRaw,
            stakeShare,
            state
          });

          resolve();
        }


(other) => other.who.toString() === stashAddress


export interface StakePair {
  stashAddress: string;
  controllerAddress: string;
}


export enum NominationState {
  // The nomination is active and staked
  ActiveStaked,
  // The nomination is active but stake has been reallocated this era
  ActiveReallocated,
  // The nomination is active but the stake will not be rewarded
  ActiveOversubscribed,
  // The nomination will be considered in future eras
  Pending,
}


function updateWorkbasketSummaryRepresentation(
  workbasketsSummary: WorkbasketSummary[],
  selectedWorkbasket: Workbasket
) {
  return workbasketsSummary.map((w) => {
    if (w.workbasketId === selectedWorkbasket.workbasketId) {
      const workbasketSummary: WorkbasketSummary = selectedWorkbasket;
      return workbasketSummary;
    }
    return w;
  });
}


(params) => {
      let tabName: string = params.tab;
      let tab: number;

      switch (tabName) {
        case 'information':
          tab = WorkbasketComponent.INFORMATION;
          break;
        case 'access-items':
          tab = WorkbasketComponent.ACCESS_ITEMS;
          break;
        case 'distribution-targets':
          tab = WorkbasketComponent.DISTRIBUTION_TARGETS;
          break;
        default:
          tab = WorkbasketComponent.INFORMATION;
      }

      ctx.patchState({
        badgeMessage: ''
      });

      ctx.dispatch(new SelectComponent(tab));
    }


(paginatedWorkbasketsSummary) => {
          ctx.patchState({ paginatedWorkbasketsSummary });
        }


(selectedWorkbasket) => {
          ctx.patchState({
            selectedWorkbasket,
            action: ACTION.READ,
            badgeMessage: ``
          });

          ctx.dispatch(new GetWorkbasketAccessItems(ctx.getState().selectedWorkbasket._links.accessItems.href));
          ctx.dispatch(
            new GetWorkbasketDistributionTargets(ctx.getState().selectedWorkbasket._links.distributionTargets.href)
          );

          this.location.go(
            this.location
              .path()
              .replace(/(workbaskets).*/g, `workbaskets/(detail:${action.workbasketId})?tab=${selectedComponent}`)
          );

          ctx.dispatch(new ClearWorkbasketFilter('selectedDistributionTargets'));
          ctx.dispatch(new ClearWorkbasketFilter('availableDistributionTargets'));
        }


() => {
      ctx.patchState({ button: undefined });
    }


(workbasketUpdated) => {
          this.notificationService.showToast(
            NOTIFICATION_TYPES.SUCCESS_ALERT_11,
            new Map<string, string>([['workbasketKey', workbasketUpdated.key]])
          );

          this.location.go(this.location.path().replace(/(workbaskets).*/g, 'workbaskets'));
        }


(error) => {
          this.notificationService.triggerError(NOTIFICATION_TYPES.CREATE_ERR_2, error);
        }


(workbasketUpdated) => ctx.dispatch(new SelectWorkbasket(workbasketUpdated.workbasketId))


(domain) => {
        this.location.go(this.location.path().replace(/(workbaskets).*/g, 'workbaskets/(detail:new-workbasket)'));

        if (!ctx.getState().workbasketAvailableDistributionTargets) {
          ctx.dispatch(new GetAvailableDistributionTargets());
        }

        const emptyWorkbasket: Workbasket = {};
        emptyWorkbasket.domain = domain;
        emptyWorkbasket.type = WorkbasketType.PERSONAL;

        const date = TaskanaDate.getDate();
        emptyWorkbasket.created = date;
        emptyWorkbasket.modified = date;

        const accessItems = { accessItems: [], _links: {} };
        const distributionTargets = { distributionTargets: [], _links: {} };

        ctx.patchState({
          action: ACTION.CREATE,
          selectedWorkbasket: emptyWorkbasket,
          selectedComponent: WorkbasketComponent.INFORMATION,
          badgeMessage: `Creating new workbasket`,
          workbasketAccessItems: accessItems,
          workbasketDistributionTargets: distributionTargets
        });

        ctx.dispatch(new ClearWorkbasketFilter('selectedDistributionTargets'));
        ctx.dispatch(new ClearWorkbasketFilter('availableDistributionTargets'));

        return of(null);
      }


(updatedWorkbasket) => {
          this.notificationService.showToast(
            NOTIFICATION_TYPES.SUCCESS_ALERT_10,
            new Map<string, string>([['workbasketKey', updatedWorkbasket.key]])
          );

          const paginatedWorkbasketSummary = { ...ctx.getState().paginatedWorkbasketsSummary };
          paginatedWorkbasketSummary.workbaskets = updateWorkbasketSummaryRepresentation(
            paginatedWorkbasketSummary.workbaskets,
            action.workbasket
          );
          ctx.patchState({
            selectedWorkbasket: updatedWorkbasket,
            paginatedWorkbasketsSummary: paginatedWorkbasketSummary
          });
        }


(error) => {
          this.notificationService.triggerError(NOTIFICATION_TYPES.SAVE_ERR_4, error);
        }


() => {
          this.notificationService.showToast(
            NOTIFICATION_TYPES.SUCCESS_ALERT_9,
            new Map<string, string>([['workbasketId', ctx.getState().selectedWorkbasket.workbasketId]])
          );
        }


(error) => {
          this.notificationService.triggerError(
            NOTIFICATION_TYPES.REMOVE_ERR_2,
            error,
            new Map<String, String>([['workbasketId', ctx.getState().selectedWorkbasket.workbasketId]])
          );
        }


(response) => {
        if (response.status === 202) {
          this.notificationService.triggerError(
            NOTIFICATION_TYPES.MARK_ERR,
            undefined,
            new Map<String, String>([['workbasketId', ctx.getState().selectedWorkbasket.workbasketId]])
          );
        } else {
          this.notificationService.showToast(
            NOTIFICATION_TYPES.SUCCESS_ALERT_12,
            new Map<string, string>([['workbasketId', ctx.getState().selectedWorkbasket.workbasketId]])
          );

          ctx.dispatch(new DeselectWorkbasket());
        }
      }


(workbasketAccessItemsRepresentation) => {
        ctx.patchState({
          workbasketAccessItems: workbasketAccessItemsRepresentation
        });
      }


(workbasketAccessItems) => {
            ctx.patchState({
              workbasketAccessItems
            });
            this.notificationService.showToast(
              NOTIFICATION_TYPES.SUCCESS_ALERT_7,
              new Map<string, string>([['workbasketKey', ctx.getState().selectedWorkbasket.key]])
            );
            return of(null);
          }


(error) => {
            this.notificationService.triggerError(NOTIFICATION_TYPES.SAVE_ERR_2, error);
          }


(workbasketDistributionTargets) => {
        ctx.patchState({
          workbasketDistributionTargets
        });
      }


(workbasketAvailableDistributionTargets: WorkbasketSummaryRepresentation) => {
        ctx.patchState({
          workbasketAvailableDistributionTargets: workbasketAvailableDistributionTargets.workbaskets
        });
      }


(updatedWorkbasketsDistributionTargets) => {
          ctx.patchState({
            workbasketDistributionTargets: updatedWorkbasketsDistributionTargets
          });
          const workbasketId = ctx.getState().selectedWorkbasket?.workbasketId;

          if (typeof workbasketId !== 'undefined') {
            this.workbasketService.getWorkBasket(workbasketId).subscribe((selectedWorkbasket) => {
              ctx.patchState({
                selectedWorkbasket,
                action: ACTION.READ
              });
              ctx.dispatch(new ClearWorkbasketFilter('selectedDistributionTargets'));
              ctx.dispatch(new ClearWorkbasketFilter('availableDistributionTargets'));
            });
          }
          this.requestInProgressService.setRequestInProgress(false);
          this.notificationService.showToast(
            NOTIFICATION_TYPES.SUCCESS_ALERT_8,
            new Map<string, string>([['workbasketName', ctx.getState().selectedWorkbasket.name]])
          );

          return of(null);
        }


(selectedWorkbasket) => {
              ctx.patchState({
                selectedWorkbasket,
                action: ACTION.READ
              });
              ctx.dispatch(new ClearWorkbasketFilter('selectedDistributionTargets'));
              ctx.dispatch(new ClearWorkbasketFilter('availableDistributionTargets'));
            }


(error) => {
          this.notificationService.triggerError(NOTIFICATION_TYPES.SAVE_ERR_3, error);
          this.requestInProgressService.setRequestInProgress(false);
        }


(w) => {
    if (w.workbasketId === selectedWorkbasket.workbasketId) {
      const workbasketSummary: WorkbasketSummary = selectedWorkbasket;
      return workbasketSummary;
    }
    return w;
  }


class InitializeStore {
  static readonly type = '[Workbasket] Initializing state';
}


export interface WorkbasketStateModel {
  paginatedWorkbasketsSummary: WorkbasketSummaryRepresentation;
  selectedWorkbasket: Workbasket;
  action: ACTION;
  workbasketAccessItems: WorkbasketAccessItemsRepresentation;
  workbasketDistributionTargets: WorkbasketDistributionTargets;
  workbasketAvailableDistributionTargets: WorkbasketSummary[];
  selectedComponent: WorkbasketComponent;
  badgeMessage: string;
  button: ButtonAction | undefined;
}


@Action(InitializeStore)
  initializeStore(ctx: StateContext<WorkbasketStateModel>): Observable<any> {
    // read the selected tab from the route
    this.route.queryParams.pipe(take(2)).subscribe((params) => {
      let tabName: string = params.tab;
      let tab: number;

      switch (tabName) {
        case 'information':
          tab = WorkbasketComponent.INFORMATION;
          break;
        case 'access-items':
          tab = WorkbasketComponent.ACCESS_ITEMS;
          break;
        case 'distribution-targets':
          tab = WorkbasketComponent.DISTRIBUTION_TARGETS;
          break;
        default:
          tab = WorkbasketComponent.INFORMATION;
      }

      ctx.patchState({
        badgeMessage: ''
      });

      ctx.dispatch(new SelectComponent(tab));
    });
    return of();
  }


@Action(GetWorkbasketsSummary)
  getWorkbasketsSummary(ctx: StateContext<WorkbasketStateModel>, action: GetWorkbasketsSummary): Observable<any> {
    ctx.patchState({
      paginatedWorkbasketsSummary: undefined
    });
    return this.workbasketService
      .getWorkBasketsSummary(action.forceRequest, action.filterParameter, action.sortParameter, action.pageParameter)
      .pipe(
        take(1),
        tap((paginatedWorkbasketsSummary) => {
          ctx.patchState({ paginatedWorkbasketsSummary });
        })
      );
  }


@Action(SelectWorkbasket)
  selectWorkbasket(ctx: StateContext<WorkbasketStateModel>, action: SelectWorkbasket): Observable<any> {
    let selectedComponent;
    switch (ctx.getState().selectedComponent) {
      case WorkbasketComponent.INFORMATION:
        selectedComponent = 'information';
        break;
      case WorkbasketComponent.ACCESS_ITEMS:
        selectedComponent = 'access-items';
        break;
      case WorkbasketComponent.DISTRIBUTION_TARGETS:
        selectedComponent = 'distribution-targets';
        break;
    }

    const id = action.workbasketId;
    if (typeof id !== 'undefined') {
      return this.workbasketService.getWorkBasket(id).pipe(
        take(1),
        tap((selectedWorkbasket) => {
          ctx.patchState({
            selectedWorkbasket,
            action: ACTION.READ,
            badgeMessage: ``
          });

          ctx.dispatch(new GetWorkbasketAccessItems(ctx.getState().selectedWorkbasket._links.accessItems.href));
          ctx.dispatch(
            new GetWorkbasketDistributionTargets(ctx.getState().selectedWorkbasket._links.distributionTargets.href)
          );

          this.location.go(
            this.location
              .path()
              .replace(/(workbaskets).*/g, `workbaskets/(detail:${action.workbasketId})?tab=${selectedComponent}`)
          );

          ctx.dispatch(new ClearWorkbasketFilter('selectedDistributionTargets'));
          ctx.dispatch(new ClearWorkbasketFilter('availableDistributionTargets'));
        })
      );
    }
    return of(null);
  }


@Action(DeselectWorkbasket)
  deselectWorkbasket(ctx: StateContext<WorkbasketStateModel>): Observable<any> {
    this.location.go(this.location.path().replace(/(workbaskets).*/g, 'workbaskets'));
    ctx.patchState({
      selectedWorkbasket: undefined,
      action: ACTION.READ
    });
    return of(null);
  }


@Action(SetActiveAction)
  setActiveAction(ctx: StateContext<WorkbasketStateModel>, action: SetActiveAction): Observable<any> {
    ctx.patchState({ action: action.action });
    return of(null);
  }


@Action(SelectComponent)
  selectComponent(ctx: StateContext<WorkbasketStateModel>, action: SelectComponent): Observable<any> {
    switch (action.component) {
      case WorkbasketComponent.INFORMATION:
        ctx.patchState({ selectedComponent: WorkbasketComponent.INFORMATION });
        this.location.go(this.location.path().replace(/(tab).*/g, 'tab=information'));
        break;
      case WorkbasketComponent.ACCESS_ITEMS:
        ctx.patchState({ selectedComponent: WorkbasketComponent.ACCESS_ITEMS });
        this.location.go(this.location.path().replace(/(tab).*/g, 'tab=access-items'));
        break;
      case WorkbasketComponent.DISTRIBUTION_TARGETS:
        ctx.patchState({ selectedComponent: WorkbasketComponent.DISTRIBUTION_TARGETS });
        this.location.go(this.location.path().replace(/(tab).*/g, 'tab=distribution-targets'));
        break;
    }
    return of(null);
  }


@Action(OnButtonPressed)
  doWorkbasketDetailsAction(ctx: StateContext<WorkbasketStateModel>, action: OnButtonPressed): Observable<any> {
    ctx.patchState({ button: action.button });
    setTimeout(() => {
      ctx.patchState({ button: undefined });
    }, 500);
    return of(null);
  }


@Action(SaveNewWorkbasket)
  saveNewWorkbasket(ctx: StateContext<WorkbasketStateModel>, action: SaveNewWorkbasket): Observable<any> {
    ctx.dispatch(new OnButtonPressed(undefined));
    return this.workbasketService.createWorkbasket(action.workbasket).pipe(
      take(1),
      tap(
        (workbasketUpdated) => {
          this.notificationService.showToast(
            NOTIFICATION_TYPES.SUCCESS_ALERT_11,
            new Map<string, string>([['workbasketKey', workbasketUpdated.key]])
          );

          this.location.go(this.location.path().replace(/(workbaskets).*/g, 'workbaskets'));
        },
        (error) => {
          this.notificationService.triggerError(NOTIFICATION_TYPES.CREATE_ERR_2, error);
        }
      ),
      concatMap((workbasketUpdated) => ctx.dispatch(new SelectWorkbasket(workbasketUpdated.workbasketId)))
    );
  }


@Action(CopyWorkbasket)
  copyWorkbasket(ctx: StateContext<WorkbasketStateModel>, action: CopyWorkbasket): Observable<any> {
    this.location.go(this.location.path().replace(/(workbaskets).*/g, 'workbaskets/(detail:new-workbasket)'));
    ctx.dispatch(new OnButtonPressed(undefined));

    const workbasket = { ...ctx.getState().selectedWorkbasket };
    delete workbasket.workbasketId;

    ctx.patchState({
      action: ACTION.COPY,
      selectedWorkbasket: workbasket,
      badgeMessage: `Copying workbasket: ${workbasket.key}`
    });

    ctx.dispatch(new ClearWorkbasketFilter('selectedDistributionTargets'));
    ctx.dispatch(new ClearWorkbasketFilter('availableDistributionTargets'));

    return of(null);
  }


@Action(CreateWorkbasket)
  createWorkbasket(ctx: StateContext<WorkbasketStateModel>): Observable<any> {
    return this.domainService.getSelectedDomain().pipe(
      take(1),
      tap((domain) => {
        this.location.go(this.location.path().replace(/(workbaskets).*/g, 'workbaskets/(detail:new-workbasket)'));

        if (!ctx.getState().workbasketAvailableDistributionTargets) {
          ctx.dispatch(new GetAvailableDistributionTargets());
        }

        const emptyWorkbasket: Workbasket = {};
        emptyWorkbasket.domain = domain;
        emptyWorkbasket.type = WorkbasketType.PERSONAL;

        const date = TaskanaDate.getDate();
        emptyWorkbasket.created = date;
        emptyWorkbasket.modified = date;

        const accessItems = { accessItems: [], _links: {} };
        const distributionTargets = { distributionTargets: [], _links: {} };

        ctx.patchState({
          action: ACTION.CREATE,
          selectedWorkbasket: emptyWorkbasket,
          selectedComponent: WorkbasketComponent.INFORMATION,
          badgeMessage: `Creating new workbasket`,
          workbasketAccessItems: accessItems,
          workbasketDistributionTargets: distributionTargets
        });

        ctx.dispatch(new ClearWorkbasketFilter('selectedDistributionTargets'));
        ctx.dispatch(new ClearWorkbasketFilter('availableDistributionTargets'));

        return of(null);
      })
    );
  }


@Action(UpdateWorkbasket)
  updateWorkbasket(ctx: StateContext<WorkbasketStateModel>, action: UpdateWorkbasket): Observable<any> {
    ctx.dispatch(new OnButtonPressed(undefined));
    return this.workbasketService.updateWorkbasket(action.url, action.workbasket).pipe(
      take(1),
      tap(
        (updatedWorkbasket) => {
          this.notificationService.showToast(
            NOTIFICATION_TYPES.SUCCESS_ALERT_10,
            new Map<string, string>([['workbasketKey', updatedWorkbasket.key]])
          );

          const paginatedWorkbasketSummary = { ...ctx.getState().paginatedWorkbasketsSummary };
          paginatedWorkbasketSummary.workbaskets = updateWorkbasketSummaryRepresentation(
            paginatedWorkbasketSummary.workbaskets,
            action.workbasket
          );
          ctx.patchState({
            selectedWorkbasket: updatedWorkbasket,
            paginatedWorkbasketsSummary: paginatedWorkbasketSummary
          });
        },
        (error) => {
          this.notificationService.triggerError(NOTIFICATION_TYPES.SAVE_ERR_4, error);
        }
      )
    );
  }


@Action(RemoveDistributionTarget)
  removeDistributionTarget(ctx: StateContext<WorkbasketStateModel>, action: RemoveDistributionTarget): Observable<any> {
    ctx.dispatch(new OnButtonPressed(undefined));
    return this.workbasketService.removeDistributionTarget(action.url).pipe(
      take(1),
      tap(
        () => {
          this.notificationService.showToast(
            NOTIFICATION_TYPES.SUCCESS_ALERT_9,
            new Map<string, string>([['workbasketId', ctx.getState().selectedWorkbasket.workbasketId]])
          );
        },
        (error) => {
          this.notificationService.triggerError(
            NOTIFICATION_TYPES.REMOVE_ERR_2,
            error,
            new Map<String, String>([['workbasketId', ctx.getState().selectedWorkbasket.workbasketId]])
          );
        }
      )
    );
  }


@Action(MarkWorkbasketForDeletion)
  deleteWorkbasket(ctx: StateContext<WorkbasketStateModel>, action: MarkWorkbasketForDeletion): Observable<any> {
    ctx.dispatch(new OnButtonPressed(undefined));
    return this.workbasketService.markWorkbasketForDeletion(action.url).pipe(
      take(1),
      tap((response) => {
        if (response.status === 202) {
          this.notificationService.triggerError(
            NOTIFICATION_TYPES.MARK_ERR,
            undefined,
            new Map<String, String>([['workbasketId', ctx.getState().selectedWorkbasket.workbasketId]])
          );
        } else {
          this.notificationService.showToast(
            NOTIFICATION_TYPES.SUCCESS_ALERT_12,
            new Map<string, string>([['workbasketId', ctx.getState().selectedWorkbasket.workbasketId]])
          );

          ctx.dispatch(new DeselectWorkbasket());
        }
      })
    );
  }


@Action(GetWorkbasketAccessItems)
  getWorkbasketAccessItems(ctx: StateContext<WorkbasketStateModel>, action: GetWorkbasketAccessItems): Observable<any> {
    return this.workbasketService.getWorkBasketAccessItems(action.url).pipe(
      take(1),
      tap((workbasketAccessItemsRepresentation) => {
        ctx.patchState({
          workbasketAccessItems: workbasketAccessItemsRepresentation
        });
      })
    );
  }


@Action(UpdateWorkbasketAccessItems)
  updateWorkbasketAccessItems(
    ctx: StateContext<WorkbasketStateModel>,
    action: UpdateWorkbasketAccessItems
  ): Observable<any> {
    ctx.dispatch(new OnButtonPressed(undefined));
    return this.workbasketService
      .updateWorkBasketAccessItem(action.url, { accessItems: action.workbasketAccessItems })
      .pipe(
        take(1),
        tap(
          (workbasketAccessItems) => {
            ctx.patchState({
              workbasketAccessItems
            });
            this.notificationService.showToast(
              NOTIFICATION_TYPES.SUCCESS_ALERT_7,
              new Map<string, string>([['workbasketKey', ctx.getState().selectedWorkbasket.key]])
            );
            return of(null);
          },
          (error) => {
            this.notificationService.triggerError(NOTIFICATION_TYPES.SAVE_ERR_2, error);
          }
        )
      );
  }


@Action(GetWorkbasketDistributionTargets)
  getWorkbasketDistributionTargets(
    ctx: StateContext<WorkbasketStateModel>,
    action: GetWorkbasketDistributionTargets
  ): Observable<any> {
    return this.workbasketService.getWorkBasketsDistributionTargets(action.url).pipe(
      take(1),
      tap((workbasketDistributionTargets) => {
        ctx.patchState({
          workbasketDistributionTargets
        });
      })
    );
  }


@Action(GetAvailableDistributionTargets)
  getAvailableDistributionTargets(ctx: StateContext<WorkbasketStateModel>): Observable<any> {
    return this.workbasketService.getWorkBasketsSummary(true).pipe(
      take(1),
      tap((workbasketAvailableDistributionTargets: WorkbasketSummaryRepresentation) => {
        ctx.patchState({
          workbasketAvailableDistributionTargets: workbasketAvailableDistributionTargets.workbaskets
        });
      })
    );
  }


@Action(UpdateWorkbasketDistributionTargets)
  updateWorkbasketDistributionTargets(
    ctx: StateContext<WorkbasketStateModel>,
    action: UpdateWorkbasketDistributionTargets
  ): Observable<any> {
    this.requestInProgressService.setRequestInProgress(true);
    return this.workbasketService.updateWorkBasketsDistributionTargets(action.url, action.distributionTargetsIds).pipe(
      take(1),
      tap(
        (updatedWorkbasketsDistributionTargets) => {
          ctx.patchState({
            workbasketDistributionTargets: updatedWorkbasketsDistributionTargets
          });
          const workbasketId = ctx.getState().selectedWorkbasket?.workbasketId;

          if (typeof workbasketId !== 'undefined') {
            this.workbasketService.getWorkBasket(workbasketId).subscribe((selectedWorkbasket) => {
              ctx.patchState({
                selectedWorkbasket,
                action: ACTION.READ
              });
              ctx.dispatch(new ClearWorkbasketFilter('selectedDistributionTargets'));
              ctx.dispatch(new ClearWorkbasketFilter('availableDistributionTargets'));
            });
          }
          this.requestInProgressService.setRequestInProgress(false);
          this.notificationService.showToast(
            NOTIFICATION_TYPES.SUCCESS_ALERT_8,
            new Map<string, string>([['workbasketName', ctx.getState().selectedWorkbasket.name]])
          );

          return of(null);
        },
        (error) => {
          this.notificationService.triggerError(NOTIFICATION_TYPES.SAVE_ERR_3, error);
          this.requestInProgressService.setRequestInProgress(false);
        }
      )
    );
  }


ngxsAfterBootstrap(ctx?: StateContext<any>): void {
    ctx.dispatch(new InitializeStore());
  }


@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    AppTranslationModule,
    NgaModule,
    NgbModalModule,
    routing
  ],
  declarations: [
    Admin,
    Systemparameters,
    UsersComponents,
    RoleComponent,
    DefaultModalRole,
    DeleteModalRole,
    DefaultModalUser,
    DeleteModalUser
  ],
  entryComponents: [
    DefaultModalRole,
    DeleteModalRole,
    DefaultModalUser,
    DeleteModalUser
  ]
})
export class AdminModule {
}


(props) => (
  <Wrapper>
    {props.items.map(({ node }) => (
      <PortfolioCard key={node.id} slug={node.fields.slug} {...node.frontmatter} />
    ))}
  </Wrapper>
)


({ node }) => (
      <PortfolioCard key={node.id}


interface Props {
  items: Node[];
}


export class CurrentUserInterceptor implements NestInterceptor {
  constructor(private usersService: UsersService) {}

  async intercept(context: ExecutionContext, handler: CallHandler) {
    const request = context.switchToHttp().getRequest();
    const { id } = request.session;

    if (id) {
      const user = await this.usersService.getUserById(id);
      request.currentUser = user;
    }

    return handler.handle();
  }
}


async intercept(context: ExecutionContext, handler: CallHandler) {
    const request = context.switchToHttp().getRequest();
    const { id } = request.session;

    if (id) {
      const user = await this.usersService.getUserById(id);
      request.currentUser = user;
    }

    return handler.handle();
  }


/**
 * Returns an array of HTML elements located under the point specified by x, y.
 * If the native elementsFromPoint function does not exist, a polyfill will be used.
 *
 * @param  {number} x : X position
 * @param  {number} y : Y position
 * @return {array} : Array of the elements under the point (x, y)
 */
export declare function elementsFromPoint(x: number, y: number): any[];


export declare class HttpInstance {
    baseURL: string;
    constructor(param: HttpInstanceParam);
    private init;
    protected convertRequest(config: AxiosRequestConfig): AxiosRequestConfig;
    protected convertResponse(config: AxiosResponse<any>): AxiosResponse<any>;
    create(opts: AxiosOpt): Promise<unknown>;
    handleSuccess(response: AxiosResponse<any>, resolve: {
        (value?: unknown): void;
        (arg0: any): void;
    }, opts: AxiosOpt): void;
    handleError(error: any, reject: {
        (reason?: any): void;
        (arg0: any): void;
    }, opts: AxiosOpt): void;
}


export declare interface AxiosOpt {
    method?: string;
    url?: any;
    responseType?: any;
    data?: {};
    formData?: any;
    timeout?: number;
    [x: string]: any;
}


export declare interface HttpInstanceParam {
    baseURL: string;
}


protected convertRequest(config: AxiosRequestConfig): AxiosRequestConfig;


protected convertResponse(config: AxiosResponse<any>): AxiosResponse<any>;


create(opts: AxiosOpt): Promise<unknown>;


handleSuccess(response: AxiosResponse<any>, resolve: {
        (value?: unknown): void;
        (arg0: any): void;
    }, opts: AxiosOpt): void;


handleError(error: any, reject: {
        (reason?: any): void;
        (arg0: any): void;
    }, opts: AxiosOpt): void;


() => {
    return (
            <>
            <NewFlowModal/>
            <SearchModal/>
            <NewItemModal/>
            </>
    )
}


export class JenkinsTriggerTemplate extends React.Component<ITriggerTemplateComponentProps> {
  public static formatLabel = BaseBuildTriggerTemplate.formatLabel;

  public render() {
    return <BaseBuildTriggerTemplate {...this.props} buildTriggerType={BuildServiceType.Jenkins} />;
  }
}


public render() {
    return <BaseBuildTriggerTemplate {...this.props} buildTriggerType={BuildServiceType.Jenkins} />;
  }


function batchUpdateUsers(ids: string[], datas: any[]) {
  const ops = ids.map((id, idx) => {
    return {
      updateOne: {
        filter: {
          _id: id,
        },
        update: datas[idx],
      },
    };
  });
  return User.bulkWrite(ops);
}


(id, idx) => {
    return {
      updateOne: {
        filter: {
          _id: id,
        },
        update: datas[idx],
      },
    };
  }


/**
 *
Represents the properties of a global secondary index.

 */
export interface _GlobalSecondaryIndexDescription {
    /**
     *
The name of the global secondary index.

     */
    IndexName?: string;

    /**
     *
The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types:

 HASH - partition key

 RANGE - sort key

 <note>
The partition key of an item is also known as its hash attribute. The term "hash attribute" derives from DynamoDB' usage of an internal hash function to evenly distribute data items across partitions, based on their partition key values.

The sort key of an item is also known as its range attribute. The term "range attribute" derives from the way DynamoDB stores items with the same partition key physically close together, in sorted order by the sort key value.
 </note>
     */
    KeySchema?: Array<_KeySchemaElement>|Iterable<_KeySchemaElement>;

    /**
     *
Represents attributes that are copied (projected) from the table into the global secondary index. These are in addition to the primary key attributes and index key attributes, which are automatically projected.

     */
    Projection?: _Projection;

    /**
     *
The current state of the global secondary index:

 CREATING - The index is being created.

 UPDATING - The index is being updated.

 DELETING - The index is being deleted.

 ACTIVE - The index is ready for use.

     */
    IndexStatus?: 'CREATING'|'UPDATING'|'DELETING'|'ACTIVE'|string;

    /**
     *
Indicates whether the index is currently backfilling. Backfilling is the process of reading items from the table and determining whether they can be added to the index. (Not all items will qualify: For example, a partition key cannot have any duplicate values.) If an item can be added to the index, DynamoDB will do so. After all items have been processed, the backfilling operation is complete and Backfilling is false.
 <note>
For indexes that were created during a CreateTable operation, the Backfilling attribute does not appear in the DescribeTable output.
 </note>
     */
    Backfilling?: boolean;

    /**
     *
Represents the provisioned throughput settings for the specified global secondary index.

For current minimum and maximum provisioned throughput values, see Limits in the Amazon DynamoDB Developer Guide.

     */
    ProvisionedThroughput?: _ProvisionedThroughputDescription;

    /**
     *
The total size of the specified index, in bytes. DynamoDB updates this value approximately every six hours. Recent changes might not be reflected in this value.

     */
    IndexSizeBytes?: number;

    /**
     *
The number of items in the specified index. DynamoDB updates this value approximately every six hours. Recent changes might not be reflected in this value.

     */
    ItemCount?: number;

    /**
     *
The Amazon Resource Name (ARN) that uniquely identifies the index.

     */
    IndexArn?: string;
}


export interface _UnmarshalledGlobalSecondaryIndexDescription extends _GlobalSecondaryIndexDescription {
    /**
     *
The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types:

 HASH - partition key

 RANGE - sort key

 <note>
The partition key of an item is also known as its hash attribute. The term "hash attribute" derives from DynamoDB' usage of an internal hash function to evenly distribute data items across partitions, based on their partition key values.

The sort key of an item is also known as its range attribute. The term "range attribute" derives from the way DynamoDB stores items with the same partition key physically close together, in sorted order by the sort key value.
 </note>
     */
    KeySchema?: Array<_UnmarshalledKeySchemaElement>;

    /**
     *
Represents attributes that are copied (projected) from the table into the global secondary index. These are in addition to the primary key attributes and index key attributes, which are automatically projected.

     */
    Projection?: _UnmarshalledProjection;

    /**
     *
Represents the provisioned throughput settings for the specified global secondary index.

For current minimum and maximum provisioned throughput values, see Limits in the Amazon DynamoDB Developer Guide.

     */
    ProvisionedThroughput?: _UnmarshalledProvisionedThroughputDescription;
}


(msg: string) => {
  return [{
    required: true,
    message: msg + '为必填项',
  }];
}


export function HttpContext({ httpContext }: Props) {
  if (!httpContext || !httpContext.url) {
    return null;
  }

  return (
    <Fragment>
      <EuiTitle size="xs">

HTTP URL

      </EuiTitle>
      <EuiSpacer size="m" />
      <ContextUrl>{httpContext.url}</ContextUrl>
      <EuiSpacer size="l" />
    </Fragment>
  );
}


interface Props {
  httpContext: NonNullable<Span['context']>['http'];
}


(activeMapId) => activeMapId === this.mapId


(flags) => flags.get(toolsFlags.isMeasureToolActive)


([isActiveMap, isMeasureToolActive]) => {
			if (isActiveMap && isMeasureToolActive) {
				this.createInteraction();
			} else {
				this.clearInteractionAndEntities();
			}
		}


() => {
				if (this.drawInteractionHandler) {
					this.createInteraction();
				}
			}


(event) => event.originalEvent.which === 1


(featureCollection: FeatureCollection<GeometryObject>) => {
				const [featureJson] = featureCollection.features;
				const newEntity: IVisualizerEntity = {
					id: UUID.UUID(),
					featureJson
				};
				this.addOrUpdateEntities([newEntity]).subscribe();
			}


(style) => {
			styles.push(style);
		}


(start, end) => {
				const lineString = new LineString([start, end]);
				const centroid = getPointByGeometry(<any>{
					type: lineString.getType(),
					coordinates: lineString.getCoordinates()
				});
				const segmentLengthText = this.formatLength(lineString, projection);
				const singlePointLengthTextStyle = this.getSinglePointLengthTextStyle();
				singlePointLengthTextStyle.setText(segmentLengthText);
				styles.push(new Style({
					geometry: new Point(<[number, number]>centroid.coordinates),
					text: singlePointLengthTextStyle
				}));
			}


getSinglePointLengthTextStyle(): Text {
		return new Text({
			font: '14px Calibri,sans-serif',
			fill: new Fill({
				color: '#FFFFFF'
			}),
			stroke: new Stroke({
				color: '#000',
				width: 3
			}),
			offsetY: 30
		});
	}


onResetView(): Observable<boolean> {
		return super.onResetView()
			.pipe(tap(() => {
				if (this.drawInteractionHandler) {
					this.createInteraction();
				}
			}));
	}


clearInteractionAndEntities() {
		this.removeDrawInteraction();
		this.clearEntities();
	}


createInteraction(type = 'LineString') {
		this.removeDrawInteraction();

		this.interactionSource = new VectorSource({ wrapX: false });

		const drawInteractionHandler = new Draw(<any>{
			source: this.interactionSource,
			type: type,
			condition: (event) => event.originalEvent.which === 1,
			style: this.drawFeatureStyle.bind(this)
		});

		drawInteractionHandler.on('drawend', this.onDrawEndEvent.bind(this));
		this.addInteraction(VisualizerInteractions.drawInteractionHandler, drawInteractionHandler);
	}


removeDrawInteraction() {
		this.removeInteraction(VisualizerInteractions.drawInteractionHandler);
	}


onDrawEndEvent(data) {
		this.projectionService.projectCollectionAccurately([data.feature], this.iMap.mapObject)
			.subscribe((featureCollection: FeatureCollection<GeometryObject>) => {
				const [featureJson] = featureCollection.features;
				const newEntity: IVisualizerEntity = {
					id: UUID.UUID(),
					featureJson
				};
				this.addOrUpdateEntities([newEntity]).subscribe();
			});
	}


// override base entities visualizer style
featureStyle(feature: Feature, state: string = VisualizerStates.INITIAL) {
		const styles = this.mainStyle(feature);
		const measureStyles = this.getMeasureTextStyle(feature, true);
		measureStyles.forEach((style) => {
			styles.push(style);
		});
		return styles;
	}


// draw style (temp until DBClick)
drawFeatureStyle(feature: Feature) {
		const styles = [this.editDistanceStyle];
		const measureStyles = this.getMeasureTextStyle(feature);
		measureStyles.forEach((style) => {
			styles.push(style);
		});
		return styles;
	}


// Line style (after DBClick)
mainStyle(feature) {
		const styles = [new Style({
			stroke: new Stroke({
				color: this.visualizerStyle.initial.stroke,
				width: this.visualizerStyle.initial['stroke-width']
			})
		})];
		// Points
		const pointsStyle = new Style({
			image: new Circle({
				radius: 5,
				stroke: new Stroke({
					color: this.visualizerStyle.initial.stroke,
					width: this.visualizerStyle.initial['stroke-width']
				}),
				fill: new Fill({ color: this.visualizerStyle.initial.fill })
			}),
			geometry: function (feature) {
				// return the coordinates of the first ring of the polygon
				const coordinates = (<LineString>feature.getGeometry()).getCoordinates();
				return new MultiPoint(coordinates);
			}
		});
		styles.push(pointsStyle);
		return styles;
	}


// points string styles
getMeasureTextStyle(feature: Feature, calculateCenterOfMass = false) {
		const styles = [];
		const geometry = <LineString>feature.getGeometry();

		if (geometry.getType() === 'Point') {
			return styles;
		}
		const view = (<any>this.iMap.mapObject).getView();
		const projection = view.getProjection();

		// all line string
		const allLengthText = this.formatLength(geometry, projection);
		this.allLengthTextStyle.setText(allLengthText);
		let allLinePoint = new Point(geometry.getCoordinates()[0]);

		if (calculateCenterOfMass) {
			const featureId = <string>feature.getId();
			const entityMap = this.idToEntity.get(featureId);
			if (entityMap) {
				const featureGeoJson = <any>this.geoJsonFormat.writeFeatureObject(entityMap.feature);
				const centroid = getPointByGeometry(featureGeoJson.geometry);
				allLinePoint = new Point(<[number, number]>centroid.coordinates);
			}
		}

		// text points
		const length = geometry.getCoordinates().length;
		if (length > 2) {
			geometry.forEachSegment((start, end) => {
				const lineString = new LineString([start, end]);
				const centroid = getPointByGeometry(<any>{
					type: lineString.getType(),
					coordinates: lineString.getCoordinates()
				});
				const segmentLengthText = this.formatLength(lineString, projection);
				const singlePointLengthTextStyle = this.getSinglePointLengthTextStyle();
				singlePointLengthTextStyle.setText(segmentLengthText);
				styles.push(new Style({
					geometry: new Point(<[number, number]>centroid.coordinates),
					text: singlePointLengthTextStyle
				}));
			});
		}

		styles.push(new Style({
			geometry: allLinePoint,
			text: this.allLengthTextStyle
		}));
		return styles;
	}


/**
	 * Format length output.
	 * @param line The line.
	 * @param projection The Projection.
	 */
formatLength(line, projection): string {
		const length = Sphere.getLength(line, { projection: projection });
		let output;
		if (length >= 1000) {
			output = (Math.round(length / 1000 * 100) / 100) +
				' ' + 'km';
		} else {
			output = (Math.round(length * 100) / 100) +
				' ' + 'm';
		}
		return output;
	}


({
  hasEditTag,
  hasAddSelectedArticle,
  hasManageCommunity,
  hasTagLeave,

  openTagAddSelectedArticlesDialog,
  openTagDialog,
  openTagEditorDialog,
  openTagLeaveDialog,
}: BaseDropdownActionsProps) => {
  const { lang } = useContext(LanguageContext)

  const Content = ({ isInDropdown }: { isInDropdown?: boolean }) => (
    <Menu width={isInDropdown ? 'sm' : undefined}>
      {hasEditTag && (
        <Menu.Item onClick={openTagDialog}>
          <TextIcon icon={<IconEdit16 size="md" />} size="md" spacing="base">
            <Translate id="editTag" />
          </TextIcon>
        </Menu.Item>


({ isInDropdown }: { isInDropdown?: boolean }) => (
    <Menu width={isInDropdown ? 'sm' : undefined}>
      {hasEditTag && (
        <Menu.Item onClick


(props: DropdownActionsProps) => {
  const viewer = useContext(ViewerContext)
  const { lang } = useContext(LanguageContext)
  const { tag } = props

  /**
   * Data
   */
  const [add, { loading }] = useMutation<AddArticlesTags>(ADD_ARTICLES_TAGS)
  const addArticlesToTag =
    (selected: boolean) => async (articles: SearchSelectNode[]) => {
      const articleIds = articles.map((article) => article.id)

      await add({
        variables: { id: tag.id, articles: articleIds, selected },
        update: (cache, { data }) => {
          if (selected) {
            const newCount = data?.addArticlesTags?.articles?.totalCount || 0
            const oldCount = tag.articles.totalCount || 0
            updateTagArticlesCount({
              cache,
              id: tag.id,
              count: newCount - oldCount,
              type: 'increment',
            })
          }
        },
      })

      window.dispatchEvent(
        new CustomEvent(ADD_TOAST, {
          detail: {
            color: 'green',
            content: translate({ id: 'addedArticleTag', lang }),
            duration: 2000,
          },
        })
      )

      window.dispatchEvent(
        new CustomEvent(REFETCH_TAG_DETAIL_ARTICLES, {
          detail: {
            event: 'add',
            differences: articles.length,
          },
        })
      )
    }

  const forbid = () => {
    window.dispatchEvent(
      new CustomEvent(ADD_TOAST, {
        detail: {
          color: 'red',
          content: <Translate id="FORBIDDEN_BY_STATE" />,
        },
      })
    )
    return
  }

  const controls = {
    hasEditTag: props.isOwner,
    hasAddSelectedArticle: props.isMaintainer,
    hasManageCommunity: props.isOwner,
    hasTagLeave: props.isOwner || props.isEditor,
  }

  if (_isEmpty(_pickBy(controls))) {
    return null
  }

  return (
    <TagDialog {...props.tag}>
      {({ openDialog: openTagDialog })


(selected: boolean) => async (articles: SearchSelectNode[]) => {
      const articleIds = articles.map((article) => article.id)

      await add({
        variables: { id: tag.id, articles: articleIds, selected },
        update: (cache, { data }) => {
          if (selected) {
            const newCount = data?.addArticlesTags?.articles?.totalCount || 0
            const oldCount = tag.articles.totalCount || 0
            updateTagArticlesCount({
              cache,
              id: tag.id,
              count: newCount - oldCount,
              type: 'increment',
            })
          }
        },
      })

      window.dispatchEvent(
        new CustomEvent(ADD_TOAST, {
          detail: {
            color: 'green',
            content: translate({ id: 'addedArticleTag', lang }),
            duration: 2000,
          },
        })
      )

      window.dispatchEvent(
        new CustomEvent(REFETCH_TAG_DETAIL_ARTICLES, {
          detail: {
            event: 'add',
            differences: articles.length,
          },
        })
      )
    }


async (articles: SearchSelectNode[]) => {
      const articleIds = articles.map((article) => article.id)

      await add({
        variables: { id: tag.id, articles: articleIds, selected },
        update: (cache, { data }) => {
          if (selected) {
            const newCount = data?.addArticlesTags?.articles?.totalCount || 0
            const oldCount = tag.articles.totalCount || 0
            updateTagArticlesCount({
              cache,
              id: tag.id,
              count: newCount - oldCount,
              type: 'increment',
            })
          }
        },
      })

      window.dispatchEvent(
        new CustomEvent(ADD_TOAST, {
          detail: {
            color: 'green',
            content: translate({ id: 'addedArticleTag', lang }),
            duration: 2000,
          },
        })
      )

      window.dispatchEvent(
        new CustomEvent(REFETCH_TAG_DETAIL_ARTICLES, {
          detail: {
            event: 'add',
            differences: articles.length,
          },
        })
      )
    }


(article) => article.id


(cache, { data }) => {
          if (selected) {
            const newCount = data?.addArticlesTags?.articles?.totalCount || 0
            const oldCount = tag.articles.totalCount || 0
            updateTagArticlesCount({
              cache,
              id: tag.id,
              count: newCount - oldCount,
              type: 'increment',
            })
          }
        }


() => {
    window.dispatchEvent(
      new CustomEvent(ADD_TOAST, {
        detail: {
          color: 'red',
          content: <Translate id="FORBIDDEN_BY_STATE" />,
        },
      })
    )
    return
  }


interface DropdownActionsProps {
  isOwner: boolean
  isEditor: boolean
  isMaintainer: boolean
  tag: TagDetailPublic_node_Tag
}


interface DialogProps {
  openTagAddSelectedArticlesDialog: () => void
  openTagDialog: () => void
  openTagEditorDialog: () => void
  openTagLeaveDialog: () => void
}


interface Controls {
  hasEditTag: boolean
  hasAddSelectedArticle: boolean
  hasManageCommunity: boolean
  hasTagLeave: boolean
}


type BaseDropdownActionsProps = DropdownActionsProps & DialogProps & Controls


addArticlesToTag(true)


@Component({
	selector: 'amplify-auth-forgot-password-ionic',
	template,
})
export class ForgotPasswordComponentIonic extends ForgotPasswordComponentCore {
	constructor(
		@Inject(AmplifyService) protected amplifyService: AmplifyService
	) {
		super(amplifyService);
	}

	onCodeChange(val) {
		this.country_code = val;
	}

	onNumberChange(val) {
		this.local_phone_number = val;
	}

	setUsername(username: string) {
		this.username = username;
	}

	setEmail(email: string) {
		this.email = email;
	}
}


onCodeChange(val) {
		this.country_code = val;
	}


onNumberChange(val) {
		this.local_phone_number = val;
	}


setUsername(username: string) {
		this.username = username;
	}


setEmail(email: string) {
		this.email = email;
	}


result => {

      this.events = [];
      this.reload();

    }


(res: any) => {

        if (res != null) {

          for (let index = 0; index < Object.keys(res).length; index++) {

            if (res[index].comentarios == "Dieta") {
              this.events.push({
                title: res[index].comentarios,
                date: res[index].fecha,
                color: "#fed9d5",
                textColor: "black",
                res: res[index],

                id: res[index].idDieta,
                groupId: res[index].idDia,
              });
            } else if (res[index].comentarios == "Rutina") {
              this.events.push({
                title: res[index].comentarios,
                date: res[index].fecha,
                color: "#dae5fd",
                textColor: "black",
                res: res[index],
                id: res[index].idRutina,
                groupId: res[index].idDia,
              });
            } else if (res[index].comentarios == "Comentarios") {
              this.events.push({
                title: res[index].comentarios,
                date: res[index].fecha,
                color: "#e7f5d0",
                textColor: "black",
                res: res[index],
                id: res[index].idCalendario,
                groupId: res[index].idDia,
              });
            }
          }
        }

        if (this._servicio.getIdioma() == 'es') {
          this.calendarOptions = {

            locale: esLocale,
            initialView: "dayGridMonth",
            dateClick: this.openDialog.bind(this),
            eventClick: this.openDialogInfo.bind(this),
            events: this.events,

          };

        } else {
          this.calendarOptions = {

            initialView: "dayGridMonth",
            dateClick: this.openDialog.bind(this),
            eventClick: this.openDialogInfo.bind(this),
            events: this.events,

          };

        }

      }