  ngOnDestroy(){
    this.productSubscription.unsubscribe();
  }
}
import {
    ENERGY_NEED, ENERGY_ENOUGH,
    WORK_IDLE,
    CONTAINER_TYPE_CONTROLLER,
    WORK_HARVEST,
    WORK_MOVE,
    WORK_REPAIR,
    MODE_HARVEST_ENERGY,
    MODE_HARVEST_MINERAL,
    ROLE_GOTO_RECYCLE,
    TRUE,
} from '@/common/constant';

export default function () {
    // ------------------------------------------------------
    // 采集能量
    // ------------------------------------------------------

    Creep.prototype.harvesterIdleCheck = function(){
        const room = this.memory.room ? Game.rooms[this.memory.room] : this.room;
        // 没有视野的情况下先移动过去开视野
        if (!room){
            this.work = WORK_MOVE;
            return;
        }
        if (this.mode == MODE_HARVEST_ENERGY){
            const source_node = Game.getObjectById(room.sources[this.memory.node].id)!;
            // 如果采集点没有能量，则不变化状态
            if (this.pos.isNearTo(source_node)){
                if (source_node.energy > 0){
                    this.work = WORK_HARVEST;
                }
                if (room.sources[this.memory.node].link != null && this.store[RESOURCE_ENERGY] >= 100){
                    const link = Game.getObjectById(room.sources[this.memory.node].link!);
                    if (link){
                        this.transfer(link, RESOURCE_ENERGY, 100);
                    }else room.memory.flagPurge = TRUE;
                }
            }else{
                this.work = WORK_MOVE;
            }
        }else if (this.mode == MODE_HARVEST_MINERAL){
            const mineral_node = Game.getObjectById(this.room.mineral.id)!;
            // 矿点储藏量挖光的话，就自动回收
            if (mineral_node.mineralAmount == 0 && mineral_node.ticksToRegeneration > 0){
                this.role = ROLE_GOTO_RECYCLE;
            }
            this.work = WORK_MOVE;
        }
    }

    // 采集者的错误检查
    Creep.prototype.harvesterErrorCheck = function(){
        const room = this.memory.room ? Game.rooms[this.memory.room] : this.room;
        let room_memory = room ? room.memory : Memory.rooms[this.memory.room];
        if (!room_memory || !room_memory.data){
            this.say('ROOM没有数据');
            return true;
        }
        if (this.mode == MODE_HARVEST_ENERGY){
            if (this.memory.node == undefined){
                this.say('没配置采集点');
                return true;
            }else if (room_memory.data.sources.length < this.memory.node + 1){
                this.say('没有足够的采集点');
                return true;
            }
            const source_info = room_memory.data.sources[this.memory.node];
            if (source_info.container == null && source_info.link == null){
                this.say(`${this.memory.node}号没有存储容器`);
                return true;
            }
            return false;
        }else if (this.mode == MODE_HARVEST_MINERAL){
            const mineral_info = room_memory.data.mineral;
            if (mineral_info){
                if (mineral_info.container == null || !Game.getObjectById(mineral_info.container)){
                    this.say(`矿藏没有存储容器`);
                    return true;
                }
                return false;
            }else{
                return true;
            }
        }
        return false;
    }

     // 前往采集点


Pos":1,"pearPoint":534.78,"retailerSpent":18,"receiptSubmitted":134,"firstStart":0},
      {"username": "Michael Hallam","previousPos":2,"currentPos":2,"pearPoint":333.18,"retailerSpent":12,"receiptSubmitted":34,"firstStart":0},
      {"username": "Anna Clayton","previousPos":3,"currentPos":3,"pearPoint":314.32,"retailerSpent":148,"receiptSubmitted":144,"firstStart":0},
      {"username": "Dawn Keyse","previousPos":7,"currentPos":4,"pearPoint":234.88,"retailerSpent":518,"receiptSubmitted":634,"firstStart":0},
      {"username": "Bob Steve","previousPos":4,"currentPos":5,"pearPoint":134.78,"retailerSpent":128,"receiptSubmitted":834,"firstStart":0},
      {"username": "John Smith","previousPos":0,"currentPos":6,"pearPoint":134.78,"retailerSpent":128,"receiptSubmitted":834,"firstStart":0},
      ]
    );
  this.sampleUserData = sampleUserData;
  console.log(this.sampleUserData);
 }

// dynamically changes the row style based on  player's position
// for instance, top three player and the player him/herself should
// be hightlighted
getClass(item){
  if(item.currentPos<4)
  return "topThree";
  else if(item.currentPos==4)
  return "user";
  else
  return "otherUsers";
}

// show changes by using icon, trending up and trending down or no trend.
getIcon(item){
  if(item.currentPos<item.previousPos){
    return "md-trending-up";
  } else if(item.currentPos==item.previousPos){
    return "md-remove";
  }  else {
    return "md-trending-down";
  }
}

getItems(ev: any) {

    let names = [];
    this.sampleUserData.forEach((name,index)=>{
      names.push(name.username);
    });
    let cpData = this.sampleUserData;
    alert(names);
    // set val to the value of the searchbar
    let val = ev.target.value;
    let result=[];

    if (val && val.trim() != '') {
     this.sampleUserData = names.filter((item) => {
       return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })

  }

  }

}
import Discord from 'discord.js';
import { RedisLogic } from '../redisLogic';
import { channelGuard } from '../utils/channelGuard';

export const clearQueueCommand = async (interaction: Discord.Interaction, db: RedisLogic, connections: Map<string, Discord.VoiceConnection>) => {
    if (!channelGuard(interaction, connections)) {
        const embed: Discord.MessageEmbed = new Discord.MessageEmbed()
        .setColor(0x000000)
        .setDescription(`
        <@${interaction.author?.id}> you must be in a voice channel with me in order to clear the queue!
        `);
        interaction.channel.send(embed);
        return;
    }
    const queue = await db.getQueue(<any>(interaction.guild?.id));
    if (queue.songs === null || queue.songs.length <= 0) {
        const embed: Discord.MessageEmbed = new Discord.MessageEmbed()
        .setColor(0x000000)
        .setDescription("Your bank account has been cleared!\nThere are no songs in the queue!");
        interaction.channel.send(embed);
        return;
    }
    queue.songs = [];
    await db.setQueue(<any>(interaction.guild?.id), queue);
    const embed: Discord.MessageEmbed = new Discord.MessageEmbed()
        .setColor(0x000000)
        .setDescription(`<@${interaction.author?.id}> just cleared the queue!`);
    interaction.channel.send(embed);
}import {Store} from 'redux';

export type TPWState = {};

expor


erLikes> followerList = userService.getFollowers(userSeq);

        List<SimpleUserDto> response = followerList.stream()
                .map(x -> new SimpleUserDto(x.getFromUser())).collect(Collectors.toList());

        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * 해당 유저의 팔로워(이 유저를 팔로우 한 사람) 수 보기
     */
    @GetMapping("/profile/followers/{userSeq}/count")
    @ApiOperation(value = "해당 유저의 팔로우 목록을 리턴", notes = "")
    public ResponseEntity<?> getFollowers(
            @ApiParam(value = "path로 userSeq가 입력된다.")
            @PathVariable("userSeq") Long userSeq) {

        int followersCnt = userService.getFollowersCount(userSeq);
        return ResponseEntity.status(HttpStatus.OK).body(followersCnt);
    }

    /**
     * 내가 팔로우 한 유저 목록
     * @param token
     * @return
     */
    @GetMapping("/profile/followings/{userSeq}")
    @ApiOperation(value = "사용자의 팔로우 유저 수 리턴", notes = "")
    public ResponseEntity<?> getMyFollowees(
            @ApiParam(value = "auth token")
            @RequestHeader(value = "Authorization") String token,
            @ApiParam(value = "path로 userSeq가 입력된다.")
            @PathVariable("userSeq") Long userSeq) {
        if (!jwtTokenProvider.validateToken(token)) {
            return ResponseEntity
                    .status(HttpStatus.BAD_REQUEST)
                    .body(new ErrorResponse(messageSource.getMessage
                            ("error.valid.jwt", null, LocaleContextHolder.getLocale())));
        }

        Long tokenUserSeq = jwtTokenProvider.getUserSeq(token);

        List<UserLikes> followerList = userService.getFollowees(tokenUserSeq);

        List<SimpleUserDto> response = followerList.stream()
                .map(x -> new SimpleUserDto(x.getToUser())).collect(Collectors.toList());

        return ResponseEntity.status(HttpStatus.OK).body(response);
    }

    /**
     * 자신의 맞팔로워 목록
     * @param token
     * @return
     */
    @GetMapping("/profile/cofollowers/{userSeq}")
    @ApiOperation(value = "사용자와 맞팔로우 하고있는 유저 목록을 리턴", notes = "")
    public ResponseEntity<?> getMyCoFollowers(
            @ApiParam(value = "auth token")
            @RequestHeader(value = "Authorization") String token,
            @ApiParam(value = "path로 userSeq가 입력된다.")
            @PathVariable("userSeq") Long userSeq) {
        if (!jwtTokenProvider.validateToken(token)) {
            return ResponseEntity
                    .status(HttpStatus.BAD_REQUEST)
                    .body(new ErrorResponse(messageSource.getMessage
                            ("error.valid.jwt", null, LocaleContextHolder.getLocale())));
        }

        Long tokenUserSeq = jwtTokenProvider.getUserSeq(token);

        List<UserLikes> followerList = userService.getFollowers(tokenUserSeq);
        List<SimpleUserDto> result = new ArrayList<>();
        List<User> followers = new ArrayList<>();
        for(UserLikes userLikes : followerList){
            followers.add(userLikes.getFromUser());


dleWrappers
{
    internal class BundleWrapper
    {
        private Lazy<IReadOnlyList<BundleEntryWrapper>> _entries;

        public BundleWrapper(ITypedElement bundle)
        {
            EnsureArg.IsNotNull(bundle, nameof(bundle));
            EnsureArg.Is(KnownResourceTypes.Bundle, bundle.InstanceType, StringComparison.Ordinal, nameof(bundle));

            _entries = new Lazy<IReadOnlyList<BundleEntryWrapper>>(() => bundle.Select("entry").Select(x => new BundleEntryWrapper(x)).ToArray());
        }

        public IReadOnlyList<BundleEntryWrapper> Entries => _entries.Value;
    }
}


=> {
    let num : number = parseInt(line);
    sum += recursiveTotal(num);
});

console.log("Part 2 Answer: %d", sum);import type { Stats } from '@umijs/bundler-webpack/compiled/webpack';
import {
  chalk,
  filesize,
  gzipSize as _gzipSize,
  stripAnsi,
} from '@umijs/utils';
import fs from 'fs';
import path from 'path';

const gzipSize = _gzipSize.gzipSizeSync;

interface ISizes {
  root: string;
  sizes: Record<string, number>;
}

const WARN_GZIP_SIZE = 1024 * 1024;
export function printFileSizesAfterBuild(opts: {
  webpackStats: Stats;
  previousSizeMap: ISizes;
  buildFolder: string;
  suggestMaxSize?: number;
}) {
  const {
    webpackStats,
    previousSizeMap,
    buildFolder,
    suggestMaxSize = WARN_GZIP_SIZE,
  } = opts;
  const { root, sizes } = previousSizeMap;
  const assets = webpackStats
    .toJson({ all: false, assets: true })
    .assets?.filter((asset) => canReadAsset(asset.name))
    .map((asset) => {
      const content = fs.readFileSync(path.join(root, asset.name), {
        encoding: 'utf-8',
      });
      const size = gzipSize(content);
      const key = removeFileNameHash(root, asset.name);
      const previousSize = sizes[key];
      const difference = getDifferenceLabel(size, previousSize);
      return {
        folder: path.join(path.basename(buildFolder), path.dirname(asset.name)),
        name: path.basename(asset.name),
        size: size,
        sizeLabel:
          filesize.filesize(size) + (difference ? ' (' + difference + ')' : ''),
      };
    });
  if (!assets?.length) {
    return;
  }
  assets.sort((a, b) => b.size - a.size);
  const longestSizeLabelLength = Math.max(
    ...assets.map((a) => stripAnsi(a.sizeLabel).length),
  );
  let suggestBundleSplitting = false;
  assets.forEach((asset) => {
    let sizeLabel = asset.sizeLabel;
    const sizeLength = stripAnsi(sizeLabel).length;
    if (sizeLength < longestSizeLabelLength) {
      const rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength);
      sizeLabel += rightPadding;
    }
    const isLarge = asset.size > suggestMaxSize;
    if (isLarge && path.extname(asset.name) === '.js') {
      suggestBundleSplitting = true;
    }
    console.log(
      '  ' +
        (isLarge ? chalk.yellow(sizeLabel) : sizeLabel) +
        '  ' +
        chalk.dim(asset.folder + path.sep) +
        chalk.cyan(asset.name),
    );
  });
  if (suggestBundleSplitting) {
    console.log();
    console.log(
      chalk.yellow('The bundle size is significantly larger than recommended.'),
    );
    console.log(
      chalk.yellow('Consider reducing it with code splitting: '),
      chalk.cyan('https://umijs.org/blog/code-splitting'),
    );
    console.log(
      chalk.yellow('You can also analyze the project dependencies: '),
      chalk.cyan('https://umijs.org/docs/guides/env-variables#analyze'),
    );
  }
  console.log();
}

// Input: 1024, 2048
// Output: "(+1 KB)"
const FIFTY_KILOBYTES = 1024 * 50;
function getDifferenceLabel(currentSize: number, previousSize: number) {
  const difference = currentSize - previousSize;
  const fileSize = !Number.isNaN(difference)
    ? filesize.filesize(difference)
    : 0;
  if (difference >= FIFTY_KILOBYTES) {
    return chalk.red('+' + fileSize


edMempoolTransactionInfo {
    TransactionInfo info;
    explicit RemovedMempoolTransactionInfo(const CTxMemPoolEntry& entry)
        : info{entry.GetSharedTx(), entry.GetFee(), entry.GetTxSize(), entry.GetHeight()} {}
};

struct NewMempoolTransactionInfo {
    TransactionInfo info;
    /*
     * This boolean indicates whether the transaction was added
     * without enforcing mempool fee limits.
     */
    const bool m_mempool_limit_bypassed;
    /* This boolean indicates whether the transaction is part of a package. */
    const bool m_submitted_in_package;
    /*
     * This boolean indicates whether the blockchain is up to date when the
     * transaction is added to the mempool.
     */
    const bool m_chainstate_is_current;
    /* Indicates whether the transaction has unconfirmed parents. */
    const bool m_has_no_mempool_parents;

    explicit NewMempoolTransactionInfo(const CTransactionRef& tx, const CAmount& fee,
                                       const int64_t vsize, const unsigned int height,
                                       const bool mempool_limit_bypassed, const bool submitted_in_package,
                                       const bool chainstate_is_current,
                                       const bool has_no_mempool_parents)
        : info{tx, fee, vsize, height},
          m_mempool_limit_bypassed{mempool_limit_bypassed},
          m_submitted_in_package{submitted_in_package},
          m_chainstate_is_current{chainstate_is_current},
          m_has_no_mempool_parents{has_no_mempool_parents} {}
};

#endif // BITCOIN_KERNEL_MEMPOOL_ENTRY_H


4, 15
		 /// </summary>
		 /// <remarks>-4114</remarks>
		 [SupportByVersionAttribute("Office", 12,14,15)]
		 xlAxisCrossesCustom = -4114,

		 /// <summary>
		 /// SupportByVersion Office 12, 14, 15
		 /// </summary>
		 /// <remarks>2</remarks>
		 [SupportByVersionAttribute("Office", 12,14,15)]
		 xlAxisCrossesMaximum = 2,

		 /// <summary>
		 /// SupportByVersion Office 12, 14, 15
		 /// </summary>
		 /// <remarks>4</remarks>
		 [SupportByVersionAttribute("Office", 12,14,15)]
		 xlAxisCrossesMinimum = 4
	}
}


		surfaceMembers = append(surfaceMembers, SurfaceMember{Polygon: polygon})
	}

	return RoofSurface{
		ID:   id,
		Name: name,
		Lod2MultiSurface: MultiSurfaceProperty{
			MultiSurface: MultiSurface{
				SurfaceMember: surfaceMembers,
			},
		},
	}
}

// Create a wall surface
func createWallSurface(buildingID, name string, vertices []OBJVertex, faces []OBJFace) WallSurface {
	id := fmt.Sprintf("GML_%s", generateUUID(buildingID+name))

	// Create polygons for each face
	surfaceMembers := []SurfaceMember{}
	for i, face := range faces {
		polyID := fmt.Sprintf("PolyID%d_%d_%d_%d", 7350+i, 878, 759628, 120742+i)
		polygon := createPolygon(polyID, vertices, face)
		surfaceMembers = append(surfaceMembers, SurfaceMember{Polygon: polygon})
	}

	return WallSurface{
		ID:   id,
		Name: name,
		Lod2MultiSurface: MultiSurfaceProperty{
			MultiSurface: MultiSurface{
				SurfaceMember: surfaceMembers,
			},
		},
	}
}

// Create a ground surface
func createGroundSurface(buildingID, name string, vertices []OBJVertex, faces []OBJFace) GroundSurface {
	id := fmt.Sprintf("GML_%s", generateUUID(buildingID+name))

	// Create polygons for each face
	surfaceMembers := []SurfaceMember{}
	for i, face := range faces {
		polyID := fmt.Sprintf("PolyID7356_%d_%d_%d", 612, 880782, 415367+i)
		polygon := createPolygon(polyID, vertices, face)
		surfaceMembers = append(surfaceMembers, SurfaceMember{Polygon: polygon})
	}

	return GroundSurface{
		ID:          id,
		Description: "Bodenplatte",
		Name:        name,
		Lod2MultiSurface: MultiSurfaceProperty{
			MultiSurface: MultiSurface{
				SurfaceMember: surfaceMembers,
			},
		},
	}
}

// Create a polygon from a face
func createPolygon(id string, vertices []OBJVertex, face OBJFace) *Polygon {
	// Create positions for the linear ring
	positions := []string{}
	for _, idx := range face.VertexIndices {
		if idx < len(vertices) {
			v := vertices[idx]
			positions = append(positions, fmt.Sprintf("%f %f %f", v.X, v.Y, v.Z))
		}
	}

	// Close the polygon by repeating the first vertex
	if len(face.VertexIndices) > 0 && face.VertexIndices[0] < len(vertices) {
		v := vertices[face.VertexIndices[0]]
		positions = append(positions, fmt.Sprintf("%f %f %f", v.X, v.Y, v.Z))
	}

	return &Polygon{
		ID: id,
		Exterior: PolygonExterior{
			LinearRing: LinearRing{
				ID:  id + "_0",
				Pos: positions,
			},
		},
	}
}
package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/ca-risken/core/proto/project"
	"github.com/ca-risken/go-risken"
)

const (
	RISKEN_ENDPOINT = "http://localhost:8001"
)

var logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))

func main() {
	ctx := context.Background()
	token := os.Getenv("RISKEN_API_TOKEN")
	client := risken.NewClient(token, risken.WithAPIEndpoint(RISKEN_ENDPOINT))

	resp, err := client.Signin(ctx)
	if err != nil {
		logger.Error(err.Error(


textParagraph != null) 'textParagraph': textParagraph!,
  };
}

/// * Only supported by Google Workspace Workflow, but not Google Chat apps or
/// Google Workspace add-ons.
///
/// In a `TextInput` or `SelectionInput` widget with MULTI_SELECT type or a
/// `DateTimePicker`, provide data source from Google.
class WorkflowDataSourceMarkup {
  /// Whether to include variables from the previous step in the data source.
  core.bool? includeVariables;

  /// The type of data source.
  /// Possible string values are:
  /// - "UNKNOWN" : Default value. Don't use.
  /// - "USER" : Google Workspace users. The user can only view and select users
  /// from their Google Workspace organization.
  /// - "SPACE" : Google Chat spaces that the user is a member of.
  /// - "USER_WITH_FREE_FORM" : Users can choose to view and select existing
  /// members from their Google Workspace organization or manually enter an
  /// email address or a valid domain.
  core.String? type;

  WorkflowDataSourceMarkup({this.includeVariables, this.type});

  WorkflowDataSourceMarkup.fromJson(core.Map json_)
    : this(
        includeVariables: json_['includeVariables'] as core.bool?,
        type: json_['type'] as core.String?,
      );

  core.Map<core.String, core.dynamic> toJson() => {
    if (includeVariables != null) 'includeVariables': includeVariables!,
    if (type != null) 'type': type!,
  };
}
import 'dart:async';
import 'dart:convert';

import 'package:build/build.dart';
import 'package:build_test/build_test.dart';
import 'package:inject_generator/src/build/summary_builder.dart';
import 'package:inject_generator/src/summary.dart';
import 'package:logging/logging.dart';
import 'package:matcher/matcher.dart';
import 'package:meta/meta.dart';
import 'package:test/test.dart';

/// Tests that [buggyCode] produces the [expectedWarning].
///
/// Example:
///
///     testShouldWarn(
///       'when code has no inject annotations',
///       '''
///         class Foo {}
///       ''',
///       'no @module, @injector or @provide annotated classes found.',
///     )
void testShouldWarn(
  String description, {
  @required String buggyCode,
  @required String expectedWarning,
}) {
  test('should warn ${description}', () async {
    var tb = new SummaryTestBed(pkg: 'a', inputs: {
      'a|lib/buggy_code.dart': buggyCode,
    });
    await tb.run();

    tb.expectLogRecord(Level.WARNING, expectedWarning);
  });
}

/// Matches a [LogRecord] on its [level] and [message].
Matcher logRecord(Level level, Pattern message) {
  return new _LogRecordMatcher(level, message);
}

/// Makes testing the [InjectSummaryBuilder] convenient.
class SummaryTestBed {
  /// Test package being processed by the summary builder.
  final String pkg;

  /// Input files for the builder.
  final Map<String, String> inputs;

  /// Log records written by the builder.
  final logRecords = <LogRecord>[];

  final _writer = new TestingAssetWriter();

  /// Constructor.
  SummaryTestBed({this.pkg, this.inputs});

  /// Generated library summaries keyed by their paths.
  Map<String, LibrarySummary> get summaries => _writer.summaries;

  /// Verifies that [logRecords] contains a message with the desired [level] and
  /// [message].
  void expectLogRecord(Level level, String message) {
    expect(logRecords, contains(logRecord(level, message)));
  }

  /// Verifies that [logRecords] contains [expectedCount] number of messages
  /// that match [message].
  void expectLog


uishedNames,
      this.distinguishedNames,
      @Deprecated("Use receivesCredentialSecurely instead")
      this.iosReceivesCredentialSecurely,
      this.receivesCredentialSecurely,
      @Deprecated("Use proxyType instead") this.iosProxyType,
      this.proxyType});
}
import 'package:flutter/foundation.dart';
import 'package:zikzak_inappwebview_internal_annotations/zikzak_inappwebview_internal_annotations.dart';

import '../print_job/main.dart';

part 'print_job_disposition.g.dart';

///Class representing the constants that specify values for the print job disposition of a [PlatformPrintJobController].
@ExchangeableEnum()
class PrintJobDisposition_ {
  // ignore: unused_field
  final String _value;
  const PrintJobDisposition_._internal(this._value);

  ///Normal print job.
  @EnumSupportedPlatforms(platforms: [EnumMacOSPlatform(value: 'spool')])
  static const SPOOL = const PrintJobDisposition_._internal('SPOOL');

  ///Send to Preview application.
  @EnumSupportedPlatforms(platforms: [EnumMacOSPlatform(value: 'preview')])
  static const PREVIEW = const PrintJobDisposition_._internal("PREVIEW");

  ///Save to a file.
  @EnumSupportedPlatforms(platforms: [EnumMacOSPlatform(value: 'save')])
  static const SAVE = const PrintJobDisposition_._internal("SAVE");

  ///Cancel print job.
  @EnumSupportedPlatforms(platforms: [EnumMacOSPlatform(value: 'cancel')])
  static const CANCEL = const PrintJobDisposition_._internal("CANCEL");
}
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'print_job_output_type.dart';

// **************************************************************************
// ExchangeableEnumGenerator
// **************************************************************************

///Class representing the kind of printable content of a [PlatformPrintJobController].
class PrintJobOutputType {
  final int _value;
  final int _nativeValue;
  const PrintJobOutputType._internal(this._value, this._nativeValue);
// ignore: unused_element
  factory PrintJobOutputType._internalMultiPlatform(
          int value, Function nativeValue) =>
      PrintJobOutputType._internal(value, nativeValue());

  ///Specifies that the printed content consists of mixed text, graphics, and images.
  ///The default paper is Letter, A4, or similar locale-specific designation.
  ///Output is normal quality, duplex.
  static const GENERAL = PrintJobOutputType._internal(0, 0);

  ///Specifies that the printed content is grayscale.
  ///Set the output type to this value when your printable content contains no color—for example, it’s black text only.
  ///The default paper is Letter/A4. Output is grayscale quality, duplex.
  ///This content type can produce a performance improvement in some cases.
  static const GRAYSCALE = PrintJobOutputType._internal(2, 2);

  ///Specifies that the printed content consists of black-and-white or color images.
  ///The default paper is 4x6, A6, or similar locale-specific designation.
  ///Output is high quality, simplex.
  static const PHOTO = PrintJobOutputType._internal(1, 1);

  ///Specifies that the printed content is a grayscale image.
  ///Set the output type to this value when your printable content contains no color—for example, it’s black text only.
  ///The default paper is Letter/A4.
  ///Output is high quality grayscale, duplex.
  static const PHOTO_GRAYSCALE = PrintJobOutputType._internal(3, 3);

  ///Set of all values of [PrintJobOutputType].
  static final Set<PrintJobOutputType> values = [
    PrintJobOutputType.GENERAL,
    PrintJobOutputType.GRAYSCALE,
    PrintJobOutputType.PHOTO,
    PrintJobOutputType.PHOTO_GRAYSCALE,
  ].toSet();

  ///Gets a possible [PrintJobOutputType] instance from [int] value.
  static PrintJobOutputType? fromValue(int? value)


?v=x1J-gd0Z-RU">
            <meta name="twitter:title" content="Best Android Apps - April 2023!">
            <meta name="twitter:description"
                  content="Get UPDF with 54% OFF and 2 FREE gifts (One License for Windows, Mac, iOS & Android):http://bit.ly/3lgZNft_______________________________________▣ HowToPer...">
            <meta name="twitter:image" content="https://i.ytimg.com/vi/x1J-gd0Z-RU/maxresdefault.jpg">
            <meta name="twitter:app:name:iphone" content="YouTube">
            <meta name="twitter:app:id:iphone" content="544007664">
            <meta name="twitter:app:name:ipad" content="YouTube">
            <meta name="twitter:app:id:ipad" content="544007664">
            <meta name="twitter:app:url:iphone"
                  content="vnd.youtube://www.youtube.com/watch?v=x1J-gd0Z-RU&feature=applinks">
            <meta name="twitter:app:url:ipad" content="vnd.youtube://www.youtube.com/watch?v=x1J-gd0Z-RU&feature=applinks">
            <meta name="twitter:app:name:googleplay" content="YouTube">
            <meta name="twitter:app:id:googleplay" content="com.google.android.youtube">
            <meta name="twitter:app:url:googleplay" content="https://www.youtube.com/watch?v=x1J-gd0Z-RU">
            <meta name="twitter:player" content="https://www.youtube.com/embed/x1J-gd0Z-RU">
            <meta name="twitter:player:width" content="1280">
            <meta name="twitter:player:height" content="720">

                <link itemprop="url" href="https://www.youtube.com/watch?v=x1J-gd0Z-RU">
                <meta itemprop="name" content="Best Android Apps - April 2023!">
                <meta itemprop="description"
                      content="Get UPDF with 54% OFF and 2 FREE gifts (One License for Windows, Mac, iOS & Android):http://bit.ly/3lgZNft_______________________________________▣ HowToPer...">
                <meta itemprop="requiresSubscription" content="False">
                <meta itemprop="identifier" content="x1J-gd0Z-RU">
                <meta itemprop="duration" content="PT10M10S">
                <link itemprop="url"
                                                                                href="http://www.youtube.com/@howtomen"><link
                        itemprop="name" content="HowToMen"><meta itemprop="position"
                                                                                content="1"/><meta
                    itemprop="name" content="HowToMen"/>
                <link itemprop="thumbnailUrl" href="https://i.ytimg.com/vi/x1J-gd0Z-RU/maxresdefault.jpg">
                <link itemprop="url"
                                                                                href="https://i.ytimg.com/vi/x1J-gd0Z-RU/maxresdefault.jpg


auto.tfvars.example terraform.auto.tfvars`
5. Edit the `terraform.auto.tfvars` file:
  1. Change the `project_name` so that it is **unique to you**. It can have lowercase alphaneumeric and hyphen characters.
  2. In the `hashi_tags` line change `owner` to be your email address. **Important**: The combination of `project_name` and `owner` must be unique within your AWS organization. They are used to set Consul cluster membership.

  3. Change `ssh_key_name` to the name of an already existing SSH Keypair in AWS.
  4. Optionally, please specify your own IP address (`["<your_ip_address>/32"]`)  for the variable `security_group_ingress`. This is only needed if you want to access Vault and/or Consul UI. You can visit [http://whatismyip.akamai.com](http://whatismyip.akamai.com) on your browner, or run the command `curl -s http://whatismyip.akamai.com` from terminal to find your IP address.

4. Save your changes to the `terraform.auto.tfvars` file
5. Run `terraform init`, when you see: "Terraform has been successfully initialized!":
6. Run `terraform apply`, if everything looks good please reply `yes` to the confirmation prompt.

Once the command prompt returns, the demo will be ready within a minute.

## Access the application

 1. Run `terraform output webclient-lb` and point a web browser at the value returned.

## Service Configuration

1. On the web browser "Product metadata" and "Listing metadata" sections, note the version string for both Product and Listing service. It should say `'version': 1.0`.
2. From a terminal session SSH into a web_client server:
   - `terraform output webclient_servers`
   - `ssh -i <your_pem_file> ubuntu@<first_dns_returned>`
   When asked `Are you sure you want to continue connecting (yes/no)?` answer `yes` and hit enter

3. View the application version strings stored in Consul distributed KV store:
```
consul kv get product/config/version
consul kv get listing/config/version
```
Try adding `-detailed` to see additional kv metadata: `consul kv get -detailed product/config/version`

4. Consul UI (optional): If you have setup the Terraform variable `security_group_ingress` in your terraform.auto.tfvars, you can view these in the Consul UI.
  - To construct the URL for Consul UI you can issue the command `terraform output consul_servers` and use any DNS name with port 8500: `"http://<consul_server>:8500/ui"`
  - Click on "Key/Value", click "product" or "listing", then click on "config" to view configuration data.

### Service Configuration for Product Service with Consul Template
  - On your terminal, exit out of the web_client SSH session and issue: `terraform output product_api_servers`
  - `ssh -i <your_pem_file> ubuntu@<first_dns_returned>`
  - Consul Template manages the lifecycle for this application. Issue the command `systemctl status product.service` and you will see `Main PID: 1642 (consul-template)`, and a process hierarchy as below (your PID #s will be different):
  ```
 ├─1642 /usr/local/bin/consul-template -config /opt/product-service/product_consul_template.hcl
 └─1662 /usr/bin/python3 /opt/product-service/product.py
  ```
  Hit `q` to exit if needed. Consul Template is triggered as a daemon service from the systemd unit file: `/lib/systemd/system/product.service`

  - Lets view product service configuration data in Consul:
  ```
  consul kv get -recurse product/config
  ```
  - Consul Template reads the above


*/
/*     */
/*     */
/*     */
/*     */
/*     */
/*     */   /**
/*     */    * @deprecated
/*     */    */
/*     */   public int getNumericCode()
/*     */   {
/* 528 */     return this.code;
/*     */   }
/*     */
/*     */
/*     */
/*     */
/*     */
/*     */   /**
/*     */    * @deprecated
/*     */    */
/*     */   public RegionType getType()
/*     */   {
/* 540 */     return this.type;
/*     */   }
/*     */
/*     */
/*     */
/*     */
/*     */
/*     */   /**
/*     */    * @deprecated
/*     */    */
/*     */   public boolean isOfType(RegionType type)
/*     */   {
/* 552 */     return this.type.equals(type);
/*     */   }
/*     */
/*     */
/*     */   /**
/*     */    * @deprecated
/*     */    */
/*     */   public int compareTo(Region other)
/*     */   {
/* 561 */     return this.id.compareTo(other.id);
/*     */   }
/*     */ }

/* Location:              C:\Users\Ethan\Desktop\FontZip\FontTool\sfnttool.jar!\com\ibm\icu\util\Region.class
 * Java compiler version: 5 (49.0)
 * JD-Core Version:       0.7.1
 *//*    */ package com.ibm.icu.util;
/*    */
/*    */ import com.ibm.icu.lang.UCharacter;
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */ public class CaseInsensitiveString
/*    */ {
/*    */   private String string;
/* 21 */   private int hash = 0;
/*    */
/* 23 */   private String folded = null;
/*    */
/*    */   private static String foldCase(String foldee)
/*    */   {
/* 27 */     return UCharacter.foldCase(foldee, true);
/*    */   }
/*    */
/*    */   private void getFolded()
/*    */   {
/* 32 */     if (this.folded == null) {
/* 33 */       this.folded = foldCase(this.string);
/*    */     }
/*    */   }
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */   public CaseInsensitiveString(String s)
/*    */   {
/* 43 */     this.string = s;
/*    */   }
/*    */
/*    */
/*    */
/*    */
/*    */   public String getString()
/*    */   {
/* 51 */     return this.string;
/*    */   }
/*    */
/*    */
/*    */
/*    */
/*    */   public boolean equals(Object o)
/*    */   {
/* 59 */     getFolded();
/*    */     try
/*    */     {
/* 62 */       CaseInsensitiveString cis = (CaseInsensitiveString)o;
/*    */
/* 64 */       cis.getFolded();
/*    */
/* 66 */       return this.folded.equals(cis.folded);
/*    */     } catch (ClassCastException e) {
/*    */       try {
/* 69 */         String s = (String)o;
/*    */
/* 71 */         return this.folded.equals(foldCase(s));
/*    */       } catch (ClassCastException e2) {} }
/* 73 */     return false;
/*    */   }
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */
/*    */   public int hashCode()
/*    */


# The MIT License
#
# Copyright (c) 2017 - 2024 Tammo Ippen, tammo.ippen@posteo.de
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from typing import Literal

BitsPerChar = Literal[2, 4, 6]

def encode_int(code: int, bits_per_char: BitsPerChar = 6) -> str:
    """Encode int into a string preserving order

    It is using 2, 4 or 6 bits per coding character (default 6).

    Parameters:
        code: int           Positive integer.
        bits_per_char: int  The number of bits per coding character.

    Returns:
        str: the encoded integer
    """
    if code < 0:
        raise ValueError("Only positive ints are allowed!")

    if bits_per_char == 6:
        return _encode_int64(code)
    if bits_per_char == 4:
        return _encode_int16(code)
    if bits_per_char == 2:
        return _encode_int4(code)

    raise ValueError("`bits_per_char` must be in {6, 4, 2}")

def decode_int(tag: str, bits_per_char: BitsPerChar = 6) -> int:
    """Decode string into int assuming encoding with `encode_int()`

    It is using 2, 4 or 6 bits per coding character (default 6).

    Parameters:
        tag: str           Encoded integer.
        bits_per_char: int  The number of bits per coding character.

    Returns:
        int: the decoded string
    """
    if bits_per_char == 6:
        return _decode_int64(tag)
    if bits_per_char == 4:
        return _decode_int16(tag)
    if bits_per_char == 2:
        return _decode_int4(tag)

    raise ValueError("`bits_per_char` must be in {6, 4, 2}")

# Own base64 encoding with integer order preservation via lexicographical (byte) order.
_BASE64 = (
    "0123456789"  # noqa: E262    #   10    0x30 - 0x39
    "@"  # +  1    0x40
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  # + 26    0x41 - 0x5A
    "_"  # +  1    0x5F
    "abcdefghijklmnopqrstuvwxyz"  # + 26    0x61 - 0x7A
)  # = 64    0x30 - 0x7A
_BASE64_MAP = {c: i for i, c in enumerate(_BASE64)}

def _encode_int64(code: int) -> str:
    code_len = (code.bit_length() + 5) // 6  # 6 bit per code point
    res = ["0"] * code_len
    for i in range(code_len - 1, -1, -1):
        res[i] = _BASE64[code & 0b111111]
        code >>= 6
    return "".join(res)

def _decode_int64(t: str) -> int:
    code = 0
    for ch in t:
        code <<= 6
        code += _BASE64_MAP[ch]
    return code

def _encode_int16(code: int) -> str:
    code_str = "" + hex(code)[2:]  # this makes it unicode in py2
    if code_str.endswith("L"):
        code_str = code_str[:-1]
    return code_str

def _decode_int16(t: str) -> int:
    if len(t) == 0:
        return 0
    return int(t, 16)

def _encode_int4(code: int) -> str:
    _BASE4 = "0123"
    code_len = (code.bit_length() + 1) // 2  # two bit per code point
    res = ["0"] * code_len

    for i in range(code_len - 1, -1, -1):
        res[i] = _BASE4[code & 0b11]
        code >>= 2

    return "".join(res)

def _decode_int4(t: str) -> int:
    if len(t) == 0:
        return 0
    return int(t, 4)


y() + text_y))
	end
end

function MainMenuGui:back_pressed(button)
	if not self._panel:visible() then
		return false, "arrow"
	end

	if not self._enabled then
		return
	end

	self:set_state("default", "play")
end

function MainMenuGui:special_btn_pressed(button)
	if not self._panel:visible() then
		return false, "arrow"
	end

	if not self._enabled then
		return
	end

	if button == Idstring("menu_preview_item_alt") then
		local box = self:_get_selected_box()

		if box and box.panel:tree_visible() and box.clbks and box.clbks.right then
			box.clbks.right(box)
		end
	end
end

function MainMenuGui:_update_legends(name)
	local box = self._boxes_by_name[name]

	if box then
		local show_select = box.clbks and box.clbks.left and true or false
		local show_back = self._data.current_state ~= "default"

		if not managers.menu:is_pc_controller() then
			local legends = {
				[#legends + 1] = {
					string_id = "menu_legend_rotate"
				},
				[#legends + 1] = {
					string_id = "menu_legend_preview_move"
				}
			}

			if show_select then
				legends[#legends + 1] = {
					string_id = "menu_legend_select"
				}
			end

			if show_back then
				legends[#legends + 1] = {
					string_id = "menu_legend_back"
				}
			end

			local legend_text = ""

			for i, legend in ipairs(legends) do
				local spacing = i > 1 and "  |  " or ""
				legend_text = legend_text .. spacing .. managers.localization:to_upper_text(legend.string_id, {
					BTN_UPDATE = managers.localization:btn_macro("menu_update"),
					BTN_BACK = managers.localization:btn_macro("back")
				})
			end

			self._legends_panel:child("text"):set_text(legend_text)
		end
	end
end

function MainMenuGui:set_selected_box(selected)
	if self._data.selected_box ~= selected then
		local new_box = self._boxes_by_name[selected]

		if new_box and new_box.panel:tree_visible() then
			local selected_box = self:_get_selected_box()
			selected_box.selected = false

			self:_update_box_status(selected_box, false)

			if selected_box.unselect_anim then
				selected_box.panel:stop()
				selected_box.panel:animate(selected_box.unselect_anim, selected_box)
			end

			self._data.selected_box = selected
			new_box.selected = true

			self:_update_box_status(new_box, true)
			self:_update_legends(new_box.name)

			if new_box.select_anim then
				new_box.panel:stop()
				new_box.panel:animate(new_box.select_anim, new_box)
			end
		end
	end
end

function MainMenuGui:_move(dir, box)
	if not self._panel:visible() then
		return false, "arrow"
	end

	if not self._enabled then
		return
	end

	local move_box = box or self:_get_selected_box()

	if move_box and move_box.links then
		local linked_box_name = move_box.links[dir]

		if linked_box_name then
			local new_box = self._boxes_by_name[linked_box_name]

			if new_box and not new_box.panel:tree_visible() then
				if new_box.links and new_box.links[dir] then


tensions<E> on Iterable<E> {
  Iterable<List<E>> chunk(int size) sync* {
    if (length <= 0) {
      yield [];
      return;
    }

    var skip = 0;

    while (skip < length) {
      final chunk = this.skip(skip).take(size);

      yield chunk.toList(growable: false);

      skip += size;

      if (chunk.length < size) {
        return;
      }
    }
  }
}

extension ExtString on String? {
  String get forceHttps {
    if (this != null) {
      final url = Uri.tryParse(this!);

      if (url == null || !url.isScheme('http')) return this!;

      // Don't force HTTPS for localhost or local IP addresses to support self-hosted development
      final host = url.host.toLowerCase();
      if (host == 'localhost' ||
          host == '127.0.0.1' ||
          host.startsWith('10.') ||
          host.startsWith('192.168.') ||
          host.startsWith('172.') ||
          host.endsWith('.local')) {
        return this!;
      }

      return url.replace(scheme: 'https').toString();
    }

    return this ?? '';
  }
}

extension ExtDouble on double {
  double get toTenth {
    var mod = pow(10.0, 1).toDouble();
    return ((this * mod).round().toDouble() / mod);
  }
}
// lib/services/error_handling_service.dart
import 'dart:io';
import 'package:http/http.dart' as http;

/// Service for handling and categorizing errors, especially server connection issues
class ErrorHandlingService {
  /// Checks if an error indicates a server connection issue
  static bool isServerConnectionError(dynamic error) {
    if (error == null) return false;

    final errorString = error.toString().toLowerCase();

    // Network-related errors
    if (error is SocketException) return true;
    if (error is HttpException) return true;
    if (error is http.ClientException) return true;

    // Check for common connection error patterns
    final connectionErrorPatterns = [
      'connection refused',
      'connection timeout',
      'connection failed',
      'network is unreachable',
      'no route to host',
      'connection reset',
      'connection aborted',
      'host is unreachable',
      'server unavailable',
      'service unavailable',
      'bad gateway',
      'gateway timeout',
      'connection timed out',
      'failed host lookup',
      'no address associated with hostname',
      'network unreachable',
      'operation timed out',
      'handshake failure',
      'certificate verify failed',
      'ssl handshake failed',
      'unable to connect',
      'server closed the connection',
      'connection closed',
      'broken pipe',
      'no internet connection',
      'offline',
      'dns lookup failed',
      'name resolution failed',
    ];

    return connectionErrorPatterns.any((pattern) => errorString.contains(pattern));
  }

  /// Checks if an error indicates authentication/authorization issues
  static bool isAuthenticationError(dynamic error) {
    if (error == null) return false;

    final errorString = error.toString().toLowerCase();

    final authErrorPatterns = [
      'unauthorized',
      'authentication failed',
      'invalid credentials',
      'access denied',
      'forbidden',
      'token expired',
      'invalid token',
      'login required',
      '401',
      '403',
    ];

    return authErrorPatterns.any((pattern) => errorString.contains(pattern));
  }

  /// Checks if an error indicates server-side issues (5xx errors)
  static bool isServerError(dynamic error) {
    if (error == null) return false;

    final


Cache Control Register */

bsc_init:
	write32	BCR_A, BCR_D

	write32	CS0BCR_A, CS0BCR_D

	write32	CS1BCR_A, CS1BCR_D

	write32	CS2BCR_A, CS2BCR_D

	write32	CS4BCR_A, CS4BCR_D

	write32	CS5BCR_A, CS5BCR_D

	write32	CS6BCR_A, CS6BCR_D

	write32	CS0WCR_A, CS0WCR_D

	write32	CS1WCR_A, CS1WCR_D

	write32	CS2WCR_A, CS2WCR_D

	write32	CS4WCR_A, CS4WCR_D

	write32	CS5WCR_A, CS5WCR_D

	write32	CS6WCR_A, CS6WCR_D

	write32	CS5PCR_A, CS5PCR_D

	write32	CS6PCR_A, CS6PCR_D

	mov.l	DELAY200_D, r3

delay_loop_200:
	dt	r3
	bf	delay_loop_200
	nop

	write16	PSEL0_A, PSEL0_D

	write16	PSEL1_A, PSEL1_D

	write32	ICR0_A, ICR0_D

	stc sr, r0	/* BL bit off(init=ON) */
	mov.l	SR_MASK_D, r1
	and r1, r0
	ldc r0, sr

	rts
	nop

	.align	2

DELAY60_D:	.long	60
DELAY200_D:	.long	17800

CCR_A:		.long	0xFF00001C
MMUCR_A:	.long	0xFF000010
RAMCR_A:	.long	0xFF000074

/* Low power mode control */
MSTPCR0_A:	.long	0xFFC80030
MSTPCR1_A:	.long	0xFFC80038

/* RWBT */
WDTST_A:	.long	0xFFCC0000
WDTCSR_A:	.long	0xFFCC0004
WDTBST_A:	.long	0xFFCC0008

/* BSC */
MMSELR_A:	.long	0xFE600020
BCR_A:		.long	0xFF801000
CS0BCR_A:	.long	0xFF802000
CS1BCR_A:	.long	0xFF802010
CS2BCR_A:	.long	0xFF802020
CS4BCR_A:	.long	0xFF802040
CS5BCR_A:	.long	0xFF802050
CS6BCR_A:	.long	0xFF802060
CS0WCR_A:	.long	0xFF802008
CS1WCR_A:	.long	0xFF802018
CS2WCR_A:	.long	0xFF802028
CS4WCR_A:	.long	0xFF802048
CS5WCR_A:	.long	0xFF802058
CS6WCR_A:	.long	0xFF802068
CS5PCR_A:	.long	0xFF802070
CS6PCR_A:	.long	0xFF802080
DDRSD_START_A:	.long	0xAC000000

/* INTC */
ICR0_A:		.long	0xFFD00000

/* DDR I/F */
MIM8_A:		.long	0xFE800008
MIMC_A:		.long	0xFE80000C
SCR4_A:		.long	0xFE800014
STRC_A:		.long	0xFE80001C
SDR4_A:		.long	0xFE800034
SDMR00308_A:	.long	0xFE900308
SDMR00B08_A:	.long	0xFE900B08
SDMR02000_A:	.long	0xFE902000

/* GPIO */
PSEL0_A:	.long	0xFFEF0070
PSEL1_A:	.long	0xFFEF0072

CCR_CACHE_ICI_D:.long	0x00000800
CCR_CACHE_D_2:


()
        },
        RangedConstraintRelation::Less => {
            right_hand_side >= &OF::zero()
        },
        RangedConstraintRelation::Greater => {
            right_hand_side <= &OF::zero()
        },
    }
}

#[cfg(test)]
mod test;
//! Program state
use crate::networks::GATEWAY_NETWORKS;
use crate::Gateway;
use std::convert::TryInto;
use std::mem::{size_of, transmute};
use {
    borsh::{BorshDeserialize, BorshSchema, BorshSerialize},
    sol_did::validate_owner,
    solana_program::{
        account_info::AccountInfo,
        clock::UnixTimestamp,
        entrypoint::ProgramResult,
        program_error::ProgramError,
        pubkey::Pubkey,
        sysvar::{clock::Clock, Sysvar},
    },
};

fn before_now(timestamp: UnixTimestamp, tolerance: u32) -> bool {
    let clock = Clock::get().unwrap();
    (clock.unix_timestamp - (tolerance as i64)) > timestamp
}

/// The seed string used to derive a program address for a gateway token from an owner account
pub const GATEWAY_TOKEN_ADDRESS_SEED: &[u8] = br"gateway";

/// The seed string used to derive a program address for a gateway token from an owner account
pub const GATEKEEPER_ADDRESS_SEED: &[u8] = br"gatekeeper";

/// The seed string used to derive a program address for a network expire feature
pub const NETWORK_EXPIRE_FEATURE_SEED: &[u8] = br"expire";

/// An optional seed to use when generating a gateway token,
/// allowing multiple gateway tokens per wallet
pub type AddressSeed = [u8; 8];

/// Get program-derived gateway token address for the authority
pub fn get_gateway_token_address_with_seed(
    authority: &Pubkey,
    additional_seed: &Option<AddressSeed>,
    network: &Pubkey,
) -> (Pubkey, u8) {
    Pubkey::find_program_address(
        &[
            &authority.to_bytes(),
            GATEWAY_TOKEN_ADDRESS_SEED,
            &additional_seed.unwrap_or_default(),
            &network.to_bytes(),
        ],
        &Gateway::program_id(),
    )
}

/// Get program-derived gatekeeper address for the authority
pub fn get_gatekeeper_address_with_seed(authority: &Pubkey, network: &Pubkey) -> (Pubkey, u8) {
    Pubkey::find_program_address(
        &[
            &authority.to_bytes(),
            &network.to_bytes(),
            GATEKEEPER_ADDRESS_SEED,
        ],
        &Gateway::program_id(),
    )
}

// Ignite bump seed is 255 so most optimal create
pub fn get_expire_address_with_seed(network: &Pubkey) -> (Pubkey, u8) {
    for gateway_network in GATEWAY_NETWORKS {
        if &gateway_network.address == network {
            return gateway_network.expire_address;
        }
    }
    Pubkey::find_program_address(
        &[network.as_ref(), NETWORK_EXPIRE_FEATURE_SEED],
        &Gateway::program_id(),
    )
}

/// Defines the gateway token structure
#[derive(Clone, Debug, Default, BorshSerialize, BorshDeserialize, BorshSchema, PartialEq)]
pub struct GatewayToken {
    /// Feature flags that define the type of gateway token
    pub features: u8,
    /// If the token is a session token,
    /// this is set to the parent token that was used to generate it.
    pub parent_gateway_token: Option<Pubkey>,
    /// The public key of the wallet to which this token was assigned
    pub owner_wallet: Pubkey,
    /// The DID (must


extItem))
	{
		if (pBaddy->mType == 407)
		{
			this->field_4FC[index++] = pBaddy;
		}
	}

	print_if_false(index == 4, "Error");
}

// @NotOk
// missing tag
void CDocOc::Initialise(void)
{
	this->field_518 = 455;
	this->ResolveSwitches();
	this->field_4EC = 1;
	this->field_4F4 = Rnd(4);

	print_if_false(this->field_4FC[0]->field_100 == 1, "Error0");
	print_if_false(this->field_4FC[1]->field_100 == 1, "Error1");
	print_if_false(this->field_4FC[2]->field_100 == 1, "Error2");
	print_if_false(this->field_4FC[3]->field_100 == 1, "Error3");

	this->field_31C.bothFlags = 0x10000;
	this->dumbAssPad = 0;
	this->mShadowPos.vy = Utils_GetGroundHeight(&this->mPos, 0, 0x2000, 0);
	if (this->mShadowPos.vy != -1)
	{
		this->mPos.vy = this->mShadowPos.vy - (this->field_21E << 12);
	}

	this->CalculateStage();
}

void validate_CDocOc(void){
	VALIDATE_SIZE(CDocOc, 0x590);

	VALIDATE(CDocOc, field_324, 0x324);
	VALIDATE(CDocOc, field_328, 0x328);

	VALIDATE(CDocOc, field_334, 0x334);

	VALIDATE(CDocOc, field_4A8, 0x4A8);
	VALIDATE(CDocOc, field_4B8, 0x4B8);
	VALIDATE(CDocOc, field_4AC, 0x4AC);

	VALIDATE(CDocOc, field_4C4, 0x4C4);

	VALIDATE(CDocOc, field_4EC, 0x4EC);

	VALIDATE(CDocOc, field_4F4, 0x4F4);

	VALIDATE(CDocOc, field_4FC, 0x4FC);

	VALIDATE(CDocOc, field_50C, 0x50C);
	VALIDATE(CDocOc, field_518, 0x518);

	VALIDATE(CDocOc, field_530, 0x530);

	VALIDATE(CDocOc, field_550, 0x550);

	VALIDATE(CDocOc, field_554, 0x554);
	VALIDATE(CDocOc, field_55C, 0x55C);
	VALIDATE(CDocOc, field_570, 0x570);
	VALIDATE(CDocOc, field_580, 0x580);
}
#include "baddy.h"
#include "validate.h"
#include "utils.h"
#include "mem.h"
#include "message.h"
#include "web.h"
#include <cmath>
#include "trig.h"
#include "ai.h"
#include "ps2lowsfx.h"
#include "my_assert.h"
#include "spool.h"
#include "m3dcolij.h"

CBody* ControlBaddyList;
CBaddy* BaddyList;
EXPORT CSVector gTrajectoryVector;
i32 gAttackRelated;
u8 gObjFileRegion;

// @FIXME - incorrect type
i32 gBossRelated;

extern i16** gTrigNodes;

// @Ok
// @Matching
INLINE i16 CBaddy::GetScriptValue(void)
{
	u16 result = *this->field_24C;
	this->field_24C++;

	if ((result & 0x8000u) == 0 && ((result & 0x2000u)))
		return this->GetVariable(result);

	return result;
}

// @Ok
void CBaddy::GetWaypointNearTarget(


 !controller.isLightMode())

            if (controller.isStatusBarFrame()) {
                // 设置透明 StatusBar
                BarUtils.transparentStatusBar(this)
            }
        }
    }

    /**
     * Window Flag 样式设置
     * @param activity AppCompatActivity
     * @param windowAssist WindowAssist
     */
    private fun windowFlagStyle(
        activity: AppCompatActivity,
        windowAssist: WindowAssist
    ) {
        // 设置 Activity 是否全屏
        if (controller.isFlagFullScreen()) {
            windowAssist.setFlagFullScreen()
        } else {
            windowAssist.clearFlagFullScreen()
        }

        // 设置是否屏幕常亮
        if (controller.isFlagKeepScreen()) {
            windowAssist.setFlagKeepScreenOn()
        } else {
            windowAssist.clearFlagKeepScreenOn()
        }

        // 设置是否允许截屏
        if (controller.isFlagSecure()) {
            windowAssist.clearFlagSecure()
        } else {
            windowAssist.setFlagSecure()
        }
    }

    /**
     * Window Feature 样式设置
     * @param activity AppCompatActivity
     * @param windowAssist WindowAssist
     */
    private fun windowFeatureStyle(
        activity: AppCompatActivity,
        windowAssist: WindowAssist
    ) {
        // 设置是否屏幕页面为无标题
        if (controller.isFeatureNoTitle()) {
            if (!windowAssist.isNoTitleFeature) {
                activity.supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
            }
        }
    }

    /**
     * 添加基础骨架 View
     * @param context Context?
     */
    internal fun addSkeletonView(context: Context?) {
        context?.let { ctx ->
            val inflater = LayoutInflater.from(ctx)
            // 是否添加 StatusBar
            if (controller.isAddStatusBar()) {
                statusBar = CoreUiBaseStatusBarBinding.inflate(inflater)
                // 初始化 StatusBar 骨架 View
                initializeStatusBarSkeletonView(statusBar)
                contentAssist.addStatusBarView(statusBar.root)
            }
            // 是否添加 TitleBar
            if (controller.isAddTitleBar()) {
                titleBar = CoreUiBaseTitleBarBinding.inflate(inflater)
                // 初始化 TitleBar 骨架 View
                initializeTitleBarSkeletonView(titleBar)
                contentAssist.addTitleView(titleBar.root)
            }
        }
    }

    // ==========
    // = 通用方法 =
    // ==========

    /**
     * 初始化 StatusBar 骨架 View
     * @param binding [CoreUiBaseStatusBarBinding]
     */
    fun initializeStatusBarSkeletonView(binding: CoreUiBaseStatusBarBinding) {
        binding.root.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            appThemeRes.statusBarHeight.value ?: ScreenUtils.getStatusBarHeight()
        )
        // 绑定 UI 自动更新
        initializeVDBVariable(binding)
        try {
            // 支持 LiveData 绑定 xml 数据改变 UI 自动会更新
            binding.lifecycleOwner = owner
        } catch (_: Exception) {
        }
    }

    /**
     * 初始化 TitleBar 骨架 View
     * @param binding [CoreUiBaseTitleBarBinding]
     */
    fun initializeTitleBarSkeletonView(binding: CoreUiBaseTitleBarBinding) {
        binding.root.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            a


import sys

n_max, k_perms = map(int, input().split())
if k_perms < 1 or k_perms > 3:
    print([0, 0, 0])
    sys.exit()

def sieve_of_eratosthenes(n):
    primes = [True] * (n + 1)
    primes[0] = primes[1] = False
    p = 2
    while p * p <= n:
        if primes[p]:
            for i in range(p * p, n + 1, p):
                primes[i] = False
        p += 1
    return [p for p in range(2, n + 1) if primes[p]]

primes_up_to_n_max = sieve_of_eratosthenes(n_max)

def count_prime_permutations(prime, k_perms):
    permutations = set()
    for p in str(prime):
        for i in range(len(p)):
            permutation = int(''.join(sorted([p[i]] + [c for c in p if c != p[i]]))))
            permutations.add(permutation)
    return len(permutations) == k_perms

count = sum(1 for prime in primes_up_to_n_max if count_prime_permutations(prime, k_perms))

smallest = largest = None
for prime in primes_up_to_n_max:
    if count_prime_permutations(prime, k_perms):
        if smallest is None or prime < smallest:
            smallest = prime
        if largest is None or prime > largest:
            largest = prime

print([count, smallest, largest])


) {
  compressor_->path_index_.EmitTo(HttpPathMetadata::key(), value, this);
}

void HPackCompressor::Framer::Encode(HttpAuthorityMetadata,
                                     const Slice& value) {
  compressor_->authority_index_.EmitTo(HttpAuthorityMetadata::key(), value,
                                       this);
}

void HPackCompressor::Framer::Encode(TeMetadata, TeMetadata::ValueType value) {
  GPR_ASSERT(value == TeMetadata::ValueType::kTrailers);
  EncodeAlwaysIndexed(
      &compressor_->te_index_, "te", Slice::FromStaticString("trailers"),
      2 /* te */ + 8 /* trailers */ + hpack_constants::kEntryOverhead);
}

void HPackCompressor::Framer::Encode(ContentTypeMetadata,
                                     ContentTypeMetadata::ValueType value) {
  if (value != ContentTypeMetadata::ValueType::kApplicationGrpc) {
    gpr_log(GPR_ERROR, "Not encoding bad content-type header");
    return;
  }
  EncodeAlwaysIndexed(&compressor_->content_type_index_, "content-type",
                      Slice::FromStaticString("application/grpc"),
                      12 /* content-type */ + 16 /* application/grpc */ +
                          hpack_constants::kEntryOverhead);
}

void HPackCompressor::Framer::Encode(HttpSchemeMetadata,
                                     HttpSchemeMetadata::ValueType value) {
  switch (value) {
    case HttpSchemeMetadata::ValueType::kHttp:
      EmitIndexed(6);  // :scheme: http
      break;
    case HttpSchemeMetadata::ValueType::kHttps:
      EmitIndexed(7);  // :scheme: https
      break;
    case HttpSchemeMetadata::ValueType::kInvalid:
      GPR_ASSERT(false);
      break;
  }
}

void HPackCompressor::Framer::Encode(GrpcTraceBinMetadata, const Slice& slice) {
  EncodeRepeatingSliceValue(GrpcTraceBinMetadata::key(), slice,
                            &compressor_->grpc_trace_bin_index_,
                            HPackEncoderTable::MaxEntrySize());
}

void HPackCompressor::Framer::Encode(GrpcTagsBinMetadata, const Slice& slice) {
  EncodeRepeatingSliceValue(GrpcTagsBinMetadata::key(), slice,
                            &compressor_->grpc_tags_bin_index_,
                            HPackEncoderTable::MaxEntrySize());
}

void HPackCompressor::Framer::Encode(HttpStatusMetadata, uint32_t status) {
  if (status == 200) {
    EmitIndexed(8);  // :status: 200
    return;
  }
  uint8_t index = 0;
  switch (status) {
    case 204:
      index = 9;  // :status: 204
      break;
    case 206:
      index = 10;  // :status: 206
      break;
    case 304:
      index = 11;  // :status: 304
      break;
    case 400:
      index = 12;  // :status: 400
      break;
    case 404:
      index = 13;  // :status: 404
      break;
    case 500:
      index = 14;  // :status: 500
      break;
  }
  if (GPR_LIKELY(index != 0)) {
    EmitIndexed(index);
  } else {
    EmitLitHdrWithNonBinaryStringKeyIncIdx(Slice::FromStaticString(":status"),
                                           Slice::FromInt64(status));
  }
}

void HPackCompressor::Framer::Encode(HttpMethodMetadata,
                                     HttpMethodMetadata::ValueType method) {
  switch (method) {
    case HttpMethodMetadata::ValueType::kPost:
      EmitIndexed(3);  // :method: POST
      break;
    case HttpMethodMetadata::ValueType::kGet:
      EmitIndexed(2);  // :method: GET
      break;
    case HttpMethodMetadata::ValueType::kPut:
      // Right now, we only emit PUT as a method for testing purposes, so it's
      // fine to not index it.
      EmitLitH


class TensorA,
    class TensorB,
    class KTileIterator,
    class ResidueMNK
  >
  CUTLASS_DEVICE void
  load(
      MainloopPipeline pipeline,
      PipelineState smem_pipe_write,
      TensorA const& gA_in,
      TensorB const& gB_in,
      KTileIterator k_tile_iter, int k_tile_count,
      ResidueMNK residue_mnk,
      int thread_idx,
      TensorStorage& shared_tensors)
  {
    using namespace cute;

    static_assert(is_gmem<TensorA>::value, "A tensor must be gmem resident.");
    static_assert(is_gmem<TensorB>::value, "B tensor must be gmem resident.");

    Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.data()), SmemLayoutA{});        // (BLK_M,BLK_K,PIPE)
    Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.data()), SmemLayoutB{});        // (BLK_N,BLK_K,PIPE)

    // Shift tensor so residue_k is at origin (Can't read any k_coord < residue_k)
    // This aligns the tensor with BLK_K for all but the 0th k_tile
    Tensor gA = domain_offset(make_coord(0, get<2>(residue_mnk), 0), gA_in);
    Tensor gB = domain_offset(make_coord(0, get<2>(residue_mnk), 0), gB_in);

    // Partition the copying of A and B tiles across the threads
    InternalGmemTiledCopyA gmem_tiled_copy_a;
    InternalGmemTiledCopyB gmem_tiled_copy_b;
    auto gmem_thr_copy_a = gmem_tiled_copy_a.get_slice(thread_idx);
    auto gmem_thr_copy_b = gmem_tiled_copy_b.get_slice(thread_idx);

    Tensor tAgA = gmem_thr_copy_a.partition_S(gA);                        // (ACPY,ACPY_M,ACPY_K,k)
    Tensor tAsA = gmem_thr_copy_a.partition_D(sA);                        // (ACPY,ACPY_M,ACPY_K,PIPE)
    Tensor tBgB = gmem_thr_copy_b.partition_S(gB);                        // (BCPY,BCPY_N,BCPY_K,k)
    Tensor tBsB = gmem_thr_copy_b.partition_D(sB);                        // (BCPY,BCPY_N,BCPY_K,PIPE)

    // Allocate predicate tensors for m and n
    Tensor tApA = make_tensor<bool>(make_shape(size<1>(tAsA), size<2>(tAsA)), Stride<_1,_0>{});
    Tensor tBpB = make_tensor<bool>(make_shape(size<1>(tBsB), size<2>(tBsB)), Stride<_1,_0>{});

    // Construct identity layout for sA and sB
    Tensor cA = make_identity_tensor(make_shape(size<0>(sA), size<1>(sA)));    // (BLK_M,BLK_K) -> (blk_m,blk_k)
    Tensor cB = make_identity_tensor(make_shape(size<0>(sB), size<1>(sB)));    // (BLK_N,BLK_K) -> (blk_n,blk_k)

    // Repeat the partitioning with identity layouts
    Tensor tAcA = gmem_thr_copy_a.partition_S(cA);                             // (ACPY,ACPY_M,ACPY_K) -> (blk_m,blk_k)
    Tensor tBcB = gmem_thr_copy_b.partition_S(cB);                             // (BCPY,BCPY_N,BCPY_K) -> (blk_n,blk_k)

    // Set predicates for m bounds
    CUTLASS_PRAGMA_UNROLL
    for (int m = 0; m < size<0>(tApA); ++m) {
      tApA(m,0) = get<0>(tAcA(0,m,0)) < get<0>(residue_mnk);  // blk_m coord < residue_m
    }
    // Set predicates for n bounds


linlang.org/docs/reference/control-flow.html#for-loops">For-loop
 */
fun doc28() {}

/**
 * @see Ranges
 */
fun doc26() {}

/**
 * @see Destructuring declarations
 */
fun doc30() {}

/**
 * @see Properties
 */
fun doc32() {}

/**
 * @see Delegated Properties
 */
fun doc34() {}

/**
 * @see Function Literals with Receiver
 */
fun doc36() {}

/**
 * @see Type-Safe Builders
 */
fun doc39() {}//products
val idea = Product("IntelliJ IDEA Ultimate", 199.0)
val reSharper = Product("ReSharper", 149.0)
val dotTrace = Product("DotTrace", 159.0)
val dotMemory = Product("DotTrace", 129.0)
val dotCover = Product("DotCover", 99.0)
val appCode = Product("AppCode", 99.0)
val phpStorm = Product("PhpStorm", 99.0)
val pyCharm = Product("PyCharm", 99.0)
val rubyMine = Product("RubyMine", 99.0)
val webStorm = Product("WebStorm", 49.0)
val teamCity = Product("TeamCity", 299.0)
val youTrack = Product("YouTrack", 500.0)

//customers
val lucas = "Lucas"
val cooper = "Cooper"
val nathan = "Nathan"
val reka = "Reka"
val bajram = "Bajram"
val asuka = "Asuka"

//cities
val Canberra = City("Canberra")
val Vancouver = City("Vancouver")
val Budapest = City("Budapest")
val Ankara = City("Ankara")
val Tokyo = City("Tokyo")

fun customer(name: String, city: City, vararg orders: Order) = Customer(name, city, orders.toList())
fun order(vararg products: Product, isDelivered: Boolean = true) = Order(products.toList(), isDelivered)
fun shop(name: String, vararg customers: Customer) = Shop(name, customers.toList())

val shop = shop("jb test shop",
        customer(lucas, Canberra,
                order(reSharper),
                order(reSharper, dotMemory, dotTrace)
        ),
        customer(cooper, Canberra),
        customer(nathan, Vancouver,
                order(rubyMine, webStorm)
        ),
        customer(reka, Budapest,
                order(idea, isDelivered = false),
                order(idea, isDelivered = false),
                order(idea)
        ),
        customer(bajram, Ankara,
                order(reSharper)
        ),
        customer(asuka, Tokyo,
                order(idea)
        )
)

val customers: Map<String, Customer> = shop.customers.associateBy { it.name }

val orderedProducts = setOf(idea, reSharper, dotTrace, dotMemory, rubyMine, webStorm)

val groupedByCities = mapOf(
        Canberra to listOf(lucas, cooper),
        Vancouver to listOf(nathan),
        Budapest to listOf(reka),
        Ankara to listOf(bajram),
        Tokyo to listOf(asuka)
).mapValues { it.value.map { name -> customers[name] } }
//products
val idea = Product("Intelli


*   搜索引擎结果中[webpage 2]和[webpage 7]明确指出该漏洞可以被利用来实现权限提升，并提供了利用分析的文章。
*   POC 代码尝试通过构造特定的 Binder 事务来触发 UAF。代码首先初始化 Binder 事务，其中包含多个指向共享内存区域中 `flat_binder_object` 结构的引用。然后，通过 `ioctl` 系统调用将构造的事务发送到 Binder 驱动程序。通过多线程竞争和 `BINDER_THREAD_EXIT`，尝试触发在释放 Binder 对象的过程中出现的竞争条件，进而导致 UAF。

**投毒风险分析：**

经过对 POC 代码的仔细检查，**未发现明显的投毒代码**。代码主要集中在 Binder 事务的构造和发送，以及多线程并发上，旨在触发 UAF 漏洞。代码中使用的常量和结构体定义与 Binder 机制相关，没有发现任何可疑的恶意行为。
因此，投毒风险评估为0%。

**利用方式：**

1.  **漏洞触发：** 利用的关键在于 `binder_release_work` 函数中的竞争条件。通过并发发送多个 Binder 事务，并配合 `BINDER_THREAD_EXIT` 来加速竞争，从而触发在对象释放后被再次访问的 UAF 情况。
2.  **利用过程：**
    *   **内存布局：**  首先，使用 `mmap` 创建一块共享内存区域，用于存储 Binder 事务数据和相关对象。
    *   **构造恶意Binder 事务：** 创建包含 BINDER_TYPE_BINDER 对象的 Binder 事务，该事务的 offsets 和 object buffer 指向共享内存。
    *   **多线程竞争：** 创建多个线程同时执行以下操作：
        *   复制 Binder 文件描述符 (`dup`)。
        *   使用 `BINDER_WRITE_READ` ioctl 发送构造的 Binder 事务。
        *   使用 `BINDER_THREAD_EXIT` ioctl 退出 Binder 线程，加速竞争。
        *   关闭复制的文件描述符 (`close`)。
    *   **UAF 触发：**  当一个线程释放了某个 Binder 对象后，另一个线程可能仍然持有指向该对象的指针，并尝试访问它，从而触发 UAF。
3.  **权限提升：** 成功触发 UAF 后，可以通过控制被释放的内存区域的内容，例如通过内存喷射，


= {
  '1': 'TransceiverFaults',
  '2': [
    {'1': 'over_temp_modem_asic_fault', '3': 1, '4': 1, '5': 8, '10': 'overTempModemAsicFault'},
    {'1': 'over_temp_pcba_fault', '3': 2, '4': 1, '5': 8, '10': 'overTempPcbaFault'},
    {'1': 'dc_voltage_fault', '3': 3, '4': 1, '5': 8, '10': 'dcVoltageFault'},
  ],
};

/// Descriptor for `TransceiverFaults`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List transceiverFaultsDescriptor = $convert.base64Decode(
    'ChFUcmFuc2NlaXZlckZhdWx0cxI6ChpvdmVyX3RlbXBfbW9kZW1fYXNpY19mYXVsdBgBIAEoCF'
    'IWb3ZlclRlbXBNb2RlbUFzaWNGYXVsdBIvChRvdmVyX3RlbXBfcGNiYV9mYXVsdBgCIAEoCFIR'
    'b3ZlclRlbXBQY2JhRmF1bHQSKAoQZGNfdm9sdGFnZV9mYXVsdBgDIAEoCFIOZGNWb2x0YWdlRm'
    'F1bHQ=');

@$core.Deprecated('Use transceiverGetTelemetryRequestDescriptor instead')
const TransceiverGetTelemetryRequest$json = {
  '1': 'TransceiverGetTelemetryRequest',
};

/// Descriptor for `TransceiverGetTelemetryRequest`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List transceiverGetTelemetryRequestDescriptor = $convert.base64Decode(
    'Ch5UcmFuc2NlaXZlckdldFRlbGVtZXRyeVJlcXVlc3Q=');

@$core.Deprecated('Use transceiverGetTelemetryResponseDescriptor instead')
const TransceiverGetTelemetryResponse$json = {
  '1': 'TransceiverGetTelemetryResponse',
  '2': [
    {'1': 'antenna_pointing_mode', '3': 1001, '4': 1, '5': 13, '10': 'antennaPointingMode'},
    {'1': 'antenna_pitch', '3': 1002, '4': 1, '5': 2, '10': 'antennaPitch'},
    {'1': 'antenna_roll', '3': 1003, '4': 1, '5': 2, '10': 'antennaRoll'},
    {'1': 'antenna_rx_theta', '3': 1004, '4': 1, '5': 2, '10': 'antennaRxTheta'},
    {'1': 'antenna_true_heading', '3': 1005, '4': 1, '5': 2, '10': 'antennaTrueHeading'},
    {'1': 'rx_channel', '3': 1006, '4': 1, '5': 13, '10': 'rxChannel'},
    {'1': 'current_cell_id', '3': 1007, '4': 1, '5': 13, '10': 'currentCellId'},
    {'1': 'seconds_until_slot_end', '3': 1008, '4': 1, '5': 2, '10': 'secondsUntilSlotEnd'},
    {'1': 'wb_rssi_peak_mag_db', '3':


import os, pickle, numpy as np
import faiss
import tiktoken
from openai import OpenAI
from ..configuracoes.config import API_KEY, CAMINHO_FAISS, CAMINHO_META, EMBED_DIM, EMBEDDING_MODEL, TOKENIZER_ENCODING, MAX_TOKENS_PER_CHUNK

client = OpenAI(api_key=API_KEY)
tokenizador = tiktoken.get_encoding(TOKENIZER_ENCODING)

class RAGMemory:
    def __init__(self, embed_dim=EMBED_DIM):
        self.embed_dim = embed_dim
        if os.path.exists(CAMINHO_FAISS):
            try:
                idx = faiss.read_index(CAMINHO_FAISS)
                if idx.d != embed_dim:
                    # dimensão incompatível: reinicia índice e reconstroi a partir do meta existente
                    self.index = faiss.IndexFlatL2(embed_dim)
                    try:
                        with open(CAMINHO_META, "rb") as f:
                            self.meta = pickle.load(f)
                    except Exception:
                        self.meta = []
                    if self.meta:
                        self._rebuild_from_meta()
                else:
                    self.index = idx
                    with open(CAMINHO_META, "rb") as f:
                        self.meta = pickle.load(f)
            except Exception:
                self.index = faiss.IndexFlatL2(embed_dim)
                self.meta = []
        else:
            self.index = faiss.IndexFlatL2(embed_dim)
            self.meta = []
        self.ids_set = set(hash(text) for text in self.meta)

    def embed_text(self, texto: str):
        resp = client.embeddings.create(model=EMBEDDING_MODEL, input=texto)
        return np.array(resp.data[0].embedding, dtype="float32")

    def chunk_text(self, texto: str, max_tokens=MAX_TOKENS_PER_CHUNK):
        tokens = tokenizador.encode(texto)
        chunks = []
        for i in range(0, len(tokens), max_tokens):
            chunk_tokens = tokens[i:i+max_tokens]
            chunks.append(tokenizador.decode(chunk_tokens))
        return chunks

    def add_texts(self, textos: list[str]):
        novos_chunks = []
        for t in textos:
            h = hash(t)
            if h not in self.ids_set:
                novos_chunks.append(t)
                self.ids_set.add(h)
        if novos_chunks:
            # Embeddings em batch para reduzir latência
            resp = client.embeddings.create(model=EMBEDDING_MODEL, input=novos_chunks)
            embeddings = [np.array(item.embedding, dtype="float32") for item in resp.data]
            self.index.add(np.array(embeddings))
            self.meta.extend(novos_chunks)
            self._persist()

    def _persist(self):
        os.makedirs(os.path.dirname(CAMINHO_FAISS), exist_ok=True)
        faiss.write_index(self.index, CAMINHO_FAISS)
        with open(CAMINHO_META, "wb") as f:
            pickle.dump(self.meta, f)

    def _rebuild_from_meta(self):
        # Re-embeddings em batch e reconstrução do índice
        resp = client.embeddings.create(model=EMBEDDING_MODEL, input=self.meta)
        embeddings = [np.array(item.embedding, dtype="float32") for item in resp.data]
        self.index.reset()
        self.index.add(np.array(embeddings))
        self._persist()

    def query(self, pergunta: str, k: int = 3):
        if self.index.ntotal == 0:
            return []
        query_emb = self.embed_text(pergunta).reshape(1, -1)
        D, I = self.index.search(query_emb, k)
        resultados = []
        for i in I[0]:
            if i == -1:
                continue
            if 0 <= i < len(self.meta):
                resultados.append(self.meta[i])
        return resultados

rag_memory = RAGMemory()


ntrast(10, 20, 255, 0.3)
    fcc.getColor()
    expect(setColorsFromRgbNumbers).toHaveBeenCalledTimes(0)
    expect(setColorsFromHexString).toHaveBeenCalledTimes(1)
    expect(setColorsFromNumber).toHaveBeenCalledTimes(0)
    expect(setColorsFromArray).toHaveBeenCalledTimes(0)
    expect(contrastFromHSP).toHaveBeenCalledTimes(1)
  })

  test('HEX number', () => {
    isNumber.mockImplementation(() => true)
    const fcc = new FontColorContrast(10, 20, 255, 0.3)
    fcc.getColor()
    expect(setColorsFromRgbNumbers).toHaveBeenCalledTimes(0)
    expect(setColorsFromHexString).toHaveBeenCalledTimes(0)
    expect(setColorsFromNumber).toHaveBeenCalledTimes(1)
    expect(setColorsFromArray).toHaveBeenCalledTimes(0)
    expect(contrastFromHSP).toHaveBeenCalledTimes(1)
  })

  test('HEX array', () => {
    isArray.mockImplementation(() => true)
    const fcc = new FontColorContrast(10, 20, 255, 0.3)
    fcc.getColor()
    expect(setColorsFromRgbNumbers).toHaveBeenCalledTimes(0)
    expect(setColorsFromHexString).toHaveBeenCalledTimes(0)
    expect(setColorsFromNumber).toHaveBeenCalledTimes(0)
    expect(setColorsFromArray).toHaveBeenCalledTimes(1)
    expect(contrastFromHSP).toHaveBeenCalledTimes(1)
  })

  test('failed params', () => {
    const fcc = new FontColorContrast(10, 20, 255, 0.3)
    fcc.getColor()
    expect(setColorsFromRgbNumbers).toHaveBeenCalledTimes(0)
    expect(setColorsFromHexString).toHaveBeenCalledTimes(0)
    expect(setColorsFromNumber).toHaveBeenCalledTimes(0)
    expect(setColorsFromArray).toHaveBeenCalledTimes(0)
    expect(contrastFromHSP).toHaveBeenCalledTimes(0)
  })
})

describe('getColor() end to end', () => {
  let setColorsFromRgbNumbers: jest.SpyInstance<any, unknown[]>
  let setColorsFromHexString: jest.SpyInstance<any, unknown[]>
  let setColorsFromNumber: jest.SpyInstance<any, unknown[]>
  let setColorsFromArray: jest.SpyInstance<any, unknown[]>
  let isRgb: jest.SpyInstance<any, unknown[]>
  let isHexString: jest.SpyInstance<any, unknown[]>
  let isNumber: jest.SpyInstance<any, unknown[]>
  let isArray: jest.SpyInstance<any, unknown[]>
  let contrastFromHSP: jest.SpyInstance<'#000000' | '#ffffff', []>

  beforeEach(() => {
    setColorsFromRgbNumbers = jest
      .spyOn(FontColorContrast.prototype, 'setColorsFromRgbNumbers')
    setColorsFromHexString = jest
      .spyOn(FontColorContrast.prototype, 'setColorsFromHexString')
    setColorsFromNumber = jest
      .spyOn(FontColorContrast.prototype, 'setColorsFromNumber')
    setColorsFromArray = jest
      .spyOn(FontColorContrast.prototype, 'setColorsFromArray')
    isRgb = jest
      .spyOn(FontColorContrast.prototype, 'isRgb')
    isHexString = jest
      .spyOn(FontColorContrast.prototype, 'isHexString')
    isNumber = jest
      .spyOn(FontColorContrast.prototype, 'isNumber')
    isArray = jest
      .spyOn(FontColorContrast.prototype, 'isArray')
    contrastFromHSP = jest
      .spyOn(FontColorContrast.prototype, 'contrastFromHSP')
  })


;

#[deprecated]
pub const MAGIC_NO_CHECK_FORTRAN: c_int = 0x00_0000;
#[deprecated]
pub const MAGIC_NO_CHECK_TROFF: c_int = 0x00_0000;

// TODO: MAGIC_VERSION string

// TODO: MAGIC_SNPRINTB bytes

#[cfg(feature = "v5-21")]
pub const MAGIC_PARAM_INDIR_MAX: c_int = 0;
#[cfg(feature = "v5-21")]
pub const MAGIC_PARAM_NAME_MAX: c_int = 1;
#[cfg(feature = "v5-21")]
pub const MAGIC_PARAM_ELF_PHNUM_MAX: c_int = 2;
#[cfg(feature = "v5-21")]
pub const MAGIC_PARAM_ELF_SHNUM_MAX: c_int = 3;
#[cfg(feature = "v5-22")]
pub const MAGIC_PARAM_ELF_NOTES_MAX: c_int = 4;
#[cfg(feature = "v5-25")]
pub const MAGIC_PARAM_REGEX_MAX: c_int = 5;
#[cfg(feature = "v5-27")]
pub const MAGIC_PARAM_BYTES_MAX: c_int = 6;
#[cfg(feature = "v5-40")]
pub const MAGIC_PARAM_ENCODING_MAX: c_int = 7;

// NOTE: the following are from `file.h`, but part of `magic.h` API
#[cfg(feature = "v5-04")]
pub const FILE_LOAD: c_int = 0;
#[cfg(feature = "v5-04")]
pub const FILE_CHECK: c_int = 1;
#[cfg(feature = "v5-04")]
pub const FILE_COMPILE: c_int = 2;
#[cfg(feature = "v5-05")]
pub const FILE_LIST: c_int = 3;

extern "C" {
    pub fn magic_open(flags: c_int) -> magic_t;
    pub fn magic_close(cookie: magic_t);

    #[cfg(feature = "v5-04")]
    pub fn magic_getpath(magicfile: *const c_char, action: c_int) -> *const c_char;
    pub fn magic_file(cookie: magic_t, filename: *const c_char) -> *const c_char;
    pub fn magic_descriptor(cookie: magic_t, fd: c_int) -> *const c_char;
    pub fn magic_buffer(cookie: magic_t, buffer: *const u8, length: size_t) -> *const c_char;

    pub fn magic_error(cookie: magic_t) -> *const c_char;
    #[cfg(feature = "v5-32")]
    pub fn magic_getflags(cookie: magic_t) -> c_int;
    #[must_use]
    pub fn magic_setflags(cookie: magic_t, flags: c_int) -> c_int;

    #[cfg(feature = "v5-13")]
    pub fn magic_version() -> c_int;
    #[must_use]
    pub fn magic_load(cookie: magic_t, filename: *const c_char) -> c_int;
    #[cfg(feature = "v5-20")]
    #[must_use]
    pub fn magic_load_buffers(
        cookie: magic_t,
        buffers: *mut *mut c_void,
        sizes: *mut size_t,
        nbuffers: size_t,
    ) -> c_int;

    #[must_use]
    pub fn magic_compile(cookie: magic_t, filename: *const c_char) -> c_int;
    #[must_use]
    pub fn magic_check(cookie: magic_t, filename: *const c_char


ntity", Arrays.asList(1L));
        verifyException(cb, IllegalArgumentException.class, r -> r.getResultList());

        // Values with matching entry
        cb.setParameter("intEntity", Arrays.asList(new IntIdEntity("doc1")));
        resultList = cb.getResultList();
        assertEquals(1, resultList.size());

        assertEquals("doc1", resultList.get(0).get(0));
        assertEquals("doc1", resultList.get(0).get(1));

        // Values with no matching entry
        cb.setParameter("intEntity", Arrays.asList(new IntIdEntity("docX")));
        resultList = cb.getResultList();
        assertEquals(1, resultList.size());

        assertEquals("docX", resultList.get(0).get(0));
        assertNull(resultList.get(0).get(1));

        // Empty values
        cb.setParameter("intEntity", Collections.emptyList());
        resultList = cb.getResultList();
        assertEquals(0, resultList.size());
    }

    @Test
    // NOTE: Entity joins are supported since Hibernate 5.1, Datanucleus 5 and latest Eclipselink
    @Category({ NoHibernate42.class, NoHibernate43.class, NoHibernate50.class, NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class })
    public void testValuesEntityFunctionParameterWithoutNullsFilter() {
        CriteriaBuilder<Tuple> cb = cbf.create(em, Tuple.class);
        cb.setProperty(ConfigurationProperties.VALUES_CLAUSE_FILTER_NULLS, "false");

        cb.fromValues(IntIdEntity.class, "intEntity", 1);
        cb.leftJoinOn(Document.class, "doc")
                .on("doc.name").eqExpression("intEntity.name")
                .end();
        cb.select("intEntity.name");
        cb.select("doc.name");
        cb.orderByAsc("intEntity.name");

        // Empty values
        cb.setParameter("intEntity", Collections.emptyList());
        List<Tuple> resultList = cb.getResultList();
        assertEquals(1, resultList.size());

        assertNull(resultList.get(0).get(0));
        assertNull(resultList.get(0).get(1));
    }

    @Test
    // NOTE: Entity joins are supported since Hibernate 5.1, Datanucleus 5 and latest Eclipselink
//    @Category({ NoHibernate42.class, NoHibernate43.class, NoHibernate50.class, NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class })
    // No hibernate for now, see https://hibernate.atlassian.net/browse/HHH-11340
    // H2 before 1.4.199 does not support parameters in the CTE http://dba.stackexchange.com/a/78449
    @Category({ NoHibernate42.class, NoHibernate43.class, NoHibernate50.class, NoHibernate51.class, NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoMySQLOld.class })
    public void testValuesEntityFunctionInCte() {
        CriteriaBuilder<Tuple> cb = cbf.create(em, Tuple.class);
        cb.setProperty(ConfigurationProperties.VALUES_CLAUSE_FILTER_NULLS, "false");

        cb.with(PersonCTE.class, false)
            .fromValues(IntIdEntity.class, "intEntity", 1)
            .leftJoinOn(Document.class, "doc")
                .on("doc.name").eqExpression("intEntity.name")
            .end()
            .innerJoin("doc.owner", "owner")
            .bind("id").select("owner.id")
            .bind("name").select("owner.name")
            .bind("age").select("owner.age")
            .bind("idx").select("1")
            .bind("owner").select("owner")
        .end()
        .from(PersonCTE.class)
        .select("id")
        .select("name");

        // Empty values
        cb.setParameter("intEntity",


00, .98);
$red-navbar:                rgba(#FF4C40, .98);

$bg-nude:               #f4f3ef !default;
$bg-primary:            #8ECFD5 !default;
$bg-info:               #7CE4FE !default;
$bg-success:            #8EF3C5 !default;
$bg-warning:            #FFE28C !default;
$bg-danger:             #FF8F5E !default;

$topbar-x:             topbar-x !default;
$topbar-back:          topbar-back !default;
$bottombar-x:          bottombar-x !default;
$bottombar-back:       bottombar-back !default;

$transition-linear:                                   linear !default;
$transition-bezier:         cubic-bezier(0.34, 1.61, 0.7, 1) !default;
$transition-ease:           ease 0s;
$transition-ease-in:              ease-in !default;
$transition-ease-out:             ease-out !default;

$general-transition-time:  300ms !default;

$slow-transition-time:           370ms !default;
$dropdown-coordinates:      29px -50px !default;

$fast-transition-time:           150ms !default;

$ultra-fast-transition-time:     100ms  !default;

$select-coordinates:         50% -40px !default;

$padding-zero:                   0px !default;

$sidebar-width:               calc(100% - 260px) !default;
$medium-dark-gray:           #AAAAAA !default;

//variables used in cards
$card-black-color:          #252422 !default;
$card-muted-color:          #ccc5b9 !default;

//variables used for sidebar
$sidebar-background-dark-blue: #506367;

$sidebar-background-blue:      #b8d8d8 !default;
$sidebar-font-blue:            #506568 !default;
$sidebar-subtitle-blue:        #7a9e9f !default;

$sidebar-background-green:      #d5e5a3 !default;
$sidebar-font-green:            #60773d !default;
$sidebar-subtitle-green:        #92ac56 !default;

$sidebar-background-yellow:      #ffe28c !default;
$sidebar-font-yellow:            #b25825 !default;
$sidebar-subtitle-yellow:        #d88715 !default;

$sidebar-background-brown:      #d6c1ab !default;
$sidebar-font-brown:            #75442e !default;
$sidebar-subtitle-brown:        #a47e65 !default;

$sidebar-background-purple:      #baa9ba !default;
$sidebar-font-purple:            #3a283d !default;
$sidebar-subtitle-purple:        #5a283d !default;

$sidebar-background-orange:      #ff8f5e !default;
$sidebar-font-orange:            #772510 !default;
$sidebar-subtitle-orange:        #e95e37 !default;
body {
    position: absolute;
    width: 100%;
    height: 100%;
    font-family: 'Roboto', sans-serif;
    --bs-body-font-size: 0.9rem;
}

/* roboto-300 - latin */

@font-face {
    font-family: 'Roboto';
    font-style: normal;
    font-weight: 300;
    src: url('../fonts/roboto-v15-latin-300.eot');
    /* IE9 Compat Modes */
    src:
        local('Roboto Light'),
        local('Roboto-Light'),
        url('..


f450-1f3fc": "open_hands_tone2",
"1f450-1f3fd": "open_hands_tone3",
"1f450-1f3fe": "open_hands_tone4",
"1f450-1f3ff": "open_hands_tone5",
"1f64c": "raised_hands",
"1f64c-1f3fb": "raised_hands_tone1",
"1f64c-1f3fc": "raised_hands_tone2",
"1f64c-1f3fd": "raised_hands_tone3",
"1f64c-1f3fe": "raised_hands_tone4",
"1f64c-1f3ff": "raised_hands_tone5",
"1f44f": "clap",
"1f44f-1f3fb": "clap_tone1",
"1f44f-1f3fc": "clap_tone2",
"1f44f-1f3fd": "clap_tone3",
"1f44f-1f3fe": "clap_tone4",
"1f44f-1f3ff": "clap_tone5",
"1f91d": "handshake",
"1f44d": "thumbsup",
"1f44d-1f3fb": "thumbsup_tone1",
"1f44d-1f3fc": "thumbsup_tone2",
"1f44d-1f3fd": "thumbsup_tone3",
"1f44d-1f3fe": "thumbsup_tone4",
"1f44d-1f3ff": "thumbsup_tone5",
"1f44e": "thumbsdown",
"1f44e-1f3fb": "thumbsdown_tone1",
"1f44e-1f3fc": "thumbsdown_tone2",
"1f44e-1f3fd": "thumbsdown_tone3",
"1f44e-1f3fe": "thumbsdown_tone4",
"1f44e-1f3ff": "thumbsdown_tone5",
"1f44a": "punch",
"1f44a-1f3fb": "punch_tone1",
"1f44a-1f3fc": "punch_tone2",
"1f44a-1f3fd": "punch_tone3",
"1f44a-1f3fe": "punch_tone4",
"1f44a-1f3ff": "punch_tone5",
"270a": "fist",
"270a-1f3fb": "fist_tone1",
"270a-1f3fc": "fist_tone2",
"270a-1f3fd": "fist_tone3",
"270a-1f3fe": "fist_tone4",
"270a-1f3ff": "fist_tone5",
"1f91b": "left_facing_fist",
"1f91b-1f3fb": "left_facing_fist_tone1",
"1f91b-1f3fc": "left_facing_fist_tone2",
"1f91b-1f3fd": "left_facing_fist_tone3",
"1f91b-1f3fe": "left_facing_fist_tone4",
"1f91b-1f3ff": "left_facing_fist_tone5",
"1f91c": "right_facing_fist",
"1f91c-1f3fb": "right_facing_fist_tone1",
"1f91c-1f3fc": "right_facing_fist_tone2",
"1f91c-1f3fd": "right_facing_fist_tone3",
"1f91c-1f3fe": "right_facing_fist_tone4",
"1f91c-1f3ff": "right_facing_fist_tone5",
"1f91e": "fingers_crossed",
"1f91e-1f


return null;
        }

        try {
            return new URL(spec.substring(0, separator));
        } catch (MalformedURLException e) {
            return null;
        }
    }

    private boolean handleNetworkOrFileUrlCheck(Class<?> callerClass, URL url) {
        if (isNetworkUrl(url)) {
            checkOutboundNetworkAccess(callerClass);
            return true;
        }
        if (isFileUrl(url)) {
            checkURLFileRead(callerClass, url);
            return true;
        }
        return false;
    }

    @Override
    public void checkJarURLAccess(Class<?> callerClass, JarURLConnection connection) {
        var jarFileUrl = connection.getJarFileURL();
        if (handleNetworkOrFileUrlCheck(callerClass, jarFileUrl)) {
            return;
        }
        checkUnsupportedURLProtocolConnection(callerClass, jarFileUrl.getProtocol());
    }

    private static final Set<String> NETWORK_PROTOCOLS = Set.of("http", "https", "ftp", "mailto");

    private static boolean isNetworkUrl(java.net.URL url) {
        return NETWORK_PROTOCOLS.contains(url.getProtocol());
    }

    private static boolean isFileUrl(java.net.URL url) {
        return "file".equals(url.getProtocol());
    }

    private static boolean isJarUrl(java.net.URL url) {
        return "jar".equals(url.getProtocol());
    }

    private static boolean isJrtUrl(java.net.URL url) {
        return "jrt".equals(url.getProtocol());
    }

    // We have to use class names for sun.net.www classes as java.base does not export them
    private static final List<String> ADDITIONAL_NETWORK_URL_CONNECT_CLASS_NAMES = List.of(
        "sun.net.www.protocol.ftp.FtpURLConnection",
        "sun.net.www.protocol.mailto.MailToURLConnection"
    );

    private static boolean isNetworkUrlConnection(java.net.URLConnection urlConnection) {
        var connectionClass = urlConnection.getClass();
        return HttpURLConnection.class.isAssignableFrom(connectionClass)
            || ADDITIONAL_NETWORK_URL_CONNECT_CLASS_NAMES.contains(connectionClass.getName());
    }

    // We have to use class names for sun.net.www classes as java.base does not export them
    private static boolean isFileUrlConnection(java.net.URLConnection urlConnection) {
        var connectionClass = urlConnection.getClass();
        return "sun.net.www.protocol.file.FileURLConnection".equals(connectionClass.getName());
    }

    @Override
    public void checkURLFileRead(Class<?> callerClass, URL url) {
        try {
            checkFileRead(callerClass, Paths.get(url.toURI()));
        } catch (URISyntaxException e) {
            // We expect this method to be called only on File URLs; otherwise the underlying method would fail anyway
            throw new RuntimeException(e);
        }
    }

}
/*
 * @notice
 *
 * Copyright 2020 Adrien Grand and the lz4-java contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.elasticsearch.lz4;

/**
 * Th


 the remote host</param>
        /// <param name="bufferSize">Size of the buffer to allocate for packet data</param>
        public UDPPacketBuffer(IPEndPoint endPoint, int bufferSize)
        {
            Data = new byte[bufferSize];
            RemoteEndPoint = endPoint;
        }

        /// <summary>
        /// Create an allocated UDP packet buffer for sending a packet
        /// </summary>
        public UDPPacketBuffer(byte[] buffer, int bufferSize, IPEndPoint destination, int category)
        {
            Data = new byte[bufferSize];
            this.CopyFrom(buffer, bufferSize);
            DataLength = bufferSize;

            RemoteEndPoint = destination;
        }

        /// <summary>
        /// Create an allocated UDP packet buffer for sending a packet
        /// </summary>
        /// <param name="endPoint">EndPoint of the remote host</param>
        /// <param name="data">The actual buffer to use for packet data (no allocation).</param>
        public UDPPacketBuffer(IPEndPoint endPoint, byte[] data)
        {
            Data = data;
            RemoteEndPoint = endPoint;
        }

        public void CopyFrom(Array src, int length)
        {
            Buffer.BlockCopy(src, 0, this.Data, 0, length);
        }

        public void CopyFrom(Array src)
        {
            this.CopyFrom(src, src.Length);
        }

        public void ResetEndpoint()
        {
            RemoteEndPoint = new IPEndPoint(Settings.BIND_ADDR, 0);
        }
    }
}


* Optional. The automated backup mode. If the mode is disabled, the other
     * fields will be ignored.
     *

     *
     *
     * .google.cloud.redis.cluster.v1.AutomatedBackupConfig.AutomatedBackupMode automated_backup_mode = 1 [(.google.api.field_behavior) = OPTIONAL];
     *
     *
     * @return The automatedBackupMode.
     */
    @java.lang.Override
    public com.google.cloud.redis.cluster.v1.AutomatedBackupConfig.AutomatedBackupMode
        getAutomatedBackupMode() {
      com.google.cloud.redis.cluster.v1.AutomatedBackupConfig.AutomatedBackupMode result =
          com.google.cloud.redis.cluster.v1.AutomatedBackupConfig.AutomatedBackupMode.forNumber(
              automatedBackupMode_);
      return result == null
          ? com.google.cloud.redis.cluster.v1.AutomatedBackupConfig.AutomatedBackupMode.UNRECOGNIZED
          : result;
    }

    /**
     *
     *
     *

     * Optional. The automated backup mode. If the mode is disabled, the other
     * fields will be ignored.
     *

     *
     *
     * .google.cloud.redis.cluster.v1.AutomatedBackupConfig.AutomatedBackupMode automated_backup_mode = 1 [(.google.api.field_behavior) = OPTIONAL];
     *
     *
     * @param value The automatedBackupMode to set.
     * @return This builder for chaining.
     */
    public Builder setAutomatedBackupMode(
        com.google.cloud.redis.cluster.v1.AutomatedBackupConfig.AutomatedBackupMode value) {
      if (value == null) {
        throw new NullPointerException();
      }
      bitField0_ |= 0x00000002;
      automatedBackupMode_ = value.getNumber();
      onChanged();
      return this;
    }

    /**
     *
     *
     *

     * Optional. The automated backup mode. If the mode is disabled, the other
     * fields will be ignored.
     *

     *
     *
     * .google.cloud.redis.cluster.v1.AutomatedBackupConfig.AutomatedBackupMode automated_backup_mode = 1 [(.google.api.field_behavior) = OPTIONAL];
     *
     *
     * @return This builder for chaining.
     */
    public Builder clearAutomatedBackupMode() {
      bitField0_ = (bitField0_ & ~0x00000002);
      automatedBackupMode_ = 0;
      onChanged();
      return this;
    }

    private com.google.protobuf.Duration retention_;
    private com.google.protobuf.SingleFieldBuilderV3<
            com.google.protobuf.Duration,
            com.google.protobuf.Duration.Builder,
            com.google.protobuf.DurationOrBuilder>
        retentionBuilder_;

    /**
     *
     *
     *

     * Optional. How long to keep automated backups before the backups are
     * deleted. The value should be between 1 day and 365 days. If not specified,
     * the default value is 35 days.
     *

     *
     *
     * optional .google.protobuf.Duration retention = 3 [(.google.api.field_behavior) = OPTIONAL];
     *
     *
     * @return Whether the retention field is set.
     */
    public boolean hasRetention() {
      return ((bitField0_ & 0x00000004) != 0);
    }

    /**
     *
     *
     *

     * Optional. How long to keep automated backups before the backups are
     * deleted. The value should be between 1 day and 365 days. If not specified,
     * the default value is 35 days.
     *

     *
     *
     * optional .google.protobuf.Duration retention = 3 [(.google.api.field_behavior) = OPTIONAL];
     *


c4:	7101941f 	cmp	w0, #0x65
  4559c8:	7a500b84 	ccmp	w28, #0x10, #0x4, eq  // eq = none
  4559cc:	54000580 	b.eq	455a7c <____strtof_l_internal+0x46c>  // b.none
  4559d0:	39c00680 	ldrsb	w0, [x20, #1]
  4559d4:	7100b41f 	cmp	w0, #0x2d
  4559d8:	540023c0 	b.eq	455e50 <____strtof_l_internal+0x840>  // b.none
  4559dc:	7100ac1f 	cmp	w0, #0x2b
  4559e0:	54000440 	b.eq	455a68 <____strtof_l_internal+0x458>  // b.none
  4559e4:	5100c000 	sub	w0, w0, #0x30
  4559e8:	12001c02 	and	w2, w0, #0xff
  4559ec:	7100245f 	cmp	w2, #0x9
  4559f0:	54000468 	b.hi	455a7c <____strtof_l_internal+0x46c>  // b.pmore
  4559f4:	91000683 	add	x3, x20, #0x1
  4559f8:	7100439f 	cmp	w28, #0x10
  4559fc:	54004460 	b.eq	456288 <____strtof_l_internal+0xc78>  // b.none
  455a00:	b5004604 	cbnz	x4, 4562c0 <____strtof_l_internal+0xcb0>
  455a04:	b100043f 	cmn	x1, #0x1
  455a08:	5400b1c0 	b.eq	457040 <____strtof_l_internal+0x1a30>  // b.none
  455a0c:	928004e2 	mov	x2, #0xffffffffffffffd8    	// #-40
  455a10:	f2efffe2 	movk	x2, #0x7fff, lsl #48
  455a14:	eb02003f 	cmp	x1, x2
  455a18:	5400d028 	b.hi	45741c <____strtof_l_internal+0x1e0c>  // b.pmore
  455a1c:	b202e7e5 	mov	x5, #0xcccccccccccccccc    	// #-3689348814741910324
  455a20:	91009c22 	add	x2, x1, #0x27
  455a24:	f29999a5 	movk	x5, #0xcccd
  455a28:	9bc57c45 	umulh	x5, x2, x5
  455a2c:	5280000c 	mov	w12, #0x0                   	// #0
  455a30:	d343fca5 	lsr	x5, x5, #3
  455a34:	8b0508ab 	add	x11, x5, x5, lsl #2
  455a38:	cb0b044b 	sub	x11, x2, x11, lsl #1
  455a3c:	14000119 	b	455ea0 <____strtof_l_internal+0x890>
  455a40:	b875d8c0 	ldr	w0, [x6, w21, sxtw #2]
  455a44:	51018400 	sub


manual]).
latex_documents = [
  ('index', 'scikit-rf.tex', 'scikit-rf Documentation',
   'scikit-rf Developers', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
latex_logo = '_static/scikit-rf-title-flat.pdf'

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Additional stuff for the LaTeX preamble.
latex_preamble = r'\usepackage{epstopdf}'

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

autosummary_generate = True

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'scikit-rf', 'scikit-rf Documentation',
     ['alex arsenovic'], 1)
]

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
    'python': ('https://docs.python.org/3', None),
    'numpy': ('https://numpy.org/doc/stable', None),
    'pd': ('https://pandas.pydata.org/docs', None),
    'scipy': ('https://docs.scipy.org/doc/scipy/', None),
}

def process_signature(app, what, name, obj, options, signature, return_annotation):

    func_name = name.split(".")[-1]
    if func_name.startswith("plot_") and func_name[5:] in rf.Network._generated_functions().keys():
        signature = signature.split(",")[2:]
        return "(" + ", ".join(signature), return_annotation

    return signature, return_annotation

def setup(app):
    app.connect("autodoc-process-signature", process_signature)