ause();
    }
  }

  function parse_ForClause()
  {
    eventHandler.startNonterminal("ForClause", e0);
    shift(139);                     // 'for'
    lookahead1W(21);                // S^WS | '$' | '(:'
    whitespace();
    parse_ForBinding();
    for (;;)
    {
      if (l1 != 42)                 // ','
      {
        break;
      }
      shift(42);                    // ','
      lookahead1W(21);              // S^WS | '$' | '(:'
      whitespace();
      parse_ForBinding();
    }
    eventHandler.endNonterminal("ForClause", e0);
  }

  function try_ForClause()
  {
    shiftT(139);                    // 'for'
    lookahead1W(21);                // S^WS | '$' | '(:'
    try_ForBinding();
    for (;;)
    {
      if (l1 != 42)                 // ','
      {
        break;
      }
      shiftT(42);                   // ','
      lookahead1W(21);              // S^WS | '$' | '(:'
      try_ForBinding();
    }
  }

  function parse_ForBinding()
  {
    eventHandler.startNonterminal("ForBinding", e0);
    shift(31);                      // '$'
    lookahead1W(246);               // EQName^Token | S^WS | '(:' | 'after' | 'allowing' | 'ancestor' |
    whitespace();
    parse_VarName();
    lookahead1W(182);               // S^WS | '(:' | 'allowing' | 'as' | 'at' | 'in' | 'score'
    if (l1 == 80)                   // 'as'
    {
      whitespace();
      parse_TypeDeclaration();
    }
    lookahead1W(173);               // S^WS | '(:' | 'allowing' | 'at' | 'in' | 'score'
    if (l1 == 73)                   // 'allowing'
    {
      whitespace();
      parse_AllowingEmpty();
    }
    lookahead1W(160);               // S^WS | '(:' | 'at' | 'in' | 'score'
    if (l1 == 82)                   // 'at'
    {
      whitespace();
      parse_PositionalVar();
    }
    lookahead1W(126);               // S^WS | '(:' | 'in' | 'score'
    if (l1 == 232)                  // 'score'
    {
      whitespace();
      parse_FTScoreVar();
    }
    lookahead1W(56);                // S^WS | '(:' | 'in'
    shift(156);                     // 'in'
    lookahead1W(267);               // EQName^Token | IntegerLiteral | DecimalLiteral | DoubleLiteral | StringLiteral |
    whitespace();
    parse_ExprSingle();
    eventHandler.endNonterminal("ForBinding", e0);
  }

  function try_ForBinding()
  {
    shiftT(31);                     // '$'
    lookahead1W(246);               // EQName^Token | S^WS | '(:' | 'after' | 'allowing' | 'ancestor' |
    try_VarName();
    lookahead1W(182);               // S^WS | '(:' | 'allowing' | 'as' | 'at' | 'in' | 'score'
    if (l1 == 80)                   // 'as'
    {
      try_TypeDeclaration();
    }
    lookahead1W(173);               // S^WS | '(:' | 'allowing' | 'at' | 'in' | 'score'
    if (l1 == 73)                   // 'allowing'
    {
      try_AllowingEmpty();
    }
    lookahead1W(160);               // S^WS | '(:' | 'at' | 'in' | 'score'
    if (l1 == 82)                   // 'at'
    {
      try_PositionalVar();
    }
    lookahead1W(126);


is_true(h_result::failed(h_result::COR_E_IO));
    }

    void test_method_(failed_with_ERROR_OPEN_FAILED) {
      assert::is_true(h_result::failed(h_result::ERROR_OPEN_FAILED));
    }

    void test_method_(failed_with_COR_E_ABANDONEDMUTEX) {
      assert::is_true(h_result::failed(h_result::COR_E_ABANDONEDMUTEX));
    }

    void test_method_(failed_with_ERROR_DLL_INIT_FAILED) {
      assert::is_true(h_result::failed(h_result::ERROR_DLL_INIT_FAILED));
    }

    void test_method_(failed_with_COR_E_CUSTOMATTRIBUTEFORMAT) {
      assert::is_true(h_result::failed(h_result::COR_E_CUSTOMATTRIBUTEFORMAT));
    }

    void test_method_(failed_with_S_FALSE) {
      assert::is_false(h_result::failed(h_result::S_FALSE));
    }

    void test_method_(failed_with_COR_E_MEMBERACCESS) {
      assert::is_true(h_result::failed(h_result::COR_E_MEMBERACCESS));
    }

    void test_method_(failed_with_COR_E_RANK) {
      assert::is_true(h_result::failed(h_result::COR_E_RANK));
    }

    void test_method_(failed_with_COR_E_INVALIDCOMOBJECT) {
      assert::is_true(h_result::failed(h_result::COR_E_INVALIDCOMOBJECT));
    }

    void test_method_(failed_with_E_HANDLE) {
      assert::is_true(h_result::failed(h_result::E_HANDLE));
    }

    void test_method_(failed_with_COR_E_INVALIDOPERATION) {
      assert::is_true(h_result::failed(h_result::COR_E_INVALIDOPERATION));
    }

    void test_method_(failed_with_STG_E_PATHNOTFOUND) {
      assert::is_true(h_result::failed(h_result::STG_E_PATHNOTFOUND));
    }

    void test_method_(failed_with_COR_E_SYSTEM) {
      assert::is_true(h_result::failed(h_result::COR_E_SYSTEM));
    }

    void test_method_(get_code_with_ERROR_FILE_INVALID) {
      assert::are_equal(static_cast<int32>(0x03EE), h_result::get_code(h_result::ERROR_FILE_INVALID));
    }

    void test_method_(get_code_with_MSEE_E_ASSEMBLYLOADINPROGRESS) {
      assert::are_equal(static_cast<int32>(0x1016), h_result::get_code(h_result::MSEE_E_ASSEMBLYLOADINPROGRESS));
    }

    void test_method_(get_code_with_ERROR_UNRECOGNIZED_VOLUME) {
      assert::are_equal(static_cast<int32>(0x03ED), h_result::get_code(h_result::ERROR_UNRECOGNIZED_VOLUME));
    }

    void test_method_(get_code_with_ERROR_LOCK_VIOLATION) {
      assert::are_equal(static_cast<int32>(0x0021), h_result::get_code(h_result::ERROR_LOCK_VIOLATION));
    }

    void test_method_(get_code_with_ERROR_SHARING_VIOLATION) {
      assert::are_equal(static_cast<int32>(0x0020), h_re


01D57D4 45020004 */  bc1fl .L801D57E8_ovl9
/* 183828 801D57D8 46007086 */   mov.s $f2, $f14
/* 18382C 801D57DC 10000002 */  b     .L801D57E8_ovl9
/* 183830 801D57E0 46007087 */   neg.s $f2, $f14
/* 183834 801D57E4 46007086 */  mov.s $f2, $f14
.L801D57E8_ovl9:
/* 183838 801D57E8 4600103E */  c.le.s $f2, $f0
/* 18383C 801D57EC 00000000 */  nop
/* 183840 801D57F0 4502000C */  bc1fl .L801D5824_ovl9
/* 183844 801D57F4 44802000 */   mtc1  $zero, $f4
/* 183848 801D57F8 44809000 */  mtc1  $zero, $f18
/* 18384C 801D57FC 24020002 */  li    $v0, 2
/* 183850 801D5800 460C903E */  c.le.s $f18, $f12
/* 183854 801D5804 00000000 */  nop
/* 183858 801D5808 45000003 */  bc1f  .L801D5818_ovl9
/* 18385C 801D580C 00000000 */   nop
/* 183860 801D5810 1000000C */  b     .L801D5844_ovl9
/* 183864 801D5814 24030003 */   li    $v1, 3
.L801D5818_ovl9:
/* 183868 801D5818 1000000A */  b     .L801D5844_ovl9
/* 18386C 801D581C 00401825 */   move  $v1, $v0
/* 183870 801D5820 44802000 */  mtc1  $zero, $f4
.L801D5824_ovl9:
/* 183874 801D5824 24020001 */  li    $v0, 1
/* 183878 801D5828 460E203E */  c.le.s $f4, $f14
/* 18387C 801D582C 00000000 */  nop
/* 183880 801D5830 45000003 */  bc1f  .L801D5840_ovl9
/* 183884 801D5834 00000000 */   nop
/* 183888 801D5838 10000001 */  b     .L801D5840_ovl9
/* 18388C 801D583C 00001025 */   move  $v0, $zero
.L801D5840_ovl9:
/* 183890 801D5840 00401825 */  move  $v1, $v0
.L801D5844_ovl9:
/* 183894 801D5844 00601025 */  move  $v0, $v1
/* 183898 801D5848 03E00008 */  jr    $ra
/* 18389C 801D584C 27BD0038 */   addiu $sp, $sp, 0x38

.type func_801D56D0_ovl9, @function
.size func_801D56D0_ovl9, . - func_801D56D0_ovl9

glabel func_801D5850_ovl9
/* 1838A0 801D5850 27BDFFC0 */  addiu $sp, $sp, -0x40
/* 1838A4 801D5854 AFB1001C */  sw    $s1, 0x1c($sp)
/* 1838A8 801D5858 3C118005 */ lui $s1, 0x8005
/* 1838AC 801D585C 2631A7C4 */ addiu $s1, -0x583c
/* 1838B0 801D5860 8E2F0000 */  lw    $t7, ($s1)


OCAL
    is CIFileStatus.SndTransfer -> true
    is CIFileStatus.SndComplete -> false
    is CIFileStatus.SndCancelled -> true
    is CIFileStatus.SndError -> true
    is CIFileStatus.SndWarning -> true
    is CIFileStatus.RcvInvitation -> false
    is CIFileStatus.RcvAccepted -> true
    is CIFileStatus.RcvTransfer -> true
    is CIFileStatus.RcvAborted -> true
    is CIFileStatus.RcvCancelled -> true
    is CIFileStatus.RcvComplete -> false
    is CIFileStatus.RcvError -> true
    is CIFileStatus.RcvWarning -> true
    is CIFileStatus.Invalid -> true
  }

  /**
   * DO NOT CALL this function in compose scope, [LaunchedEffect], [DisposableEffect] and so on. Only with [withBGApi] or [runBlocking].
   * Otherwise, it will be canceled when moving to another screen/item/view, etc
   * */
  suspend fun loadRemoteFile(allowToShowAlert: Boolean): Boolean {
    val rh = chatModel.currentRemoteHost.value
    val user = chatModel.currentUser.value
    if (rh == null || user == null || fileSource == null || !loaded) return false
    if (getLoadedFilePath(this) != null) return true
    if (cachedRemoteFileRequests.contains(fileSource)) return false

    val rf = RemoteFile(
      userId = user.userId,
      fileId = fileId,
      sent = fileStatus.sent,
      fileSource = fileSource
    )
    cachedRemoteFileRequests[fileSource] = false
    val showAlert = fileSize > 5_000_000 && allowToShowAlert
    if (showAlert) {
      AlertManager.shared.showAlertMsgWithProgress(
        title = generalGetString(MR.strings.loading_remote_file_title),
        text = generalGetString(MR.strings.loading_remote_file_desc)
      )
    }
    val res = chatModel.controller.getRemoteFile(rh.remoteHostId, rf)
    cachedRemoteFileRequests[fileSource] = res
    if (showAlert) {
      AlertManager.shared.hideAlert()
    }
    return res
  }

  fun forwardingAllowed(): Boolean = when {
    chatModel.connectedToRemote() && cachedRemoteFileRequests[fileSource] != false && loaded -> true
    getLoadedFilePath(this) != null -> true
    else -> false
  }

  companion object {
    fun getSample(
      fileId: Long = 1,
      fileName: String = "test.txt",
      fileSize: Long = 100,
      filePath: String? = "test.txt",
      fileStatus: CIFileStatus = CIFileStatus.RcvComplete
    ): CIFile =
      CIFile(fileId = fileId, fileName = fileName, fileSize = fileSize, fileSource = if (filePath == null) null else CryptoFile.plain(filePath), fileStatus = fileStatus, fileProtocol = FileProtocol.XFTP)

    val cachedRemoteFileRequests = SnapshotStateMap<CryptoFile, Boolean>()
  }
}

@Serializable
data class CryptoFile(
  val filePath: String,
  val cryptoArgs: CryptoFileArgs?
) {

  val isAbsolutePath: Boolean
    get() = File(filePath).isAbsolute

  @Transient
  private var tmpFile: File? = null

  fun createTmpFileIfNeeded(): File {
    if (tmpFile == null) {
      val tmpFile = File(tmpDir, UUID.randomUUID().toString())
      tmpFile.deleteOnExit()
      ChatModel.filesToDelete.add(tmpFile)
      this.tmpFile = tmpFile
    }
    return tmpFile!!
  }

  fun deleteTmpFile()


; track event.id) {
        <event-registration-card [event]="event" />
        } }
      </mat-card-content>
    </mat-card>
    <mat-card appearance="outlined" class="registrations-pane-mobile">
      <mat-card-header>
        <mat-card-title>My Next Event</mat-card-title>
      </mat-card-header>
      <mat-card-content class="registrations-pane-content">
        @if(eventStatus()) { @if (eventStatus()!.registered.length === 0) {
        @if(profile) {

You are not registered for any events.

        } @else {

          You cannot register or view details for events until you sign in to
          the CSXL site.

        <button
          mat-button
          class="primary-button sign-in-button"
          (click)="signIn()">
          Sign In
        </button>
        } }
        <event-registration-card [event]="eventStatus()!.registered[0]" />
        }
      </mat-card-content>
    </mat-card>

    <search-bar
      class="mat-csxl-search-bar"
      [searchBarQuery]="searchBarQuery"
      (searchBarQueryChange)="onSearchBarQueryChange($event)" />

    <mat-card appearance="outlined" class="events-pane">
      <mat-card-header>
        <mat-card-title>Events</mat-card-title>
        <mat-chip-set
          class="pagination-chip-set"
          [disabled]="filterQuery().length > 0">
          <mat-chip (click)="previousPage()">
            <mat-icon class="primary-color"> keyboard_arrow_left </mat-icon>
          </mat-chip>

            <mat-chip disableRipple>
              <mat-icon class="primary-color" matChipAvatar> today </mat-icon>
              @if(filterQuery().length > 0) { Showing Search Results } @else {
              {{ startDate() | date: 'mediumDate' }} -
              {{ endDate() | date: 'mediumDate' }}
              }
            </mat-chip>

          <mat-chip (click)="nextPage()">
            <mat-icon class="primary-color">keyboard_arrow_right</mat-icon>
          </mat-chip>
        </mat-chip-set>
        <mat-divider />
      </mat-card-header>
      <mat-card-content class="events-pane-content">

        @if (eventsByDate().length === 0) {

          There are no events for the provided time range.

        } @for (eventGroup of eventsByDate(); track eventGroup) {
        <mat-card-subtitle class="date-header">
          {{ eventGroup[0] }}
        </mat-card-subtitle>
        @for (event of eventGroup[1]; track event.id) {
        <new-event-card
          [event]="event"
          [profile]="profile"
          (registrationChange)="reloadPage()" />
        } }
      </mat-card-content>
    </mat-card>

    <mat-icon>location_on</mat-icon>

        {{
          reservation.room


d能够保证同步方法或同步代码块中变量的复合操作的原子性；也能保证变量的可见性。
（2）volatile不能保证变量的复合操作的原子性；只能保证变量的可见性。

##### 7、JMM关于synchronized的两条规定（synchronized如何实现内存可见性）：

（1）线程加锁时，将清空工作内存中共享变量的值，从而使用共享变量时需要从主内存中重新读取最新的值。
（2）线程解锁时，必须把共享变量的最新值刷新到主内存中。

##### 8、synchronized线程执行互斥代码的六个过程：

（1）获得互斥锁；
（2）清空工作内存；
（3）从主内存中拷贝变量的最新值到工作内存；
（4）执行代码；
（5）将更改后的共享变量的值刷新到主内存；
（6）释放互斥锁。

##### 9、指令重排序：重排序不会对单线程带来内存可见性问题。但是多线程交互时，指令重排序可能会造成内存可见性问题。

10、volatile如何实现内存可见性：通过加入内存屏障和禁止重排序来优化实现的。
（1）对volatile变量执行写操作时，会在写操作后加入一条store屏障指令；
（2）对volatile变量执行读操作时，会在读操作前加入一条load屏障指令。

##### 11、volatile如何实现内存可见性：

（1）线程写volatile变量的过程：
    1.改变线程工作内存中volatile变量副本的值
    2.将改变后的副本的值从工作内存刷新的主内存

（2）线程读volatile变量的过程：
   1.从主内存中读取volatile变量的最新值到线程的工作内存中
   2.从工作内存中读取volatile变量的副本

##### 12、volatile不能保证变量复合操作的原子性：

> private int number = 0;
> number++; //不是原子操作
>
> number++的步骤
> 1.读取number的值
> 2.将number的值加1
> 3.写入最新的number的值

    synchronized(this){  //加入synchronized，变为原子操作
       number++;
    }

**private volatile int number = 0;**//变为volatile变量，无法保证原子性

##### volatile和synchronized的区别


login = {
			{
				1100,
				"亲~爱~的~！嘿~这是今天份的爱的拥抱哦！和亲爱的的拥抱，已经是我们之间必不可少的日常了呢~"
			}
		},
		home = {
			{
				1100,
				"亲爱的，你回来啦！出击没有受伤吧？有没有想柴郡呀？真是的，不用这么害羞嘛~！"
			}
		},
		headtouch = {
			{
				1100,
				"亲爱的，我又弄到了一些新的猫耳发饰，你来帮我试一下怎么样？……欸，不要躲开啦！明明戴着那么可爱~"
			}
		},
		main = {
			{
				1100,
				"nil|又在傻笑了？才没有傻笑呢！只是因为突然想起了亲爱的你嘛~|亲爱的，今天是想喝红茶呢，还是想喝果汁呢？我个人的推荐是自动售货机里的那款橙汁！…不，不会因为方便所以才推荐的哦？"
			}
		},
		mission_complete = {
			{
				1100,
				"任务完成！这些任务对我们来说小菜一碟啦~"
			}
		},
		touch2 = {
			{
				1100,
				"亲爱的！！…嗯？没什么事情哦？柴郡不能搞偷袭吗？"
			}
		},
		feeling5 = {
			{
				1100,
				"亲爱的~今天想去哪里~？想吃什么？有什么想问我的嘛？柴郡的话…想在亲爱的身边！想吃能和亲爱的一起吃的东西！最想说的是——亲爱的，最喜欢你啦！嘿嘿~"
			}
		}
	},
	[299040] = {
		touch = "",
		feeling3 = "",
		win_mvp = "",
		upgrade = "",
		expedition = "",
		main_extra = "",
		home = "",
		mission = "",
		id = 299040,
		skill = "",
		unlock = "",
		mail = "",
		lose = "",
		feeling4 = "",
		feeling1 = "",
		profile = "",
		mission_complete = "",
		headtouch = "",
		feeling2 = "",
		battle = "",
		login = "",
		detail = "",
		main = {
			{
				1100,
				"大家都想装上更强的鱼雷和火炮，都想加上更厚的装甲和更强力的引擎——虽然是没办法的事情，不过造价太高果然还是不行的吧|nil|来点青柠果汁如何？虽然有新鲜的水果是最好的，不过想要远洋航行的话，有些事还是得习惯习惯呢。"
			}
		},
		touch2 = {
			{
				1100,
				"大白天做些什么啊，你这是…"
			}
		},
		feeling5 = {
			{
				1100,
				"原来如此，这就是爱与被爱的感觉吗？不是试图掠夺对方，或是占有对方，而是有些紧张，又有些安心的矛盾情绪…真是奇妙。"
			}
		}
	},
	[499030] = {
		feeling3 = "",
		win_mvp = "",
		upgrade = "",
		expedition = "",
		main_extr


CdCCHCjhhwvQvXuKryL2s34Ma6CXsRzntSUTYVYxCQ9\",\n          1\n        ]\n      ]\n    },\n    \"active\": {\n      \"weight_threshold\": 1,\n      \"account_auths\": [],\n      \"key_auths\": [\n        [\n          \"STM6LUoAA8gCL9tHRz7v9xcwR4ZWD3KDRHP5t1U7UAZHdfanLxyBE\",\n          1\n        ]\n      ]\n    },\n    \"posting\": {\n      \"weight_threshold\": 1,\n      \"account_auths\": [],\n      \"key_auths\": [\n        [\n          \"STM8anmpHdfVE4AmwsDpcSXpRsydHysEbv6vGJkRQy1d1CC83zeTA\",\n          1\n        ]\n      ]\n    },\n    \"memo_key\": \"STM67RYDyEkP1Ja1jFehJ45BFGA9oHHUnRnYbxKJEtMhVQiHW3S3k\",\n    \"json_metadata\": \"{}\",\n    \"extensions\": []\n  }\n]\n\n\n\n\n\n\n\nVirtual Operation\n\n\n\n\n\nfill_convert_request\n\n\n\nFills when conversion requests with a conversion date before the head\nblock time and then converts them to/from steem/sbd at the current\nmedian price feed history price times the premium.\n\nRoles: active owner\nParameters: owner requestid amount_in amount_out\n\n\n\n\n\n\nVirtual Operation\n\n\n\n\n\nauthor_reward\n\n\n\n\nRoles: posting active owner\nParameters: author permlink sbd_payout steem_payout vesting_payout\n\n\n\n\n\n\nVirtual Operation\n\n\n\n\n\ncuration_reward\n\n\n\n\nRoles: posting active owner\nParameters: curator reward comment_author comment_permlink\n\n\n\n\n\nSince: HF17\n\n\nVirtual Operation\n\n\n\n\n\ncomment_reward\n\n\n\nSee: #774\n\nRoles: posting active owner\nParameters: author permlink payout\n\n\n\n\n\n\nVirtual Operation\n\n\n\nDisabled\n\n\n\nliquidity_reward\n\n\n\nDeprecated as of HF12, see: #178.\n\nRoles: active owner\nParameters: owner payout\n\n\n\n\n\n\nVirtual Operation\n\n\n\n\n\ninterest\n\n\n\n\nRoles: active owner\nParameters: owner interest\n\nExample Op:\n\n[\n  \"interest\",\n  {\"owner\": \"alice\", \"interest\": \"0.001 SBD\"}\n]\n\n\n\n\n\n\nSince: HF6\n\n\nVirtual Operation\n\n\n\n\n\nfill_vesting_withdraw\n\n\n\nSee: #78\n\nRoles: active owner\nParameters: from_account to_account withdrawn deposited\n\nExample Op:\n\n[\n  \"fill_vesting_withdraw\",\n  {\n    \"from_account\": \"alice\",\n    \"to_account\": \"alice\",\n    \"withdrawn\": \"0.026475 VESTS\",\n    \"deposited\": \"0.710 STEEM\"\n  }\n]\n\n\n\n\n\n\n\nVirtual Operation\n\n\n\n\n\nfill_order\n\n\n\n\nRoles: posting active owner\nParameters: current_owner current_orderid current_pays open_owner open_orderid open_pays\n\nExample Op:\n\n[\n  \"fill_order\",\n  {\n    \"current_owner\": \"alice\",\n    \"current_orderid\": 42896,\n    \"current_pays\": \"94.999 SBD\",\n    \"open_owner\": \"bob\",\n    \"open_orderid\


id", "ID session", base.HEX)
local pf_reply_id  = ProtoField.uint16("zk6.reply_id", "ID Reply")
local pf_commkey   = ProtoField.new   ("Communication key", "zk6.commkey", ftypes.UINT32, nil, base.HEX)
local pf_data      = ProtoField.new   ("Data(hex)", "zk6.data", ftypes.BYTES, nil, base.DOT)
local pf_data_len  = ProtoField.new   ("Data(length)", "zk6.data", ftypes.UINT32, nil)
local pf_string    = ProtoField.new   ("Data(string)", "zk6.string", ftypes.STRING)
local pf_time      = ProtoField.new   ("Time", "zk6.time", ftypes.UINT32, nil)
local pf_start     = ProtoField.new   ("Data offset", "zk6.start", ftypes.UINT32, nil)
local pf_size      = ProtoField.new   ("Data Size", "zk6.size", ftypes.UINT32, nil)
local pf_psize     = ProtoField.new   ("Packet Size", "zk6.psize", ftypes.UINT32, nil)
local pf_fsize0    = ProtoField.new   ("null #1", "zk6.fsize0", ftypes.UINT32, nil)
local pf_fsize1    = ProtoField.new   ("null #2", "zk6.fsize1", ftypes.UINT32, nil)
local pf_fsize2    = ProtoField.new   ("null #3", "zk6.fsize2", ftypes.UINT32, nil)
local pf_fsize3    = ProtoField.new   ("null #4", "zk6.fsize3", ftypes.UINT32, nil)
local pf_fsizeu    = ProtoField.new   ("users", "zk6.fsizeu", ftypes.UINT32, nil)
local pf_fsize4    = ProtoField.new   ("null #5", "zk6.fsize4", ftypes.UINT32, nil)
local pf_fsizef    = ProtoField.new   ("fingers", "zk6.fsizef", ftypes.UINT32, nil)
local pf_fsize5    = ProtoField.new   ("null #6", "zk6.fsize5", ftypes.UINT32, nil)
local pf_fsizer    = ProtoField.new   ("records", "zk6.fsizer", ftypes.UINT32, nil)
local pf_fsize6    = ProtoField.new   ("null #7", "zk6.fsize6", ftypes.UINT32, nil)
local pf_fsize7    = ProtoField.new   ("null 4096", "zk6.fsize7", ftypes.UINT32, nil)
local pf_fsize8    = ProtoField.new   ("null #8", "zk6.fsize8", ftypes.UINT32, nil)
local pf_fsizec    = ProtoField.new   ("cards", "zk6.fsizec", ftypes.UINT32, nil)
local pf_fsize9    = ProtoField.new   ("null #9", "zk6.fsize9", ftypes.UINT32, nil)
local pf_fsizefc   = ProtoField.new   ("finger capacity", "zk6.fsizefc", ftypes.UINT32, nil)
local pf_fsizeuc   = ProtoField.new   ("user capacity", "zk6.fsizeuc", ftypes.UINT32, nil)
local pf_fsizerc   = ProtoField.new   ("record capacity", "zk6.fsizerc", ftypes.UINT32, nil)
local pf_fsizefa   = ProtoField.new   ("finger available", "zk6.fsizefa", ftypes.UINT


(
					key = a.attr("href").substringAfterLast('/'),
					title = a.text().toTitleCase(sourceLocale),
					source = source,
				)
			},
			authors = setOfNotNull(author),
			state = when (doc.selectFirst("div.y6x11p i.fas.fa-rss + span.dt")?.text()?.lowercase().orEmpty()) {
				in ongoing -> MangaState.ONGOING
				in finished -> MangaState.FINISHED
				in paused -> MangaState.PAUSED
				in abandoned -> MangaState.ABANDONED
				else -> null
			},
			chapters = doc.selectOrThrow("ul > li.chapter").mapChapters(reversed = true) { i, element ->
				val href = element.selectFirstOrThrow("a").attrAsRelativeUrl("href")
				MangaChapter(
					id = generateUid(href),
					title = element.selectFirst("a")?.textOrNull(),
					number = i + 1f,
					volume = 0,
					url = href,
					scanlator = null,
					uploadDate = element.selectFirst("time[datetime]")?.attr("datetime")?.toLongOrNull()?.times(1000)
						?: 0L,
					branch = null,
					source = source,
				)
			},
		)
	}

	override suspend fun getPages(chapter: MangaChapter): List<MangaPage> {
		val fullUrl = chapter.url.toAbsoluteUrl(domain)
		val doc = webClient.httpGet(fullUrl).parseHtml()

		val script = doc.selectFirstOrThrow("script:containsData(const CHAPTER_ID)").data()

		val chapterId = script.substringAfter("const CHAPTER_ID = ", "").substringBefore(';', "")
		check(chapterId.isNotEmpty()) { "Failed to get chapter id" }

		val ajaxUrl = buildString {
			append("https://")
			append(domain)
			append("/ajax/image/list/chap/")
			append(chapterId)
		}

		val responseJson = webClient.httpGet(ajaxUrl).parseJson()

		check(responseJson.getBooleanOrDefault("status", false)) { responseJson.getString("msg") }

		val pageListDoc = Jsoup.parse(responseJson.getString("html"))

		return pageListDoc.selectOrThrow("div").map {
			val url = it.selectFirstOrThrow("img").attr("src")
			MangaPage(
				id = generateUid(url),
				url = url,
				preview = null,
				source = source,
			)
		}
	}

	protected open suspend fun getAvailableTags(): Set<MangaTag> = coroutineScope {
		val doc = webClient.httpGet("https://$domain/filter").parseHtml()
		doc.select("div.advanced-genres > div > .advance-item").mapToSet { element ->
			MangaTag(
				key = element.selectFirstOrThrow("span[data-genre]").attr("data-genre"),
				title = element.text().toTitleCase(sourceLocale),
				source = source,
			)
		}
	}
}
package org.koitharu.kotatsu.parsers.site.all

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import okhttp3.HttpUrl
import org.json.JSONArray
import org.json.JSONObject
import org.koitharu.kotatsu.parsers.MangaLoaderContext
import org.koitharu.kotatsu.parsers.MangaSourceParser
import org.koitharu.kotatsu.parsers.config.ConfigKey
import org.koitharu.kotatsu.parsers.core.FlexibleMangaParser
import org.koitharu.kotatsu.parsers.exception.ParseException
import org.koitharu.kotatsu.parsers.model.*
import org.koitharu.kotatsu.parsers.model.search.MangaSearchQuery
import org.koith


_leaflist>())).dflts as *const _
                as usize
        },
        192usize,
        concat!(
            "Offset of field: ",
            stringify!(lysp_node_leaflist),
            "::",
            stringify!(dflts)
        )
    );
    assert_eq!(
        unsafe {
            &(*(::std::ptr::null::<lysp_node_leaflist>())).min as *const _
                as usize
        },
        200usize,
        concat!(
            "Offset of field: ",
            stringify!(lysp_node_leaflist),
            "::",
            stringify!(min)
        )
    );
    assert_eq!(
        unsafe {
            &(*(::std::ptr::null::<lysp_node_leaflist>())).max as *const _
                as usize
        },
        204usize,
        concat!(
            "Offset of field: ",
            stringify!(lysp_node_leaflist),
            "::",
            stringify!(max)
        )
    );
}
impl Default for lysp_node_leaflist {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct lysp_node_list {
    pub __bindgen_anon_1: lysp_node_list__bindgen_ty_1,
    pub musts: *mut lysp_restr,
    pub when: *mut lysp_when,
    pub key: *const ::std::os::raw::c_char,
    pub typedefs: *mut lysp_tpdf,
    pub groupings: *mut lysp_node_grp,
    pub child: *mut lysp_node,
    pub actions: *mut lysp_node_action,
    pub notifs: *mut lysp_node_notif,
    pub uniques: *mut lysp_qname,
    pub min: u32,
    pub max: u32,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union lysp_node_list__bindgen_ty_1 {
    pub node: lysp_node,
    pub __bindgen_anon_1: lysp_node_list__bindgen_ty_1__bindgen_ty_1,
    _bindgen_union_align: [u64; 8usize],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct lysp_node_list__bindgen_ty_1__bindgen_ty_1 {
    pub parent: *mut lysp_node,
    pub nodetype: u16,
    pub flags: u16,
    pub next: *mut lysp_node,
    pub name: *const ::std::os::raw::c_char,
    pub dsc: *const ::std::os::raw::c_char,
    pub ref_: *const ::std::os::raw::c_char,
    pub iffeatures: *mut lysp_qname,
    pub exts: *mut lysp_ext_instance,
}
#[test]
fn bindgen_test_layout_lysp_node_list__bindgen_ty_1__bindgen_ty_1() {
    assert_eq!(
        ::std::mem::size_of::<lysp_node_list__bindgen_ty_1__bindgen_ty_1>(),
        64usize,
        concat!(
            "Size of: ",
            stringify!(lysp_node_list__bindgen_ty_1__bindgen_ty_1)
        )
    );
    assert_eq!(
        ::std::mem::align_of::<lysp_node_list__bindgen_ty_1__bindgen_ty_1>(),
        8usize,
        concat!(
            "Alignment of ",
            stringify!(lysp_node_list__bindgen_ty_1__bindgen_ty_1)
        )
    );
    assert_eq!(
        unsafe {
            &(*(::std::ptr::null::<lysp_node_list__bindgen_ty_1__bindgen_ty_1>(
            )))
            .parent as *const _ as usize
        },
        0usize,
        concat!(
            "Offset of field: ",


nText.text = kicking ? "KICK AND REPORT" : "REPORT";
    kickButton.gameObject.SetActive(kicking);
  }

  void Kick()
  {
    networking.KickPlayer(reportee);
    Close();
  }

  void Report()
  {
    string description = descriptionInputText.text;
    if (description.IsNullOrEmpty())
    {
      return;
    }

    if (!PhotonNetwork.isMasterClient && reportee != PhotonNetwork.masterClient)
    {
      networking.SendReportToMasterClient(reportee.NickName, description);
    }

#if USE_PUN
    object steamId = "(N/A)";
    reportee.CustomProperties.TryGetValue((object)NetworkingController.SteamIdPlayerProperty, out steamId);
#endif

    // Feedback
    if (reportee != PhotonNetwork.masterClient)
    {
      popups.Show("Thank you for reporting the player. We will review your message and take appropriate action if necessary. The Game Master has also been notified and may kick the player from the game.", "OK", () => { }, 800f);
    }
    else
    {
      popups.Show(new DynamicPopup.Popup
      {
        fullWidthButtons = true,
        textWrapWidth = 800f,
        getMessage = () => $"Thank you for reporting the player. We will review your message and take appropriate action if necessary. Would you like to leave the current game or continue playing?",
        buttons = new List<PopupButton.Params>() {
          new PopupButton.Params{ getLabel = () => "Leave Game", onClick = () => scenes.LoadSplashScreen()},
          new PopupButton.Params { getLabel = () => "Continue Playing", onClick = () => { } }
        }
      });
    }

    if (kicking) networking.KickPlayer(reportee);
    Close();
  }
}


и верованиями. Племена людей-ящериц обычно возглавляет король ящериц, который значительно крупнее и могущественнее своих сородичей. Люди-ящерицы не часто вступают в конфликт с людьми, но их пристрастие к вкусу человеческой плоти часто становится причиной проблем.",
	RGB_MINO = "Минотавры - это либо проклятые люди, либо потомство минотавров и людей. Обычно они обитают в подземных лабиринтах, поскольку в таких местах они не путаются под ногами, что даёт им преимущество перед добычей. Минотавры огромны, их рост превышает 7 футов, они довольно широки и мускулисты. У них голова быка, но тело человеческого мужчины. Их мех от коричневого до чёрного, а окраска тела варьируется, как у обычного человека. Одежда минимальна, обычно это набедренная повязка или юбка.",
	RGB_YUAN = "Эти существа - редкие, но чрезвычайно смертоносные противники. Юань-ти - ответвление расы, правившей Фаэруном задолго до прихода гуманоидов. Обладая змееподобными телами и конечностями, напоминающими человеческие, юань-ти прячутся в тайных хранилищах, пока не наступит подходящий момент, чтобы нанести удар по своим врагам. Юань-ти - чрезвычайно умные враги, обладающие сложнейшими магическими талантами. Они известны своим хитрым умом, ядовитыми ловушками и мерзкими религиозными ритуалами.",
	RGB_MUMM = "Мумии - это трупы, обитающие в засушливых пустынных районах, где мёртвые погребены в результате процесса, известного как мумификация. Когда их гробницы тревожат, трупы оживают, превращаясь в странное неживое состояние, чья нечестивая ненависть к жизни заставляет их без жалости нападать на живых существ. Мумии обычно (но не всегда) одеты в гниющие полоски льна. Их рост составляет от 5 до 7 футов, и они обладают сверхъестественной силой.",
	RGB_MUMG = "Также известные как Дети Анхктепота, большие мумии - это мощная форма нежити, созданная, когда высокопоставленный законный злой священник определённых рел


eyword());
        assertEquals("$", assertions.get(1).getInstanceLocation().toString());
        assertEquals("$.oneOf[0].additionalProperties", assertions.get(1).getEvaluationPath().toString());

        assertEquals("type", assertions.get(2).getKeyword());
        assertEquals("$.test", assertions.get(2).getInstanceLocation().toString());
        assertEquals("$.oneOf[1].additionalProperties.type", assertions.get(2).getEvaluationPath().toString());

        assertEquals("type", assertions.get(3).getKeyword());
        assertEquals("$.test", assertions.get(3).getInstanceLocation().toString());
        assertEquals("$.oneOf[2].additionalProperties.type", assertions.get(3).getEvaluationPath().toString());
    }

    @Test
    void invalidTypeShouldThrowJsonSchemaException() {
        String schemaData = "{\r\n"
                + "  \"$defs\": {\r\n"
                + "    \"User\": true\r\n"
                + "  },\r\n"
                + "  \"oneOf\": {\r\n"
                + "    \"$ref\": \"#/defs/User\"\r\n"
                + "  }\r\n"
                + "}";
        SchemaRegistry factory = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12);
        SchemaException ex = assertThrows(SchemaException.class, () -> factory.getSchema(schemaData));
        assertEquals("type", ex.getError().getMessageKey());
    }

    /**
     * This test checks that the oneOf example at
     * https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/
     * behaves according to the specification instead of the example.
     * <p>
     * https://github.com/swagger-api/swagger.io/issues/253
     * https://github.com/OAI/OpenAPI-Specification/issues/3477
     * https://github.com/networknt/json-schema-validator/issues/110
     */
    @Test
    void invalidSwaggerIoExample() {
        String document = "paths:\r\n"
                + "  /pets:\r\n"
                + "    patch:\r\n"
                + "      requestBody:\r\n"
                + "        content:\r\n"
                + "          application/json:\r\n"
                + "            schema:\r\n"
                + "              oneOf:\r\n"
                + "                - $ref: '#/components/schemas/Cat'\r\n"
                + "                - $ref: '#/components/schemas/Dog'\r\n"
                + "      responses:\r\n"
                + "        '200':\r\n"
                + "          description: Updated\r\n"
                + "components:\r\n"
                + "  schemas:\r\n"
                + "    Dog:\r\n"
                + "      type: object\r\n"
                + "      properties:\r\n"
                + "        bark:\r\n"
                + "          type: boolean\r\n"
                + "        breed:\r\n"
                + "          type: string\r\n"
                + "          enum: [Dingo, Husky, Retriever, Shepherd]\r\n"
                + "    Cat:\r\n"
                + "      type: object\r\n"
                + "      properties:\r\n"
                + "        hunts:\r\n"
                + "          type: boolean\r\n"
                + "        age:\r\n"
                + "          type: integer";

        Schema schema = SchemaRegistry
                .withDefaultDialect(SpecificationVersion.DRAFT_2020_12,
                        builder -> builder.resourceLoaders(resourceLoaders -> resourceLoaders
                                .resources(Collections.singletonMap("http://example.org/example.yaml", document))))
                .getSchema(SchemaLocation.of(
                        "http://example.org/example.yaml#/paths/~1pets/patch


днако производительность не идеальна, поскольку обычно только один процесс запускается или останавливается за раз.

При использовании Sys V состояние машины определяется уровнями выполнения (runlevels), которые задаются от 0 до 6. Эти различные режимы будут варьироваться в зависимости от дистрибутива, но в большинстве случаев они выглядят следующим образом:

- 0: Выключение (Shutdown)
- 1: Режим одного пользователя (Single User Mode)
- 2: Многопользовательский режим без сети (Multiuser mode without networking)
- 3: Многопользовательский режим с сетью (Multiuser mode with networking)
- 4: Не используется (Unused)
- 5: Многопользовательский режим с сетью и графическим интерфейсом (Multiuser mode with networking and GUI)
- 6: Перезагрузка (Reboot)

Когда ваша система загружается, она проверяет, в каком уровне выполнения она находится, и выполняет скрипты, расположенные в конфигурации этого уровня выполнения. Скрипты находятся в **/etc/rc.d/rc[runlevel number].d/** или **/etc/init.d**. Скрипты, начинающиеся с S (start — запуск) или K (kill — остановка), будут выполняться при запуске и выключении соответственно. Числа, следующие за этими символами, указывают последовательность их выполнения.

Например:

```bash
pete@icebox:/etc/rc.d/rc0.d$ ls
K10updates  K80openvpn
```

Мы видим, что при переключении на уровень выполнения 0 или режим выключения наша машина попытается выполнить скрипт для остановки служб обновлений, а затем OpenVPN. Чтобы узнать, в какой уровень выполнения загружается ваша машина, вы можете посмотреть уровень выполнения по умолчанию в файле `/etc/inittab`. Вы также можете изменить уровень выполнения по умолчанию в этом файле.

Стоит отметить: System V в большинстве современных дистрибутивов Linux был в значительной степени заменен systemd. Однако вы можете встретить упоминания об уровнях выполнения в других реализациях init. Это в основном сделано для поддержки тех служб, которые запускаются или останавливаются с использованием скриптов System V init.

## Exercise

Практика ведет к совершенству! Вот несколько практических лабораторных работ для закрепления вашего понимания управления процессами Linux и системной конфигурац


owned().into(), limits)
            .is_ok());
        assert!(metadata
            .insert_with_limits(Name::new("1")?, "23456".to_owned().into(), limits)
            .is_err());
        Ok(())
    }

    #[test]
    // This test is a good candidate for both property-based and parameterised testing
    fn insert_exceeds_len() -> Result<(), TestError> {
        let mut metadata = Metadata::new();
        let limits = Limits::new(2, 5);
        assert!(metadata
            .insert_with_limits(Name::new("1")?, "0".to_owned().into(), limits)
            .is_ok());
        assert!(metadata
            .insert_with_limits(Name::new("2")?, "0".to_owned().into(), limits)
            .is_ok());
        assert!(metadata
            .insert_with_limits(Name::new("2")?, "1".to_owned().into(), limits)
            .is_ok());
        assert!(metadata
            .insert_with_limits(Name::new("3")?, "0".to_owned().into(), limits)
            .is_err());
        Ok(())
    }
}
use libc::c_char;
use poly::polynomial;
use poly::polynomial::PolyPrinter;
use std::ffi::{CStr, CString};
use std::ops::{Add, Div, Mul, Neg, Sub};
use std::str;
use std::str::FromStr;
use structure::{Element, VarInfo};

#[derive(Clone)]
pub struct Polynomial<'a> {
    poly: polynomial::Polynomial,
    var_info: &'a VarInfo,
}

#[derive(Clone)]
pub struct RationalPolynomial<'a> {
    num: Polynomial<'a>,
    den: Polynomial<'a>,
}

impl<'a> RationalPolynomial<'a> {
    fn from_poly(mut num: Polynomial<'a>, mut den: Polynomial<'a>) -> RationalPolynomial<'a> {
        assert_eq!(
            &num.var_info.global_info as *const _,
            &den.var_info.global_info as *const _
        );

        polynomial::rationalpolynomial_normalize(&mut num.poly, &mut den.poly);
        RationalPolynomial { num, den }
    }

    fn to_string(&self) -> String {
        format!("({})/({})", self.num.to_string(), self.den.to_string())
    }

    fn neg(&self) -> RationalPolynomial {
        RationalPolynomial {
            num: self.num.neg(),
            den: self.den.clone(),
        }
    }

    fn add(&self, rhs: &RationalPolynomial) -> RationalPolynomial<'a> {
        let mut l = self.clone();
        let mut r = rhs.clone();
        // TODO: unify?
        polynomial::rationalpolynomial_add(
            &mut l.num.poly,
            &mut l.den.poly,
            &mut r.num.poly,
            &mut r.den.poly,
        );
        l
    }

    fn sub(&self, rhs: &RationalPolynomial) -> RationalPolynomial<'a> {
        let mut l = self.clone();
        let mut r = rhs.clone();
        // TODO: unify?
        polynomial::rationalpolynomial_sub(
            &mut l.num.poly,
            &mut l.den.poly,
            &mut r.num.poly,
            &mut r.den.poly,
        );
        l
    }

    fn mul(&self, rhs: &RationalPolynomial) -> RationalPolynomial<'a> {
        let mut l = self.clone();
        let mut r = rhs.clone();


"+i+" .modebar-btn:hover .icon path","fill: "+o.activecolor),a.addRelatedStyleRule(i,"#"+i+" .modebar-btn.active .icon path","fill: "+o.activecolor);var l=!this.hasButtons(e),c=this.hasLogo!==r.displaylogo,u=this.locale!==r.locale;if(this.locale=r.locale,(l||c||u)&&(this.removeAllButtons(),this.updateButtons(e),r.watermark||r.displaylogo)){var f=this.getLogo();r.watermark&&(f.className=f.className+" watermark"),"v"===n.modebar.orientation?this.element.insertBefore(f,this.element.childNodes[0]):this.element.appendChild(f),this.hasLogo=!0}this.updateActiveButton()},c.updateButtons=function(t){var e=this;this.buttons=t,this.buttonElements=[],this.buttonsNames=[],this.buttons.forEach((function(t){var r=e.createGroup();t.forEach((function(t){var n=t.name;if(!n)throw new Error("must provide button 'name' in button config");if(-1!==e.buttonsNames.indexOf(n))throw new Error("button name '"+n+"' is taken");e.buttonsNames.push(n);var i=e.createButton(t);e.buttonElements.push(i),r.appendChild(i)})),e.element.appendChild(r)}))},c.createGroup=function(){var t=document.createElement("div");return t.className="modebar-group",t},c.createButton=function(t){var e=this,r=document.createElement("a");r.setAttribute("rel","tooltip"),r.className="modebar-btn";var i=t.title;void 0===i?i=t.name:"function"==typeof i&&(i=i(this.graphInfo)),(i||0===i)&&r.setAttribute("data-title",i),void 0!==t.attr&&r.setAttribute("data-attr",t.attr);var a=t.val;if(void 0!==a&&("function"==typeof a&&(a=a(this.graphInfo)),r.setAttribute("data-val",a)),"function"!=typeof t.click)throw new Error("must provide button 'click' function in button config");r.addEventListener("click",(function(r){t.click(e.graphInfo,r),e.updateActiveButton(r.currentTarget)})),r.setAttribute("data-toggle",t.toggle||!1),t.toggle&&n.select(r).classed("active",!0);var s=t.icon;return"function"==typeof s?r.appendChild(s()):r.appendChild(this.createIcon(s||o.question)),r.setAttribute("data-gravity",t.gravity||"n"),r},c.createIcon=function(t){var e,r=i(t.height)?Number(t.height):t.ascent-t.descent,n="http://www.w3.org/2000/svg";if(t.path){(e=document.createElementNS(n,"svg")).setAttribute("viewBox",[0,0,t.width,r].join(" ")),e.setAttribute("class","icon");var a=document.createElementNS(n,"path");a.setAttribute("d",t.path),t.transform?a.setAttribute("transform",t.transform):void 0!==t.ascent&&a.setAttribute("transform","matrix(1 0 0 -1 0 "+t.ascent+")"),e.appendChild(a)}t.svg&&(e=s.parseFromString(t.svg,"application/xml").childNodes[0]);return e.setAttribute("height","1em"),e.setAttribute("


/* 0E7820 80186DE0 5329000D */  beql  $t9, $t1, .L80186E18_ovl3
/* 0E7824 80186DE4 8FBF002C */   lw    $ra, 0x2c($sp)
/* 0E7828 80186DE8 8D4AA7C4 */  lw    $t2, %lo(D_8004A7C4)($t2)
/* 0E782C 80186DEC 3C04800E */ lui $a0, %hi(gEntityGObjProcessArray)
/* 0E7830 80186DF0 3C058017 */  lui   $a1, %hi(D_8016C510) # $a1, 0x8017
/* 0E7834 80186DF4 8D4B0000 */  lw    $t3, ($t2)
/* 0E7838 80186DF8 24A5C510 */  addiu $a1, %lo(D_8016C510) # addiu $a1, $a1, -0x3af0
/* 0E783C 80186DFC 000B6080 */  sll   $t4, $t3, 2
/* 0E7840 80186E00 008C2021 */  addu  $a0, $a0, $t4
/* 0E7844 80186E04 0C02C7B2 */  jal   assign_new_process_entry
/* 0E7848


        await markingDefinitionDeleteAndUpdateGroups(context, user, element.id, { forceDelete: true });
      } else {
        const forceDelete = opts.forceDelete !== undefined ? opts.forceDelete : true;
        await deleteElementById(context, user, element.id, element.entity_type, { forceDelete });
      }
      return element.id;
    }
    throw UnsupportedError('This method can only delete Stix element');
  }
  throw FunctionalError(`Cannot delete the stix element, ${id} cannot be found.`);
};

export const stixObjectMerge = async (context, user, targetId, sourceIds) => {
  return mergeEntities(context, user, targetId, sourceIds);
};

export const sendStixBundle = async (context, user, connectorId, bundle, work_id) => {
  try {
    // 01. Simple check bundle
    const jsonBundle = JSON.parse(bundle);
    if (jsonBundle.type !== 'bundle' || !jsonBundle.objects || jsonBundle.objects.length === 0) {
      throw UnsupportedError('Invalid stix bundle');
    }
    // 02. Create work and send the bundle to ingestion
    const connector = await storeLoadById(context, user, connectorId, ENTITY_TYPE_CONNECTOR);
    if (!connector) {
      throw UnsupportedError('Invalid connector');
    }
    let target_work_id = work_id;
    if (isEmptyField(work_id)) {
      const workName = `${connector.name} run @ ${now()}`;
      const work = await createWork(context, user, connector, workName, connector.internal_id, { receivedTime: now() });
      target_work_id = work.id;
      if (jsonBundle.objects.length === 1) {
        // Only add explicit expectation if the worker will not split anything
        await updateExpectationsNumber(context, context.user, target_work_id, jsonBundle.objects.length);
      }
    }
    const content = Buffer.from(bundle, 'utf-8').toString('base64');
    await pushToWorkerForConnector(connectorId, {
      type: 'bundle',
      applicant_id: user.internal_id,
      content,
      work_id: target_work_id,
      update: true
    });
    return true;
  } catch (err) {
    throw UnsupportedError('Invalid bundle', { cause: err });
  }
};

export const askListExport = async (context, user, exportContext, format, selectedIds, listParams, type, contentMaxMarkings, fileMarkings) => {
  if (!exportContext || !exportContext?.entity_type) {
    throw FunctionalError('entity_type is missing from askListExport');
  }

  const connectors = await connectorsForExport(context, user, format, true);
  const markingLevels = await Promise.all(contentMaxMarkings.map(async (id) => {
    return await findMarkingDefinitionById(context, user, id);
  }));
  await checkUserCanShareMarkings(context, user, markingLevels);
  const fileNameMarkingLevels = markingLevels.map((markingLevel) => markingLevel?.definition).join('_');

  const entity = exportContext.entity_id ? await storeLoadById(context, user, exportContext.entity_id, ABSTRACT_STIX_CORE_OBJECT) : null;
  const { entity_type } = exportContext;

  const toFileName = (connector) => {
    const fileNamePart = `${entity_type}_${type}.${mime.extension(format) ? mime.extension(format) : specialTypesExtensions[format] ?? 'unknown'}`;
    return `${now()}_${fileNameMarkingLevels || 'TLP:ALL'}_(${connector.name})_${fileNamePart}`;
  };

  const markingList = await getEntitiesListFromCache(context, user, ENTITY_TYPE_MARKING_DEFINITION);

  const { markingFilter, mainFilter } = await getExportFilter(user, { markingList, contentMaxMarkings, objectIdsList: selectedIds });

  const baseEvent = {
    format, // extension mime type
    export_type: type, //


Scene        = nil --
end

--ʼ
function initRelease()

	---------list
	nGridWidth = SX(70)
	mMagicList_Width  = pWinSize.width*0.9
	mMagicList_Height = pWinSize.height*0.33
	mMagicList_StartX = SX(24)
	mMagicList_StartY = pWinSize.height*0.51

    	mMagicDetail_StartX = SX(24)
	mMagicDetail_Width  = mMagicList_Width
	mMagicDetail_Height = pWinSize.height*0.27
	mMagicDetail_StartY = pWinSize.height*0.22
	mCurrentTabIndex = 1
	mCurrentListIndex = 1
	mNowPage = 1
	mMaxPage = 1
	mUserExperience = 0 --ʣ
	mMagicColdTime  = 0--ȴʱ
	mMagicDataList = {}
	mTeamMagicDataList = {}
	mMagicListCur_MagicID   = 1--ħid
	mMagicListCur_MagicType = 2--ħ
	mMagicListCur_MagicName = 3--ħ
	mMagicListCur_HeadID    = 4--ͼƬid
	mMagicListCur_MagicLv   = 5--ħȼ
	mMagicListCur_IsUp      = 6--Ƿ
end

function init()
	if magicScene ~= nil then
		return
	end
    local scene = ScutScene:new()  --
	scene:registerCallback(netCallback)--ص
	magicScene = scene.root
	magicScene:registerScriptHandler(SpriteEase_onEnterOrExit)
	SlideInLReplaceScene(magicScene,1)

	initRelease() -----ʼ

	mLayer = CCLayer:create()    -----
	mLayer:setPosition(PT(0,0))  -----
	magicScene:addChild(mLayer,2)

	--
	creatBg()

	mTopListLayer     = CCLayer:create();
	mTopListLayer:setPosition(PT(0,0))
	mLayer:addChild(mTopListLayer,2)  -------------------

	MainMenuLayer.init(2, mLayer)

	createTabBar(tabName) ----л

	creatMagicLayer()  -----ħ汳

	sendRequestDataListFirst()------һ

	schedulerEntry1 = 	CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(timeElapse, 1, false)
	--CCScheduler:sharedScheduler():scheduleScriptFunc("MagicScene.timeElapse",1, false)---
end

function creatBg()
	local midSprite=CCSprite:create(P(Image.image_halfbackground))
	local boxSize=SZ(pWinSize.width,pWinSize.height*0.855)
	midSprite:setScaleX(boxSize.width/midSprite:getContentSize().width)
	midSprite:setScaleY(boxSize.height/midSprite:getContentSize().height)
	midSprite:setAnchorPoint(PT(0,0))
	midSprite:setPosition(PT(0,pWinSize.height*0.145))
	mLayer:addChild(midSprite,0)

	local headTitleBg=CCSprite:create(P("title/list_1104.png"))
	headTitleBg:setAnchorPoint(PT(0.5, 1))
	headTitleBg:setPosition(CCPoint(pWinSize.width/2, pWinSize.height*0.96))
	mLayer:addChild(headTitleBg, 0)
end;

function SpriteEase_onEnterOrExit (tag)
    if tag == "exit" then
        release()
    end
end

--ħ汳
function creatMagicLayer()
	if magicLayer ~= nil then
		magicLayer:getParent():removeChild(magicLayer,true)
		magicLayer = nil
	end
	magicLayer = CCLayer:create()
	mLayer:addChild(magicLayer,0)

	local left_background  = CCSprite:create(P("common/list_1038.9.png"));--
	left_background:


* Private helper to construct a graph from a specific list of memories. Ensures that edges are
     * only created if both source and target nodes are in the list.
     */
    private fun buildGraphFromMemories(memories: List<Memory>): Graph {
        val memoryUuids = memories.map { it.uuid }.toSet()

        val nodes =
                memories.map { memory ->
                    Node(
                            id = memory.uuid,
                            label = memory.title,
                            color =
                                    if (memory.isDocumentNode) {
                                        Color(0xFF9575CD) // Purple for documents
                                    } else {
                                    when (memory.tags.firstOrNull()?.name) {
                                        "Person" -> Color(0xFF81C784) // Green
                                        "Concept" -> Color(0xFF64B5F6) // Blue
                                        else -> Color.LightGray
                                        }
                                    }
                    )
                }

        val edges = mutableListOf<Edge>()
        memories.forEach { memory ->
            // 关键：重置关系缓存，确保获取最新的连接信息
            memory.links.reset()
            memory.links.forEach { link ->
                val sourceId = link.source.target?.uuid
                val targetId = link.target.target?.uuid
                // Only add edges if both source and target are in the filtered list
                if (sourceId != null &&
                    targetId != null &&
                    sourceId in memoryUuids &&
                    targetId in memoryUuids
                ) {
                    edges.add(
                        Edge(
                            id = link.id,
                            sourceId = sourceId,
                            targetId = targetId,
                            label = link.type,
                            weight = link.weight
                        )
                    )
                } else if (sourceId != null && targetId != null) {
                    // Log discarded edges for debugging
                    // android.util.Log.d("MemoryRepo", "Discarding edge: $sourceId -> $targetId
                    // (Not in filtered list)")
                }
            }
        }
        android.util.Log.d(
                "MemoryRepo",
                "Built graph with ${nodes.size} nodes and ${edges.distinct().size} edges."
        )
        return Graph(nodes = nodes, edges = edges.distinct())
    }
}
package com.abaga129.tekisuto.util

import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.SuperscriptSpan
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.abaga129.tekisuto.R

/**
 * Helper class for handling pitch accent display
 */
class PitchAccentHelper {
    companion object {
        private const val TAG = "PitchAccentHelper"

        /**
         * Configure the pitch accent view with appropriate styles
         *
         * @param context The context for accessing resources
         * @param pitchAccentView The TextView for displaying the pitch accent data
         * @param pitchAccent The pitch accent pattern to display
         */
        fun setupPitchAccentView(
            context: Context,
            pitchAccentView: TextView,
            pitchAccent: String
        ) {
            // Try to format the pitch accent based on its type
            val formattedText = formatPitchAccent(context, pitchAccent)

            // Set the text in the view
            pitchAccentView.text = formattedText

            // Make the view visible
            pitchAccentView.visibility = View.VISIBLE
        }

        /**
         * Format the pitch accent pattern appropriately
         *
         * @param context The context for accessing resources
         * @param pitchAccent The pitch accent pattern to format
         * @return A fo


-- multilanguage text table
-- if Yo want add your supported mother language, extend table and let me know, I will push it in the Git
-- Warm thanks to my Italian colleague Francesco Salvi for the translation into Italian

local transtable        = { en = { wgname          = "Flights",
                                   menuname        = "Flights",
                                   frame           = "Border",
                                   txtColorF       = "Select flights text color",
                                   txtColorT       = "Select time text color",
                                   preset          = "Preset",
                                   flights         = " Flights",
                                   flightswitch    = "Flight active switch",
                                   trigger         = "Trigger switch",
                                   trigerdelay     = "Trigger delay",
                                 },
                            cs = {
                                   wgname          = "Citac letu",
                                   menuname        = "Čítač letů",
                                   frame           = "Rámeček",
                                   txtColorF       = "Barva textu letů",
                                   txtColorT       = "Barva textu


local o = vim.o

---@type LazySpec
return {
  "kevinhwang91/nvim-ufo",
  event = "VeryLazy",
  init = function()
    o.foldcolumn = "1"
    o.foldlevel = 99
    o.foldlevelstart = 99
    o.foldenable = true
  end,
  ---@module 'ufo'
  ---@type UfoConfig
  opts = {
    close_fold_kinds_for_ft = {
      default = {
        "imports",
      },
    },
    preview = {
      win_config = {
        winblend = vim.o.winblend,
      },
    },
  },
  keys = {
    {
      "zR",
      function()
        require("ufo").openAllFolds()
      end,
      desc = "Nvim UFO | Open All Folds",
      silent = true,
    },
    {
      "zM",
      function()
        require("ufo").closeAllFolds()
      end,
      desc = "Nv


loatBlockEXT";
      case Format::eAstc12x10SfloatBlockEXT : return "Astc12x10SfloatBlockEXT";
      case Format::eAstc12x12SfloatBlockEXT : return "Astc12x12SfloatBlockEXT";
      case Format::eA4R4G4B4UnormPack16EXT : return "A4R4G4B4UnormPack16EXT";
      case Format::eA4B4G4R4UnormPack16EXT : return "A4B4G4R4UnormPack16EXT";
      default: return "invalid ( " + VULKAN_HPP_NAMESPACE::toHexString( static_cast<uint32_t>( value ) ) + " )";
    }
  }

  enum class FormatFeatureFlagBits : VkFormatFeatureFlags
  {
    eSampledImage = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT,
    eStorageImage = VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT,
    eStorageImageAtomic = VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT,
    eUniformTexelBuffer = VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT,
    eStorageTexelBuffer = VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT,
    eStorageTexelBufferAtomic = VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT,
    eVertexBuffer = VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT,
    eColorAttachment = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT,
    eColorAttachmentBlend = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT,
    eDepthStencilAttachment = VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT,
    eBlitSrc = VK_FORMAT_FEATURE_BLIT_SRC_BIT,
    eBlitDst = VK_FORMAT_FEATURE_BLIT_DST_BIT,
    eSampledImageFilterLinear = VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT,
    eTransferSrc = VK_FORMAT_FEATURE_TRANSFER_SRC_BIT,
    eTransferDst = VK_FORMAT_FEATURE_TRANSFER_DST_BIT,
    eMidpointChromaSamples = VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT,
    eSampledImageYcbcrConversionLinearFilter = VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT,
    eSampledImageYcbcrConversionSeparateReconstructionFilter = VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT,
    eSampledImageYcbcrConversionChromaReconstructionExplicit = VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT,
    eSampledImageYcbcrConversionChromaReconstructionExplicitForceable = VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT,
    eDisjoint = VK_FORMAT_FEATURE_DISJOINT_BIT,
    eCositedChromaSamples = VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT,
    eSampledImageFilterMinmax = VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT,
    eSampledImageFilterCubicIMG = VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG,
    eAccelerationStructureVertexBufferKHR = VK_FORMAT_FEATURE_ACCELERATION_STRUCTURE_VERTEX_BUFFER_BIT_K


stderr, "rl   = %lx\n", rl);
		  dump ("r   ", r);
		  dump ("rref", rr);
		  dump ("q   ", q);
		  dump ("qref", rq);
		  abort ();
		}

	      mpz_set_si (q, 3);
	      rl = div_q_ui[j] (q, a, mpz_get_ui (b));
	      if (rl != mpz_get_ui (rr) || mpz_cmp (q, rq))
		{
		  fprintf (stderr, "mpz_%cdiv_q_ui failed:\n", name[j]);
		  dump ("a", a);
		  dump ("b", b);
		  fprintf(stderr, "rl   = %lx\n", rl);
		  dump ("rref", rr);
		  dump ("q   ", q);
		  dump ("qref", rq);
		  abort ();
		}

	      mpz_set_ui (r, 7);
	      rl = div_r_ui[j] (r, a, mpz_get_ui (b));
	      if (rl != mpz_get_ui (rr) || mpz_cmp (r, rr))
		{
		  fprintf (stderr, "mpz_%cdiv_r_ui failed:\n", name[j]);
		  dump ("a", a);
		  dump ("b", b);
		  fprintf(stderr, "rl   = %lx\n", rl);
		  dump ("r   ", r);
		  dump ("rref", rr);
		  abort ();
		}

	      rl = div_ui[j] (a, mpz_get_ui (b));
	      if (rl != mpz_get_ui (rr))
		{
		  fprintf (stderr, "mpz_%cdiv_ui failed:\n", name[j]);
		  dump ("a", a);
		  dump ("b", b);
		  fprintf(stderr, "rl   = %lx\n", rl);
		  dump ("rref", rr);
		  abort ();
		}

	      if (j == 0)	/* do this once, not for all roundings */
		{
		  div_p = mpz_divisible_ui_p (a, mpz_get_ui (b));
		  if ((mpz_sgn (r) == 0) ^ (div_p != 0))
		    {
		      fprintf (stderr, "mpz_divisible_ui_p failed:\n");
		      dump ("a", a);
		      dump ("b", b);
		      dump ("r   ", r);
		      abort ();
		    }
		}

	      if (j == 1)	/* floor */
		{
		  mpz_set_si (r, -2);
		  mpz_mod_ui (r, a, mpz_get_ui (b));
		  if (mpz_cmp (r, rr))
		    {
		      fprintf (stderr, "mpz_mod failed:\n");
		      dump ("a", a);
		      dump ("b", b);
		      dump ("r   ", r);
		      dump ("rref", rr);
		      abort ();
		    }
		}
	    }
	}
    }
  mpz_clear (a);
  mpz_clear (b);
  mpz_clear (r);
  mpz_clear (q);
  mpz_clear (rr);
  mpz_clear (rq);
}


-us)>q{quotes:"\201c""\201d""\2018""\2019";}
:lang(en-gb)>q{quotes:"\2018""\2019""\201c""\201d";}
a.one,a.two,a.three,a.four,a.five,a.six,a.seven,a.eight,a.nine,a.ten{max-width:12px;}
a.longclassname.one,a.longclassname.two,a.longclassname.three,a.longclassname.four,a.longclassname.five,a.longclassname.six,a.longclassname.seven,a.longclassname.eight,a.longclassname.nine,a.longclassname.ten{max-height:12px;}
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{padding:0;}
article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{padding:0;}
#f7{color:#fff777;}
.asterisk_last *{padding:0;}
.class_no_3{padding:-3px;}
.label-important,.badge-important{background-color:#ff0000;}
.label-important[href],.badge-important[href]{background-color:#cc0000;}
.div {
	color: blue;
}
.div .nest {
	color: red;
}
.div .nest.deep {
	color: yellow;
}
.div .nest.deep .deeper {
	color: angry;
}
.div .nest.deep .deeper .deepest {
	color: purple;
}
h1 a:hover,
h2 a:hover,
h3 a:hover,
h1 p:hover,
h2 p:hover,
h3 p:hover {
	color: red;
}
a.btn-small span {
	font-size: 10px;
}
a {
	color: red;
}
a:hover {
	color: blue;
}
div a {
	color: green;
}
p a span {
	color: yellow;
}
.foo .bar .qux,
.foo .baz .qux {
	display: block;
}
.qux .foo .bar,
.qux .foo .baz {
	display: inline;
}
.qux .foo .bar .biz,
.qux .foo .baz .biz {
	display: none;
}
#first > .one {
	font-size: 2em;
}
#first > .one > #second .two > #deux {
	width: 50%;
}
#first > .one > #second .two > #deux #third {
	height: 100%;
}
#first > .one > #second .two > #deux #third:focus {
	color: black;
}
#first > .one > #second .two > #deux #third:focus #fifth > #sixth .seventh #eighth {
	color: purple;
}
#first > .one > #second .two > #deux #third:focus #fifth > #sixth .seventh #eighth + .sibling_selector {
	color: angry;
}
#first > .one > #second .two > #deux #third ~ p.general_sibling_selector {
	color: unused;
}


r = false,
}

local user_config = type(vim.g.compile_mode) == "function" and vim.g.compile_mode() or vim.g.compile_mode

local health_info = {
	health_info = {
		unrecognized_keys = check.unrecognized_keys(user_config or {}, default_config),
		no_user_config = user_config == nil,
	},
}

local config = vim.tbl_extend("force", health_info, default_config, user_config or {})
config.error_regexp_table =
	vim.tbl_extend("force", require("compile-mode.errors").error_regexp_table, config.error_regexp_table)
config.error_ignore_file_list = vim.list_extend({ "/bin/[a-z]*sh$" }, config.error_ignore_file_list)
config.hidden_output = type(config.hidden_output) == "string" and { config.hidden_output } or config.hidden_output

local ok, err = check.validate(config)
if not ok then
	log.error(err)
end

if #config.health_info.unrecognized_keys > 0 then
	log.fmt_warn("found unrecognized options: %s", config.health_info.unrecognized_keys)
end

if config.health_info.no_user_config then
	log.warn("no configuration found; did you forget to set the `vim.g.compile_mode` table?")
end

---@cast config CompileModeConfig

--- Modify the log level based off the parsed config
log.new({ level = config.debug and "debug" or "info" }, true)

return config


75488281,44.69025421142578,2005-01-01T00:00:00Z,chilipepper\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,cowcod\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,darkblotched rockfish\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,Dover sole\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,English sole\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,longspine thornyhead\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,Pacific ocean perch\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,petrale sole\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,sablefish\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,shortspine thornyhead\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,widow rockfish\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,yelloweye rockfish\n"
            + "-124.34809875488281,44.69025421142578,2005-01-01T00:00:00Z,yellowtail rockfish\n";
    Test.ensureEqual(results, expected, "results=\n" + results);
  }

  /** NOT FINISHED. This tests nosCoopsRWL. */
  @org.junit.jupiter.api.Test
  @TagMissingDataset // source 404
  void testNosCoopsRWL() throws Throwable {
    // String2.log("\n*** EDDTableFromDapSequence.testNosCoopsRWL\n");
    // testVerboseOn();
    int language = 0;
    String results, query, tName, expected;
    String today = Calendar2.epochSecondsToIsoStringTZ(Calendar2.backNDays(1, Double.NaN));
    String yesterday = Calendar2.epochSecondsToIsoStringTZ(Calendar2.backNDays(2, Double.NaN));

    EDDTable edd = (EDDTable) EDDTestDataset.getnosCoopsRWL();

    // *** test a TableWriter that doesn't convert time to iso format
    query = "&station=\"1612340\"&datum=\"MLLW\"&beginTime=" + yesterday + "&endTime=" + today;
    // https://opendap.co-ops.nos.noaa.gov/dods/IOOS/SixMin_Verified_Water_Level.ascii?
    // &WATERLEVEL_6MIN_VFD_PX._STATION_ID="1612340"&WATERLEVEL_6MIN_VFD_PX._DATUM="MLLW"
    // &WATERLEVEL_6MIN_VFD_PX._BEGIN_DATE="20100825"&WATERLEVEL_6MIN_VFD_PX._END_DATE="20100826"
    tName =
        edd.makeNewFileForDapQuery(
            language,
            null,
            null,
            query,
            EDStatic.config.fullTestCacheDirectory,
            edd.className() + "_RWL",
            ".csv");
    results = File2.directReadFrom88591File(EDStatic.config.fullTestCacheDirectory + tName);
    // trouble: java.time (was Joda) doesn't like space-padded hour values

    expected = "zztop\n";
    Test.ensureEqual(results, expected, "results=\n" + results);
  }

  /** Test reading .das */
  @org.junit.jupit


// @copyright 2017-2018 zzu_softboy <zzu_softboy@163.com>
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Created by softboy on 2017/08/08.

#ifndef ZAPI_DS_CALLABLE_VARIANT_H
#define ZAPI_DS_CALLABLE_VARIANT_H

#include "zapi/ds/Variant.h"
#include "zapi/stdext/TypeTraits.h"
#include "zapi/vm/Closure.h"

namespace zapi
{
namespace lang
{

class Parameters;

} // lang
} // zapi

namespace zapi
{
namespace ds
{

using zapi::vm::Closure;
using zapi::lang::Parameters;

class ZAPI_DECL_EXPORT CallableVariant final : public Variant
{
public:
   using HaveArgCallable = Variant(Parameters &);
   using NoArgCallable = Variant();
   CallableVariant(HaveArgCallable callable);
   CallableVariant(NoArgCallable callable);

   CallableVariant(const Variant &other);
   CallableVariant(const CallableVariant &other);
   CallableVariant(Variant &&other);
   CallableVariant(CallableVariant &&other) ZAPI_DECL_NOEXCEPT;
   CallableVariant(zval &other);
   CallableVariant(zval &&other);
   CallableVariant(zval *other);

   CallableVariant &operator =(const CallableVariant &other);
   CallableVariant &operator =(const Variant &other);
   CallableVariant &operator =(CallableVariant &&other) ZAPI_DECL_NOEXCEPT;
   CallableVariant &operator =(Variant &&other);

   Variant operator ()() const;
   template <typename ...Args>
   Variant operator ()(Args&&... args);
   virtual ~CallableVariant();
protected:
   Variant exec(int argc, Variant *argv) const;
};

template <typename ...Args>
Variant CallableVariant::operator ()(Args&&... args)
{
   Variant vargs[] = { static_cast<Variant>(args)... };
   return exec(sizeof...(Args), vargs);
}

} // ds
} // zapi

#endif // ZAPI_DS_CALLABLE_VARIANT_H


: 0;
  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}
.bootstrap .form-check-input:checked {
  background-color: #0d6efd;
  border-color: #0d6efd;
}
.bootstrap .form-check-input:checked[type=checkbox] {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3e%3cpath fill='none' stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='M6 10l3 3l6-6'/%3e%3c/svg%3e");
}
.bootstrap .form-check-input:checked[type=radio] {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='2' fill='%23fff'/%3e%3c/svg%3e");
}
.bootstrap .form-check-input[type=checkbox]:indeterminate {
  background-color: #0d6efd;
  border-color: #0d6efd;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3e%3cpath fill='none' stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='M6 10h8'/%3e%3c/svg%3e");
}
.bootstrap .form-check-input:disabled {
  pointer-events: none;
  filter: none;
  opacity: 0.5;
}
.bootstrap .form-check-input[disabled] ~ .form-check-label,
.bootstrap .form-check-input:disabled ~ .form-check-label {
  opacity: 0.5;
}
.bootstrap .form-switch {
  padding-left: 2.5em;
}
.bootstrap .form-switch .form-check-input {
  width: 2em;
  margin-left: -2.5em;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%280, 0, 0, 0.25%29'/%3e%3c/svg%3e");
  background-position: left center;
  border-radius: 2em;
  transition: background-position 0.15s ease-in-out;
}
@media (prefers-reduced-motion: reduce) {
  .bootstrap .form-switch .form-check-input {
    transition: none;
  }
}
.bootstrap .form-switch .form-check-input:focus {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%2386b7fe'/%3e%3c/svg%3e");
}
.bootstrap .form-switch .form-check-input:checked {
  background-position: right center;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e");
}
.bootstrap .form-check-inline {
  display: inline-block;
  margin-right: 1rem;
}
.bootstrap .btn-check {
  position: absolute;
  clip: rect(0, 0, 0, 0);
  pointer-events: none;
}
.bootstrap .btn-check[disabled] + .btn,
.bootstrap .btn-check:disabled + .btn {
  pointer-events: none;
  filter: n


VATION at the given index
	///</summary>
	public void RemoveORDER_RELATED_OBSERVATIONAt(int index)
	{
		this.RemoveRepetition("ORDER_RELATED_OBSERVATION", index);
	}

}
}


rentVideoQuality.height;

      // 保持宽高比
      final ratio = image.width / image.height;
      if (ratio > 1) {
        targetHeight = (targetWidth / ratio).round();
      } else {
        targetWidth = (targetHeight * ratio).round();
      }

      // 压缩图片
      final compressed = img.copyResize(image, width: targetWidth, height: targetHeight);
      final compressedBytes = img.encodeJpg(compressed, quality: quality ?? 85);

      // 保存压缩后的图片
      final compressedFile = File('${_tempDir!.path}/compressed_${DateTime.now().millisecondsSinceEpoch}.jpg');
      await compressedFile.writeAsBytes(compressedBytes);

      return compressedFile;

    } catch (e) {
      print('图片压缩失败: $e');
      return imageFile; // 返回原文件
    }
  }

  /// 压缩视频
  Future<File?> compressVideo(File videoFile) async {
    try {
      final result = await VideoCompress.compressVideo(
        videoFile.path,
        quality: _getVideoCompressionQuality(),
        deleteOrigin: false,
        includeAudio: true,
      );

      if (result?.file != null) {
        return result!.file;
      }

      return null;
    } catch (e) {
      print('视频压缩失败: $e');
      return null;
    }
  }

  /// 获取视频压缩质量
  VideoQuality _getVideoCompressionQuality() {
    switch (_currentVideoQuality) {
      case VideoQuality.high:
        return VideoQuality.medium; // 压缩时降级
      case VideoQuality.medium:
        return VideoQuality.low;
      case VideoQuality.low:
        return VideoQuality.low;
    }
  }

  /// 缓存管理
  Future<void> cacheData(String key, dynamic data, {int? size}) async {
    try {
      final dataSize = size ?? _estimateDataSize(data);

      // 检查内存使用量
      if (_currentMemoryUsage + dataSize > _maxMemoryCacheSize * 1024 * 1024) {
        await _cleanupMemoryCache();
      }

      _memoryCache[key] = {
        'data': data,
        'size': dataSize,
        'timestamp': DateTime.now().millisecondsSinceEpoch,
      };

      _currentMemoryUsage += dataSize;

    } catch (e) {
      print('缓存数据失败: $e');
    }
  }

  /// 获取缓存数据
  dynamic getCachedData(String key) {
    final cached = _memoryCache[key];
    if (cached != null) {
      // 更新访问时间
      cached['timestamp'] = DateTime.now().millisecondsSinceEpoch;
      return cached['data'];
    }
    return null;
  }

  /// 清理内存缓存
  Future<void> _cleanupMemoryCache() async {
    if (_memoryCache.isEmpty) return;

    // 按访问时间排序
    final sortedKeys = _memoryCache.keys.toList()
      ..sort((a, b) => _memoryCache[b]!['timestamp'] - _memoryCache[a]!['timestamp']);

    // 删除最旧的缓存
    while (_currentMemoryUsage > _maxMemoryCacheSize * 1024 * 1024 * 0.8 && sortedKeys.isNotEmpty) {
      final key = sortedKeys.removeLast();
      final cached = _memoryCache.remove(key);
      if (cached != null) {
        _currentMemoryUsage -= cached['size'];
      }
    }
  }

  /// 清理文件缓存
  Future<void> _cleanupCache() async {
    try {
      if (_cacheDir != null) {
        final files = _cacheDir!.listSync();
        final now =


using AssetsTools.NET.Extra;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using System;
using System.Collections.Generic;
using UABEAvalonia.Plugins;

namespace UABEAvalonia
{
    public partial class PluginWindow : Window
    {
        private Window win;
        private AssetWorkspace workspace;
        private List<AssetContainer> selection;

        List<UABEAPluginMenuInfo> plugInfs;

        public PluginWindow()
        {
            InitializeComponent();
#if DEBUG
            this.AttachDevTools();
#endif
            //generated events
            btnOk.Click += BtnOk_Click;
            btnCancel.Click += BtnCancel_Click;
        }

        public PluginWindow(Window win, AssetWorkspace workspace, List<AssetContainer> selection, PluginManager plugLoader) : this()
        {
            this.win = win;
            this.workspace = workspace;
            this.selection = selection;

            plugInfs = plugLoader.GetPluginsTh


/*	see copyright notice in squirrel.h */
#ifndef _SQOBJECT_H_
#define _SQOBJECT_H_

#include "squtils.h"

#ifdef _SQ64
#define UINT_MINUS_ONE (0xFFFFFFFFFFFFFFFF)
#else
#define UINT_MINUS_ONE (0xFFFFFFFF)
#endif

#define SQ_CLOSURESTREAM_HEAD (('S'<<24)|('Q'<<16)|('I'<<8)|('R'))
#define SQ_CLOSURESTREAM_PART (('P'<<24)|('A'<<16)|('R'<<8)|('T'))
#define SQ_CLOSURESTREAM_TAIL (('T'<<24)|('A'<<16)|('I'<<8)|('L'))

struct SQSharedState;

enum SQMetaMethod{
	MT_ADD=0,
	MT_SUB=1,
	MT_MUL=2,
	MT_DIV=3,
	MT_UNM=4,
	MT_MODULO=5,
	MT_SET=6,
	MT_GET=7,
	MT_TYPEOF=8,
	MT_NEXTI=9,
	MT_CMP=10,
	MT_CALL=11,
	MT_CLONED=12,
	MT_NEWSLOT=13,
	MT_DELSLOT=14,
	MT_TOSTRING=15,
	MT_NEWMEMBER=16,
	MT_INHERITED=17,
	MT_LAST = 18
};

#define MM_ADD		_SC("_add")
#define MM_SUB		_SC("_sub")
#define MM_MUL		_SC("_mul")
#define MM_DIV		_SC("_div")
#define MM_UNM		_SC("_unm")
#define MM_MODULO	_SC("_modulo")
#define MM_SET		_SC("_set")
#define MM_GET		_SC("_get")
#define MM_TYPEOF	_SC("_typeof")
#define MM_NEXTI	_SC("_nexti")
#define MM_CMP		_SC("_cmp")
#define MM_CALL		_SC("_call")
#define MM_CLONED	_SC("_cloned")
#define MM_NEWSLOT	_SC("_newslot")
#define MM_DELSLOT	_SC("_delslot")
#define MM_TOSTRING	_SC("_tostring")
#define MM_NEWMEMBER _SC("_newmember")
#define MM_INHERITED _SC("_inherited")

#define _CONSTRUCT_VECTOR(type,size,ptr) { \
	for(SQInteger n = 0; n < ((SQInteger)size); n++) { \
			new (&ptr[n]) type(); \
		} \
}

#define _DESTRUCT_VECTOR(type,size,ptr) { \
	for(SQInteger nl = 0; nl < ((SQInteger)size); nl++) { \
			ptr[nl].~type(); \
	} \
}

#define _COPY_VECTOR(dest,src,size) { \
	for(SQInteger _n_ = 0; _n_ < ((SQInteger)size); _n_++) { \
		dest[_n_] = src[_n_]; \
	} \
}

#define _NULL_SQOBJECT_VECTOR(vec,size) { \
	for(SQInteger _n_ = 0; _n_ < ((SQInteger)size); _n_++) { \
		vec[_n_].Null(); \
	} \
}

#define MINPOWER2 4

struct SQRefCounted
{
	SQUnsignedInteger _uiRef;
	struct SQWeakRef *_weakref;
	SQRefCounted(): _uiRef(0), _weakref(NULL) {}
	virtual ~SQRefCounted();
	SQWeakRef *GetWeakRef(SQObjectType type);
	ABSTRACT_METHOD(virtual void Release(), {})

};

struct SQWeakRef : SQRefCounted
{
	void Release();
	SQObject _obj;
};

#define _realval(o) (sq_type((o)) != OT_WEAKREF?(SQObject)o:_weakref(o)->_obj)

struct SQObjectPtr;

#define __IsLastRefCount(type,unval) (ISREFCOUNTED(type) && (unval.pRefCounted->_uiRef == 1))

#define __AddRefRefCounted(unval) { unval.pRefCounted->_uiRef++; }

#define __AddRef(type,unval) if(ISREFCOUNTED(type))	__AddRefRefCounted(unval)

#define __ReleaseRefCounted(unval) if((--unval.pRefCounted->_uiRef)==0)	\
		{	\
			unval.pRefCounted->Release();	\
		}

#define __Release(type,unval) if(ISREFCOUNTED(type)) __ReleaseRefCounted(unval)

#define __ObjRelease(obj) { \
	if((obj)) {	\
		(obj)->_uiRef--; \
		if((obj)->_uiRef == 0) \
			(obj)->Release(); \
		(obj) = NULL;	\
	} \
}

#define __ObjAddRef(obj) { \
	(obj)->_uiRef++; \
}

#define is_delegable(t) (sq_type(t)&SQOBJECT_DELEGABLE)
#define raw_type(obj) _RAW_TYPE((obj)._type)

#define _integer(obj) ((obj)._unVal.nInteger)
#define _float(obj) ((obj)._unVal.fFloat)
#define _string(obj) ((obj)._unVal.pString)
#define _stringutf8(obj) ((obj)._unVal.pStrUtf8)
#define _table(obj) ((obj)._unVal.pTable)
#define _array(obj) ((obj)._unVal.pArrayBase)
#define _closure(obj) ((obj)._unVal.pClosure)
#define _generator(obj) ((obj)._unVal.pGenerator)
#define _nativeclosure(obj) ((obj)._unVal.pNativeClosure)
#define _userdata(obj) ((obj)._unVal.pUserData)
#define _userpointer(obj) ((obj)._unVal.pUserPointer)
#define _thread(obj) ((obj)._unVal.pThread)
#define _funcproto(obj) ((obj)._unVal.pFunctionProto)
#define _class(obj) ((obj)._unVal.pClass)
#define _instance(obj) ((obj)._unVal.pInstance)
#define _delegable(obj) ((SQDelegable *)(obj)._unVal.pDelegable)
#define _weakref(obj) ((obj)._unVal.pWeakRef)
#define _outer(obj) ((obj)._unVal.pOuter)
#define _refcounted(obj) ((obj)._unVal.pRefCounted)
#define _rawval(obj) ((obj)._unVal.raw)

#define _stringval(obj) (obj)._unVal.pString->_val
#define _userdataval(obj) ((SQUserPointer)sq_aligning((obj)._unVal.pUserData + 1))

#define tofloat(num) ((sq_type(num)==OT_INTEGER)?(SQFloat)_integer(num):_float(num))
#define tointeger(num) ((sq_type(num)==OT_FLOAT)?(SQInteger)_float(num):_integer(num))
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
#if defined(SQUSEDOUBLE) && !defined(_SQ64) || !defined(SQUSEDOUB


(private val busyIndicator: (Boolean) -> Unit,
                  private val projectRefid: String) : Task<ObservableList<VersionJsonAsFolderItem>>() {
  override fun call(): ObservableList<VersionJsonAsFolderItem> {
    this.busyIndicator(true)
    val log = GPLogger.getLogger("GPCloud")
    val http = HttpClientBuilder.buildHttpClient()

    val jsonBody = let {
      val resp = http.sendGet("/p/versions", mapOf("projectRefid" to projectRefid))
      if (resp.code == 200) {
        resp.rawBody.toString(Charsets.UTF_8)
      } else {
        with(log) {
          warning(
              "Failed to get project history. Response code=${resp.code} reason=${resp.reason}")
        }
        if (resp.code == 401 || resp.code == 403) {
          throw ForbiddenException()
        }
        throw IOException("Server responded with HTTP ${resp.code}")
      }
    }

    val objectMapper = ObjectMapper()
    val jsonNode = objectMapper.readTree(jsonBody)
    return if (jsonNode is ArrayNode) {
      FXCollections.observableArrayList(jsonNode.map(::VersionJsonAsFolderItem))
    } else {
      FXCollections.observableArrayList()
    }
  }
}

internal enum class CloseReason {
  UNKNOWN, INVALID_UID, UNKNOWN_HEARTBEAT, NETWORK_FAILURE
}

private class WebSocketListenerImpl(
    private val token: String,
    private val onAuthCompleted: () -> Unit,
    private val onPayload: (ObjectNode) -> Unit,
    private val onClose: (CloseReason) -> Unit,
    private val onBaseTxnReceived: (String) -> Unit
) : WebSocketListener() {
  private lateinit var webSocket: WebSocket

  override fun onOpen(webSocket: WebSocket, response: Response) {
    LOG.debug("WebSocket opened")
    this.webSocket = webSocket
    if (isColloboqueLocalTest()) {
      // No authentication for Colloboque testing.
      response.header("baseTxnId")?.also(onBaseTxnReceived)
    } else {
      LOG.debug("Trying sending token {}", this.token)
      this.webSocket.send("Basic ${this.token}")
      onAuthCompleted()
    }
  }

  override fun onMessage(webSocket: WebSocket, text: String?) {
    val payload = OBJECT_MAPPER.readTree(text)
    if (payload is ObjectNode) {
      LOG.debug("WebSocket message:\n{}", payload)
      onPayload(payload)
    }
  }

  override fun onClosed(webSocket: WebSocket?, code: Int, reason: String?) {
    LOG.error("WebSocket closed. Code={}, reason={}", code, reason ?: "")
    val reasonEnum = if (code == 1003) {
      when (reason) {
        "UNKNOWN_HEARTBEAT" -> CloseReason.UNKNOWN_HEARTBEAT
        "INVALID_UID" -> CloseReason.INVALID_UID
        else -> CloseReason.UNKNOWN
      }
    } else {
      CloseReason.UNKNOWN
    }
    onClose(reasonEnum)
  }

  override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
    LOG.error("WebSocket network failure: {}", response ?: "", exception = t)
    onClose(CloseReason.NETWORK_FAILURE)
  }
}

class WebSocketClient {
  private var heartbeatFuture: ScheduledFuture<*>? = null
  private var wsListener: WebSocketListenerImpl? = null
  private val heartbeatExecutor = Executors.newSingleThreadScheduledExecutor()
  private var websocket: WebSocket? = null
  private val structureChangeListeners = mutableListOf<(Any) -> Unit>()
  private val lockStatusChangeListeners = mutableListOf<(ObjectNode) -> Unit>()
  private val contentChangeListeners = mutableListOf<(ObjectNode) -> Unit>()
  private val xlogCommit


izing: border-box;
  /* 1 */
  padding: 0;
  /* 2 */
}
/**
 * Fix the cursor style for Chrome's increment/decrement buttons. For certain
 * `font-size` values of the `input`, it causes the cursor style of the
 * decrement button to change from `default` to `text`.
 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  height: auto;
}
/**
 * 1. Address `appearance` set to `searchfield` in Safari and Chrome.
 * 2. Address `box-sizing` set to `border-box` in Safari and Chrome.
 */
input[type="search"] {
  -webkit-appearance: textfield;
  /* 1 */
  box-sizing: content-box;
  /* 2 */
}
/**
 * Remove inner padding and search cancel button in Safari and Chrome on OS X.
 * Safari (but not Chrome) clips the cancel button when the search input has
 * padding (and `textfield` appearance).
 */
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none;
}
/**
 * Define consistent border, margin, and padding.
 */
fieldset {
  border: 1px solid #c0c0c0;
  margin: 0 2px;
  padding: 0.35em 0.625em 0.75em;
}
/**
 * 1. Correct `color` not being inherited in IE 8/9/10/11.
 * 2. Remove padding so people aren't caught out if they zero out fieldsets.
 */
legend {
  border: 0;
  /* 1 */
  padding: 0;
  /* 2 */
}
/**
 * Remove default vertical scrollbar in IE 8/9/10/11.
 */
textarea {
  overflow: auto;
}
/**
 * Don't inherit the `font-weight` (applied by a rule above).
 * NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
 */
optgroup {
  font-weight: bold;
}
/* Tables
   ========================================================================== */
/**
 * Remove most spacing between table cells.
 */
table {
  border-collapse: collapse;
  border-spacing: 0;
}
td,
th {
  padding: 0;
}
/*!
 *  Font Awesome 4.0.3 by @davegandy - http://fontawesome.io - @fontawesome
 *  License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
 */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.0.3');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.0.3') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff?v=4.0.3') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.0.3') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font-family:FontAwesome;font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.3333333333333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.2857142857142858em;text-align:cen


(9)
  void clearPlaceholder() => $_clearField(9);

  /// "func" represents a function. func.name is a function's name or
  /// a primitive op's name. func.attr.first is the name of an attr
  /// defined for that function. func.attr.second is the value for
  /// that attr in the instantiation.
  @$pb.TagNumber(10)
  NameAttrList get func => $_getN(9);
  @$pb.TagNumber(10)
  set func(NameAttrList v) {
    $_setField(10, v);
  }

  @$pb.TagNumber(10)
  $core.bool hasFunc() => $_has(9);
  @$pb.TagNumber(10)
  void clearFunc() => $_clearField(10);
  @$pb.TagNumber(10)
  NameAttrList ensureFunc() => $_ensure(9);
}

/// A list of attr names and their values. The whole list is attached
/// with a string name.  E.g., MatMul[T=float].
class NameAttrList extends $pb.GeneratedMessage {
  factory NameAttrList({
    $core.String? name,
    $pb.PbMap<$core.String, AttrValue>? attr,
  }) {
    final $result = create();
    if (name != null) {
      $result.name = name;
    }
    if (attr != null) {
      $result.attr.addAll(attr);
    }
    return $result;
  }
  NameAttrList._() : super();
  factory NameAttrList.fromBuffer($core.List<$core.int> i,
          [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
      create()..mergeFromBuffer(i, r);
  factory NameAttrList.fromJson($core.String i,
          [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
      create()..mergeFromJson(i, r);

  static final $pb.BuilderInfo _i = $pb.BuilderInfo(
      _omitMessageNames ? '' : 'NameAttrList',
      package: const $pb.PackageName(_omitMessageNames ? '' : 'tensorflow'),
      createEmptyInstance: create)
    ..aOS(1, _omitFieldNames ? '' : 'name')
    ..m<$core.String, AttrValue>(2, _omitFieldNames ? '' : 'attr',
        entryClassName: 'NameAttrList.AttrEntry',
        keyFieldType: $pb.PbFieldType.OS,
        valueFieldType: $pb.PbFieldType.OM,
        valueCreator: AttrValue.create,
        valueDefaultOrMaker: AttrValue.getDefault,
        packageName: const $pb.PackageName('tensorflow'))
    ..hasRequiredFields = false;

  @$core.Deprecated('Using this can add significant overhead to your binary. '
      'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
      'Will be removed in next major version')
  NameAttrList clone() => NameAttrList()..mergeFromMessage(this);
  @$core.Deprecated('Using this can add significant overhead to your binary. '
      'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
      'Will be removed in next major version')
  NameAttrList copyWith(void Function(NameAttrList) updates) =>
      super.copyWith((message) => updates(message as NameAttrList))
          as NameAttrList;

  $pb.BuilderInfo get info_ => _i;

  @$core.pragma('dart2js:noInline')
  static NameAttrList create() => NameAttrList._();
  NameAttrList createEmptyInstance() => create();
  static $pb.PbList<NameAttrList> createRepeated() =>
      $pb.PbList<NameAttrList>();
  @$core.pragma('dart2js:noInline')
  static NameAttrList getDefault() => _defaultInstance ??=
      $pb.GeneratedMessage.$_defaultFor<NameAttrList>(create);
  static NameAttrList? _defaultInstance;

  @$pb.TagNumber(1)
  $core.String get name => $_getSZ(0);
  @$pb.TagNumber(1)
  set name($core.String v) {
    $_setString(0, v);
  }

  @$pb.TagNumber(1)
  $core.bool hasName() => $_has(0);
  @$pb.TagNumber(1)
  void clearName() => $_clearField(1);

  @$pb.TagNumber(2)
  $pb.PbMap<$core.String, AttrValue> get attr => $_getMap(1);
}

const _omitFiel


eFormatStyle ),
#endif
#if UCONFIG_ENABLE_PLUGINS
    FIELD_NAME_STR( LEN_UDBG, UDBG_UPlugReason ),
    FIELD_NAME_STR( LEN_UDBG, UDBG_UPlugLevel ),
#endif
    FIELD_NAME_STR( LEN_UDBG, UDBG_UAcceptResult ),
#if !UCONFIG_NO_COLLATION
    FIELD_NAME_STR( LEN_UDBG, UDBG_UColAttributeValue ),
#endif
};

// --- Add new enum types above this line ---

#define COUNT_CASE(x)  case UDBG_##x: return (actual?count_##x:UPRV_LENGTHOF(names_##x));
#define COUNT_FAIL_CASE(x) case UDBG_##x: return -1;

#define FIELD_CASE(x)  case UDBG_##x: return names_##x;
#define FIELD_FAIL_CASE(x) case UDBG_##x: return NULL;

// low level

/**
 * @param type type of item
 * @param actual true: for the actual enum's type (UCAL_FIELD_COUNT, etc), or false for the string count
 */
static int32_t _udbg_enumCount(UDebugEnumType type, UBool actual) {
	switch(type) {
		COUNT_CASE(UDebugEnumType)
#if !UCONFIG_NO_FORMATTING
		COUNT_CASE(UCalendarDateFields)
		COUNT_CASE(UCalendarMonths)
		COUNT_CASE(UDateFormatStyle)
#endif
#if UCONFIG_ENABLE_PLUGINS
        COUNT_CASE(UPlugReason)
        COUNT_CASE(UPlugLevel)
#endif
        COUNT_CASE(UAcceptResult)
#if !UCONFIG_NO_COLLATION
        COUNT_CASE(UColAttributeValue)
#endif
		// COUNT_FAIL_CASE(UNonExistentEnum)
	default:
		return -1;
	}
}

static const Field* _udbg_enumFields(UDebugEnumType type) {
	switch(type) {
		FIELD_CASE(UDebugEnumType)
#if !UCONFIG_NO_FORMATTING
		FIELD_CASE(UCalendarDateFields)
		FIELD_CASE(UCalendarMonths)
		FIELD_CASE(UDateFormatStyle)
#endif
#if UCONFIG_ENABLE_PLUGINS
        FIELD_CASE(UPlugReason)
        FIELD_CASE(UPlugLevel)
#endif
        FIELD_CASE(UAcceptResult)
       // FIELD_FAIL_CASE(UNonExistentEnum)
#if !UCONFIG_NO_COLLATION
        FIELD_CASE(UColAttributeValue)
#endif
	default:
		return NULL;
	}
}

// implementation

int32_t  udbg_enumCount(UDebugEnumType type) {
	return _udbg_enumCount(type, false);
}

int32_t  udbg_enumExpectedCount(UDebugEnumType type) {
	return _udbg_enumCount(type, true);
}

const char *  udbg_enumName(UDebugEnumType type, int32_t field) {
	if(field<0 ||
				field>=_udbg_enumCount(type,false)) { // also will catch unsupported items
		return NULL;
	} else {
		const Field *fields = _udbg_enumFields(type);
		if(fields == NULL) {
			return NULL;
		} else {
			return fields[field].str + fields[field].prefix;
		}
	}
}

int32_t  udbg_enumArrayValue(UDebugEnumType type, int32_t field) {
	if(field<0 ||
				field>=_udbg_enumCount(type,false)) { // also will catch unsupported items
		return -1;
	} else {


i = channel.receive();
  }
  watch.stop();
  printTiming("Interprocess latency per message", watch);
}

// -----------------------------------------------------------

void channelResponder(Channel output) {
  Channel input = new Channel();
  output.send(input);
  int message;
  do {
    message = input.receive();
    output.send(message - 1);
  } while (message > 0);
}

void portResponder(Port output) {
  Channel input = new Channel();
  output.send(new Port(input));
  int message;
  do {
    message = input.receive();
    output.send(message - 1);
  } while (message > 0);
}

// -----------------------------------------------------------

void printTiming(String banner, Stopwatch watch) {
  int tus = (watch.elapsedMicroseconds * 10) ~/ (2 * MESSAGES);
  int us = tus ~/ 10;
  int fraction = tus % 10;
  print('$banner: $us.$fraction us.');
}
// Copyright (c) 2014, the Dartino project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE.md file.
//
// DartinoOptions=-Xgc-on-delete

import 'dart:async';
import 'dart:dartino';

import 'package:expect/expect.dart';

List constList = const [1, 2, 3];

noop() { }

main() {
  var input = new Channel();
  var port = new Port(input);
  Process.spawnDetached(() => subProcess(port));
  // Wait while messages are enqueued and a program GC is forced with
  // messages in the queue.
  new Timer(const Duration(milliseconds: 100), () {
    var replyPort = input.receive();
    Expect.equals(input.receive(), constList);
    replyPort.send(constList);
    for (int i = 0; i < 10; i++) {
      Expect.equals(i, input.receive());
    }
  });
}

subProcess(Port replyPort) {
  var input = new Channel();
  var port = new Port(input);
  Process.spawnDetached(noop);
  // Put two messages in the queue.
  replyPort.send(port);
  replyPort.send(constList);
  // Spin up a process that will die immediately to force a program GC.
  Process.spawnDetached(noop);
  Expect.equals(input.receive(), constList);
  for (int i = 0; i < 10; i++) {
    Process.spawnDetached(noop);
    replyPort.send(i);
  }
}
// Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE.md file.

import 'dart:dartino';

import 'package:expect/expect.dart';
import 'package:immutable/immutable.dart';

const int INSERTS_PER_PROCESS = 1000;
const int NUM_PROCESSES = 500;

// This function:
//   * inserts [INSERTS_PER_PROCESS/2] numbers into a tree
//     * sends the tree to a child process
//     * waits for the modified tree of the child process
//


IGludGVyYWN0aW9u 10375
IGp1cmlzZA== 10376
IHNwZWxscw== 10377
ZGVw 10378
Zmls 10379
IGNpdmlsaWFucw== 10380
dXR0ZXI= 10381
IENvb3Blcg== 10382
IEJlbG93 10383
IGVudHJhbmNl 10384
IGNvbnZlcnQ= 10385
IGNvbnRyb3ZlcnN5 10386
b3dlcmVk 10387
IGNvbnRyYXJ5 10388
IGFyYw== 10389
IEV4ZWN1dGl2ZQ== 10390
IE9mZmljZXI= 10391
IHBhY2thZ2Vz 10392
IHByb2dyZXNzaXZl 10393
d2lkdGg= 10394
IHJlc2VydmVk 10395
dm9s 10396
IFNhbXN1bmc= 10397
IHByaW50ZWQ= 10398
IGNlbnRlcnM= 10399
IGludHJvZHVjZQ== 10400
IEtlbm5lZHk= 10401
IG9kZHM= 10402
IHN1cmVseQ== 10403
IGluZGVwZW5kZW5jZQ== 10404
IHBhc3NlbmdlcnM= 10405
cmVwcmVuZQ== 10406
IEJlaA== 10407
IGxvdmVz 10408
IEVTUE4= 10409
IGZhY2lsaXQ= 10410
IGlkZW50aWNhbA== 10411
IGRvY3Q= 10412
IHBhcnRuZXJzaGlw 10413
Y29uZg== 10414
IEhpZGU= 10415
IGNvbmZ1c2Vk 10416
IENvdw== 10417
TWVu 10418
IHdyZXN0 10419
IElyYXFp 10420
IGhvbGVz 10421
IFN0dWRpZXM= 10422
IHByZWduYW50 10423
aGFyZA== 10424
IHNpZ25hbHM= 10425
SVg= 10426
IHB1bGxpbmc= 10427
IGdyYWR1YXRl 10428
IG5vbWluZWU= 10429
RGF0ZQ== 10430
IHBlcm1pdHRlZA== 10431
IOKCrA== 10432
IE9rbGFob21h 10433
U3RhcnQ= 10434
IGF1dGhvcml6ZWQ= 10435
IGFsYXJt 10436
IENvcw== 10437
dmFu 10438
IGdlbmVyYXRpb25z 10439
Y3VsYXI= 10440
IGRyYWdvbg== 10441
IFNvZnR3YXJl 10442
IEVkd2FyZA== 10443
IGNvbnRyb2xsZXI= 10444
U2Vu 10445
Z2VyZWQ= 10446
IFZpaw== 10447
IGFwcHJvYWNoZWQ= 10448
VGhhbms= 10449
IGNhbmNl 10450
IGZvcm11bGE= 10451
IFNtYWxs 10452
IHdlYWtuZXNz 10453
IHJhbXA= 10454
aXR1ZGVz 10455
anVk 10456
IGJyaWxsaWFudA== 10457
IGFjY3Vz 10458
c291cmNl 10459
IDgwMA== 10460
IEV2aWw= 10461
U3c= 10462
IGhvbWVsZXNz 10463
d2Vlaw== 10464
aWVucw== 10465
cmljcw== 10466
IFRoaXJk 10467
VE8= 10468
IG9yZ2FuaWM= 10469
IHByZXNlbnRhdGlvbg== 10470
YWdo 10471
IERvd25sb2Fk 10472
dmF


Blks[0].Block.Address, param1.Beneficial)
	}
	if retConBlks[0].Amount.Compare(types.NewBalanceFromBigInt(param1.RewardAmount)) != types.BalanceCompEqual {
		t.Fatal("recvBlk amount not equal", retConBlks[0].Amount, param1.RewardAmount)
	}
}

func mockPKDRewardAddPovBlock(t *testing.T, l ledger.Store, povHeight uint64, txBlock *types.StateBlock, rwdCnt uint) {
	// blk1
	povBlk1, povTd := mock.GeneratePovBlockByFakePow(nil, 0)
	povBlk1.Header.BasHdr.Height = povHeight

	gsdb := statedb.NewPovGlobalStateDB(l.DBStore(), types.ZeroHash)
	csdb, err := gsdb.LookupContractStateDB(contractaddress.PubKeyDistributionAddress)
	if err != nil {
		t.Fatal(err)
	}

	ps := types.NewPovVerifierState()
	ps.TotalVerify = uint64(rwdCnt)
	ps.TotalReward = types.NewBigNumFromInt(int64(rwdCnt * 100000000))
	if povHeight > 240 {
		ps.ActiveHeight["email"] = povHeight - 240
	}
	err = dpki.PovSetVerifierState(csdb, txBlock.Address.Bytes(), ps)
	if err != nil {
		t.Fatal(err)
	}

	err = gsdb.CommitToTrie()
	if err != nil {
		t.Fatal(err)
	}
	txn := l.DBStore().Batch(true)
	err = gsdb.CommitToDB(txn)
	if err != nil {
		t.Fatal(err)
	}
	err = l.DBStore().PutBatch(txn)
	if err != nil {
		t.Fatal(err)
	}

	povBlk1.Header.CbTx.StateHash = gsdb.GetCurHash()

	mock.UpdatePovHash(povBlk1)

	t.Log("add pov block", povBlk1)

	err = l.AddPovBlock(povBlk1, povTd)
	if err != nil {
		t.Fatal(err)
	}

	err = l.AddPovBestHash(povBlk1.GetHeight(), povBlk1.GetHash())
	if err != nil {
		t.Fatal(err)
	}

	err = l.SetPovLatestHeight(povBlk1.GetHeight())
	if err != nil {
		t.Fatal(err)
	}

	/*
		{
			gsdb2 := statedb.NewPovGlobalStateDB(l.DBStore(), povBlk1.Header.CbTx.StateHash)
			csdb2, err := gsdb2.LookupContractStateDB(contractaddress.PubKeyDistributionAddress)
			if err != nil {
				t.Fatal(err)
			}

			retPs, err := dpki.PovGetVerifierState(csdb2, txBlock.Address.Bytes())
			if err != nil {
				t.Fatal(err)
			}
			t.Log("PovGetVerifierState", retPs)
		}
	*/
}

func TestPKDReward_GetTargetReceiver(t *testing.T) {
	clear, l := getTestLedger()
	if l == nil {
		t.Fatal()
	}
	defer clear()

	r := new(PKDReward)
	ctx := vmstore.NewVMContext(l, &contractaddress.PubKeyDistributionAddress)

	sendBlk := mock.StateBlockWithoutWork()
	sendBlk.Token = cfg.GasToken()
	param := new(dpki.PKDRewardParam)
	param.Account = sendBlk.Address
	param.Beneficial = mock.Address()
	param.EndHeight = 1439
	param.RewardAmount = big.NewInt(100 * 100000000)

	sendBlk.Data, _ = abi.PublicKeyDistributionABI.Pa