rk_queue, 1, Group_Size * sizeof(float));
        pipe.InitBuffer(max_queue, 1, Group_Size * sizeof(float));
        pipe.InitBuffer(min_queue, 1, Group_Size * sizeof(float));
        pipe.InitBuffer(scale_queue, 1, Group_Size / 2 * sizeof(half));
        pipe.InitBuffer(int8_queue, 1, Group_Size * sizeof(int8_t));
        pipe.InitBuffer(half_queue, 1, Group_Size * sizeof(half));
    }

    __aicore__ inline void copy_in(uint32_t offset) {
        LocalTensor<SRC_T> input_local = input_queue.AllocTensor<SRC_T>();
        DataCopy(input_local, input_gm[offset], Group_Size);
        input_queue.EnQue(input_local);
    }

    __aicore__ inline void copy_out(uint32_t offset) {
        // reinterpretcast Group_Size(32) * int4b_t to Group_Size / 2 * int8_t,
        // and using DataCopyPad to avoid 32 bits align.
        LocalTensor<int4b_t> output_local = output_queue.DeQue<int4b_t>();
        LocalTensor<int8_t> output_int8_local =
            output_local.ReinterpretCast<int8_t>();

        DataCopyExtParams dataCopyParams;
        dataCopyParams.blockCount = 1;
        dataCopyParams.blockLen = Group_Size / 2 * sizeof(int8_t);
        DataCopyPad(output_gm[offset], output_int8_local, dataCopyParams);

        output_queue.FreeTensor(output_local);
    }

    __aicore__ inline void input_to_cast(LocalTensor<float> cast_local,
                                         LocalTensor<float> input_local) {
        DataCopy(cast_local, input_local, Group_Size);
    }

    __aicore__ inline void input_to_cast(LocalTensor<float> cast_local,
                                         LocalTensor<half> input_local) {
        Cast(cast_local, input_local, RoundMode::CAST_NONE, Group_Size);
    }

    __aicore__ inline half calculate_group(int64_t row, int64_t group) {
        const int64_t i3 = row / (input_ne[1] * input_ne[2]);
        const int64_t i2 = (row - i3 * input_ne[1] * input_ne[2]) / input_ne[1];
        const int64_t i1 =
            row - i3 * input_ne[1] * input_ne[2] - i2 * input_ne[1];

        const int64_t input_offset = i1 * input_stride[1] +
                                     i2 * input_stride[2] +
                                     i3 * input_stride[3] + Group_Size * group;

        // output_offset is stride for output_gm which datatype is int8_t and
        // divided by 2 is needed for int4b_t.
        const int64_t output_offset =
            (i1 * output_stride[1] + i2 * output_stride[2] +
             i3 * output_stride[3] + Group_Size * group) /
            2;
        copy_in(input_offset);

        LocalTensor<SRC_T> input_local = input_queue.DeQue<SRC_T>();
        LocalTensor<int4b_t> output_local = output_queue.AllocTensor<int4b_t>();
        LocalTensor<float> cast_local = cast_queue.AllocTensor<float>();
        LocalTensor<float> work_local = work_queue.AllocTensor<float>();
        LocalTensor<float> max_local = max_queue.AllocTensor<float>();
        LocalTensor<float> min_local = min_queue.AllocTensor<float>();
        LocalTensor<int8_t> int8_local = int8_queue.AllocTensor<int8_t>();


','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59','60','61','62','63','64','65','66','67','68','69','70','71','72','73','74','75','76','77','78','79','80','81','82','83','84','85','86','87','88','89','90','91','92','93','94','95','96','97','98','99','100']
					var mengheikan = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59','60','61','62','63','64','65','66','67','68','69','70','71','72','73','74','75','76','77','78','79','80','81','82','83','84','85','86','87','88','89','90','91','92','93','94','95','96','97','98','99','100']
					var sipat = sifat[Math.floor(Math.random() * sifat.length)]
					var biho = hoby[Math.floor(Math.random() * hoby.length)]
					var bhucin = bukcin[Math.floor(Math.random() * bukcin.length)]
					var senga = arp[Math.floor(Math.random() * arp.length)]
					var chakep = cakep[Math.floor(Math.random() * cakep.length)]
					var watak = wetak[Math.floor(Math.random() * wetak.length)]
					var baik = baikk[Math.floor(Math.random() * baikk.length)]
					var burug = bhuruk[Math.floor(Math.random() * bhuruk.length)]
					var cerdas = cerdhas[Math.floor(Math.random() * cerdhas.length)]
					var berani = berhani[Math.floor(Math.random() * berhani.length)]
					var takut = mengheikan[Math.floor(Math.random() * mengheikan.length)]
					 profile = `*≡══《 Check @${bet.split('@')[0]} 》══≡*

*Name :* ${m.pushName}
*Characteristic :* ${sipat}
*Hobby :* ${biho}
*Simp :* ${bhucin}%
*Great :* ${senga}%
*Handsome :* ${chakep}
*Character :* ${watak}
*Good Morals :* ${baik}%
*Bad Morals :* ${burug}%
*Intelligence :* ${cerdas}%
*Courage :* ${berani}%
*Afraid :* ${takut}%

*≡═══《 CHECK PROPERTIES 》═══≡*`
					try {
ppuser = await XeonBotInc.profilePictureUrl(m.sender, 'image')
} catch (err) {
ppuser = 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png?q=60'
}
ppxeon = await getBuffer(ppuser)
let msgs = generateWAMessageFromContent(m.chat, {
  viewOnceMessage: {
    message: {
        "messageContextInfo": {
          "deviceListMetadata": {},
          "deviceListMetadataVersion": 2
        },


able::empty);
    observable.clone().into_shared().subscribe(|_: i32| {});
    observable.into_shared().subscribe(|_| {});

    let observable = observable::defer(observable::empty).into_shared();
    observable.clone().subscribe(|_: i32| {});
    observable.subscribe(|_| {});
  }

  #[test]
  fn bench() { do_bench(); }

  benchmark_group!(do_bench, bench_deref);

  fn bench_deref(b: &mut Bencher) {
    b.iter(no_results_before_deferred_subscribe);
  }
}
<reponame>yodalee/rrxv6<filename>src/uart.rs
use volatile_register::RW;
use crate::memorylayout;
use bitflags::bitflags;
use lazy_static::lazy_static;
use spin::Mutex;

lazy_static! {
    pub static ref UART: Mutex<Uart> = Mutex::new(Uart::new());
}

bitflags! {
    struct IerFlag: u8 {
        const DISABLE = 0;
        const RX_ENABLE = 1 << 0;
        const TX_ENABLE = 1 << 1;
    }

    struct LcrFlag: u8 {
        const LENGTH_5 = 0;
        const LENGTH_6 = 1;
        const LENGTH_7 = 2;
        const LENGTH_8 = 3;
        const DLAB = 1 << 7;
    }

    struct FcrFlag: u8 {
        const FIFO_ENABLE = 1 << 0;
        const FIFO_CLEAR_RX = 1 << 1;
        const FIFO_CLEAR_TX = 1 << 2;
    }
}

pub struct Uart {
    p: &'static mut UartRegister
}

#[repr(C)]
struct UartRegister {
    thr: RW<u8>,
    ier: RW<u8>,
    isr: RW<u8>,
    lcr: RW<u8>,
    mcr: RW<u8>,
    lsr: RW<u8>,
    msr: RW<u8>,
    spr: RW<u8>,
}

impl Uart {
    fn new() -> Self {
        let mut uart = Uart {
            p: unsafe { &mut *(memorylayout::UART0 as *mut UartRegister) },
        };
        uart.init();
        uart
    }

    /// Do uart initialization
    fn init(&mut self) {
        // disable interrupt
        self.set_interrupt(IerFlag::DISABLE);

        unsafe {
            // special mode to set baud rate
            self.p.lcr.write(LcrFlag::DLAB.bits());

            // set baud rate of 38.4K
            self.p.thr.write(0x03);
            self.p.ier.write(0x0);

            // set word length to 8 bits, no parity
            self.p.lcr.write(LcrFlag::LENGTH_8.bits());

            // reset and enable FIFOs
            self.p.isr.write((FcrFlag::FIFO_ENABLE | FcrFlag::FIFO_CLEAR_RX | FcrFlag::FIFO_CLEAR_TX).bits());
        }

        // enable transmit and receive interruit
        self.set_interrupt(IerFlag::RX_ENABLE | IerFlag::TX_ENABLE);
    }

    pub fn putc(&mut self, c: char) {
        while (self.p.lsr.read() & 0x40) == 0 {}
        unsafe {
            self.p.thr.write(c as u8);
        }
    }

    pub fn puts(&mut self, s: &str) {
        for c in s.chars() {
            self.putc(c);
        }
    }

    fn readc(&mut self) -> Option<u8> {
        if (self.p.lsr.read() &


span
                              >
                              马斯喀特（阿曼） ·
                              多哈（卡塔尔） ·
                              利雅德（沙特阿拉伯） ·
                              大马士革（叙利亚） ·
                              安卡拉（土耳其）8 ·
                              阿布扎比（<a
                                href="/wiki/%E9%98%BF%E6%8B%89%E


rule',
        elements: [
            {
                what: 'element',
                elementType: 'end',
                text: null,
                errors: []
            },
            {
                what: 'element',
                elementType: 'end',
                text: null,
                errors: []
            }
        ]
    };
    const serializedCondition: IExpression = {
        what: 'expression',
        root: {
            name: 'root',
            type: { name: 'boolean' },
            value: {
                what: 'variableAccess',
                id: 12,
                access: 'Item.isOk',
                type: { name: 'boolean' },
            } as IVariableAccess,
        }
    };
    const serialization: IIf = {
        text: "If",
        condition: serializedCondition,
        branchTrue: serializedSubRule,
        branchFalse: serializedSubRule
    };

    let ifElement: If;
    beforeEach(() => {
        ifElement = new If(null, serialization);
    });

    it('constructors', () => {
        ifElement = new If(null);
        expect(ifElement.getBranchFalse().isEmpty()).toBeTruthy();
        expect(ifElement.getBranchTrue().isEmpty()).toBeTruthy();
        expect(ifElement.getCondition().isEmpty()).toBeTruthy();
        const typeIsBoolean = Types.areEqual(ifElement.getCondition().getType(), { name: 'boolean' });
        expect(typeIsBoolean).toBeTruthy();
    });

    it('deserializes', () => {
        expect(ifElement.getBranchTrue()).toBeTruthy();
        expect(ifElement.getBranchFalse()).toBeTruthy();
        expect(ifElement.getCondition().isComplete()).toBeTruthy();
    });

    it('has element type "if"', () => {
        expect(ifElement.getType()).toBe("if");
    });

    it('has na enhancer', () => {
        expect(ifElement.enhance()).not.toBeNull();
    });

    it('retruns array of subrules', () => {
        const rules = ifElement.getSubRules();
        expect(rules.length).toBe(2);
    });

    xit('clones', () => {
    });

    xit('get ids of variable on the left', () => {
    });

    xit('merges', () => {});

    it('get ids of variable on the right', () => {
        expect(ifElement.getIdsOfVariablesOnTheRight()).toEqual([ 12 ]);
    });

    it('serializes', () => {
        const result = ifElement.serialize();
        expect(result.what).toBe('element');
        expect(result.elementType).toBe('if');
        expect(result.text).toBe('If');
        const typesEqual = Types.areEqual(result.condition.root.type, { name: 'boolean', isMultiValued: false});
        expect(typesEqual).toBeTruthy();
        expect(result.branchTrue).toEqual(serializedSubRule);
        expect(result.branchFalse).toEqual(serializedSubRule);
    });
});export interface SkyTimepickerTimeOutput {
  /**
   * The hour.
   */
  hour: number;

  /**
   * The minute.
   */
  minute: number;

  /**
   * The meridian (`AM` or `PM`).
   */
  meridie: string;

  /**
   * The time zone.
   */
  timezone: number;

  /**
   * The date in [iso8601 format](https://www.iso.org/iso-8601-date-and-time-format.html).
   */
  iso8601: Date;

  /**
   * The date in the current local time format.
   */
  local: string;

  /**
   * The time format string.
   */
  customFormat: string;
}
import {ElementRef} from "@


        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
Person person = new Person("CurvedBowZhang", 100);
person.setName("ZJX");
person.setAge(50);
System.out.println("name: " + person.getName() + ", age: " + person.getAge());
```

> Kotlin 的写法（如果不想暴露成员变量的set方法，可以将 var 改成 val )
```kotlin
class Person {

    var name : String? = null
    get() = field
    set(value) {field = value}

    var age : Int = 0
    get() = field
    set(value) {field = value}
}
// 换种更简洁的写法
class Person(var name : String, var age : Int)
var person = Person("CurvedBowZhang", 100)
person.name = "ZJX"
person.age = 50
println("name: {$person.name}, age: {$person.age}")
```

# 私有化 set 方法
> Java 的写法
```java
public class Person {

    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    private void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    private void setAge(int age) {
        this.age = age;
    }
}
```

> Kotlin 的写法
```kotlin
class Person {

    var name : String? = null
    private set

    var age : Int = 0
    private set
}
```

# 私有化 get 方法
> Java 的写法
```java
public class Person {

    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private String getName() {
        return name;
    }

    private void setName(String name) {
        this.name = name;
    }

    private int getAge() {
        return age;
    }

    private void setAge(int age) {
        this.age = age;
    }
}
```

> Kotlin 的写法
```kotlin
class Person {

    private var name : String? = null

    private var age : Int = 0
}
```

# 枚举
> Java 的写法
```java
enum Sex {

    MAN(true), WOMAN(false);

    Sex(boolean isMan) {}
}
```

> Kotlin 的写法
```kotlin
enum class Sex (var isMan: Boolean) {

    MAN(true), WOMAN(false)
}
```

# 接口
> Java 的写法
```java
public interface Callback {
    void onSuccess();
    void onFail();
}
```

> Kotlin 的写法（Kotlin接口方法里面是可以自己实现，这里就不再演示了）
```kotlin
interface Callback {
    fun onSuccess()
    fun onFail()
}
```

# 匿名内部类
> Java 的写法
```java
new Callback() {

    @Override
    public void onSuccess() {

    }

    @Override
    public void onFail() {


dagger.hilt.components.SingletonComponent

@Module
@InstallIn(SingletonComponent::class)
internal interface DataModule {

  @Binds
  fun bindChannelRepository(
    channelRepositoryImpl: ChannelRepositoryImpl
  ): ChannelRepository

  @Binds
  fun bindChatRepository(
    chatRepositoryImpl: ChatRepositoryImpl
  ): ChatRepository
}
/*
 * Designed and developed by 2024 skydoves (Jaewoong Eum)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.skydoves.gemini.core.data.repository

import com.google.ai.client.generativeai.Chat
import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.Content
import com.google.ai.client.generativeai.type.GenerateContentResponse
import com.skydoves.gemini.core.model.GeminiChannel
import kotlinx.coroutines.flow.Flow

/** The exposed abstraction layer of the [ChatRepositoryImpl]. */
public interface ChatRepository {

  suspend fun summaryContent(
    generativeModel: GenerativeModel,
    prompt: String
  ): GenerateContentResponse

  suspend fun sendMessage(chat: Chat, prompt: String): GenerateContentResponse

  suspend fun photoReasoning(
    generativeModel: GenerativeModel,
    content: Content
  ): GenerateContentResponse

  fun watchIsChannelMessageEmpty(cid: String): Flow<Boolean>

  fun getGeminiChannel(key: String): Flow<GeminiChannel>
}
plugins {
    alias(libs.plugins.androidApplication)
    alias(libs.plugins.kotlinAndroid)
    alias(libs.plugins.compose.compiler)
}

android {
    namespace = "io.getstream.kmp.android"
    compileSdk = 34
    defaultConfig {
        applicationId = "io.getstream.kmp.android"
        minSdk = 24
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"
    }
    buildFeatures {
        compose = true
    }
    packaging {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
    buildTypes {
        getByName("release") {
            isMinifyEnabled = false
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

dependencies {
    implementation(projects.shared)
    implementation(libs.compose.ui)
    implementation(libs.compose.ui.tooling.preview)
    implementation(libs.compose.material3)
    implementation(libs.androidx.activity.compose)
    debugImplementation(libs.compose.ui.tooling)
}/*
 * Copyright 2024 Stream.IO, Inc. All Rights Reserved.
 *
 * Licensed under the Stream License;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.getstream.live.shopping.initializer

import android.content.Context


12: STB_R	stb	%r15, [%r4 + %r5]
	.word 0xf629211c  ! 412: STB_I	stb	%r27, [%r4 + 0x011c]
	.word 0x0a800001  ! 412: BCS	bcs  	<label_0x1>
	.word 0xd6f18ce0  ! 412: STXA_R	stxa	%r11, [%r6 + %r0] 0x67
	.word 0xe6290005  ! 421: STB_R	stb	%r19, [%r4 + %r5]
	.word 0xea312b88  ! 421: STH_I	sth	%r21, [%r4 + 0x0b88]
	.word 0xec210005  ! 421: STW_R	stw	%r22, [%r4 + %r5]
	.word 0xe8310005  ! 421: STH_R	sth	%r20, [%r4 + %r5]
	.word 0xf831268e  ! 421: STH_I	sth	%r28, [%r4 + 0x068e]
	.word 0xd8290005  ! 421: STB_R	stb	%r12, [%r4 + %r5]
	.word 0xec310005  ! 421: STH_R	sth	%r22, [%r4 + %r5]
	.word 0x22c90001  ! 421: BRZ	brz,a,pt	%4,<label_0x90001>
	.word 0xd8f08ce2  ! 421: STXA_R	stxa	%r12, [%r2 + %r2] 0x67
	.word 0xe8290005  ! 430: STB_R	stb	%r20, [%r4 + %r5]
	.word 0xda2925b3  ! 430: STB_I	stb	%r13, [%r4 + 0x05b3]
	.word 0xda712db8  ! 430: STX_I	stx	%r13, [%r4 + 0x0db8]
	.word 0xe8312dbc  ! 430: STH_I	sth	%r20, [%r4 + 0x0dbc]
	.word 0xd6210005  ! 430: STW_R	stw	%r11, [%r4 + %r5]
	.word 0xd6312abe  ! 430: STH_I	sth	%r11, [%r4 + 0x0abe]
	.word 0xe8312b70  ! 430: STH_I	sth	%r20, [%r4 + 0x0b70]
	.word 0x06800001  ! 430: BL	bl  	<label_0x1>
	.word 0xf6792110  ! 430: SWAP_I	swap	%r27, [%r4 + 0x0110]
	.word 0xe0290005  ! 440: STB_R	stb	%r16, [%r4 + %r5]
	.word 0xfc710005  ! 440: STX_R	stx	%r30, [%r4 + %r5]
	.word 0xf8210005  ! 440: STW_R	stw	%r28, [%r4 + %r5]
	.word 0xfe210005  ! 440: STW_R	stw	%r31, [%r4 + %r5]
	.word 0xe2712280  ! 440: STX_I	stx	%r17, [%r4 + 0x0280]
	.word 0xfc710005  ! 440: STX_R	stx	%r30, [%r4 + %r5]
	.word 0xec712058  ! 440: STX_I	stx	%r22, [%r4 + 0x0058]
	.word 0xf67127b


po.enqueued(t)
        }
    }

    fun enqueueTasks(tasks: List<TaskModel>) {
        ensureQueue()
        for (t in tasks) {
            val withId = if (t.taskId.isBlank()) t.copy(taskId = t.entry.classFqn + "#" + t.entry.method + "#" + System.currentTimeMillis()) else t
            backlog.add(withId)
            repo.enqueued(withId)
        }
    }

    fun start() {
        if (!running.compareAndSet(false, true)) return
        // Reset concurrency limiter to current settings on every start
        permits = java.util.concurrent.Semaphore(settings.maxConcurrentRequests, true)
        val rps = settings.requestsPerSecond
        val periodMs = if (rps <= 0.0) 1000L else (1000.0 / rps).toLong().coerceAtLeast(1L)
        scheduler = Executors.newSingleThreadScheduledExecutor()
        scheduler!!.scheduleAtFixedRate({ tick() }, 0, periodMs, TimeUnit.MILLISECONDS)
        log.info("GJavaDoc QueueManager started. RPS=$rps period=${periodMs}ms")
        publishStarted()
        publishHeartbeat()
    }

    fun stop() {
        running.set(false)
        scheduler?.shutdownNow()
        scheduler = null
        log.info("GJavaDoc QueueManager stopped.")
        publishStopped()
    }

    fun clearQueue() {
        val q = ensureQueue()
        q.clear()
        backlog.clear()
        runningCount.set(0)
        log.info("GJavaDoc queue cleared")
    }

    /**
     * 自动恢复未完成的任务：包含 QUEUED / RUNNING(残留) / PARTIAL。
     * 不恢复 SUCCEEDED / CANCELLED / FAILED。
     */
    fun autoResumePending() {
        ensureQueue()
        try {
            val all = repo.all()
            val toResume = all.filter { it.status == TaskStatus.QUEUED || it.status == TaskStatus.RUNNING || it.status == TaskStatus.PARTIAL }
            if (toResume.isEmpty()) return
            for (t in toResume) {
                // 将状态复位为 QUEUED，保留错误信息便于追踪
                t.status = TaskStatus.QUEUED
                t.progress = TaskProgress(0.0, "Auto-resume")
                repo.upsert(t)
            }
            enqueueTasks(toResume)
            if (!running.get()) start() else publishHeartbeat()
            log.info("GJavaDoc auto resumed ${toResume.size} pending tasks")
        } catch (e: Throwable) {
            log.warn("autoResumePending failed", e)
        }
    }

    private fun tick() {
        if (!running.get()) return
        refreshLimiterIfChanged()
        val q = ensureQueue()
        // Fill bounded queue from backlog up to remaining capacity
        var rem = q.remainingCapacity()
        while (rem > 0) {
            val next = backlog.poll() ?: break
            if (q.offer(next)) rem-- else break
        }
        // Derive capacity from actual running indicators to avoid drift across threads
        val capacity = settings.maxConcurrentRequests - indicators.size
        if (capacity <= 0) return
        var dispatched = 0
        while (dispatched < capacity) {
            val task = q.poll() ?: break
            // Double guard: also acquire a permit; if we cannot, push it back and stop dispatching now.
            if (!permits.tryAcquire()) {
                // No permit available — return task to the head (best-effort) and break
                q.offer(task)
                break
            }
            executeTask(task)
            dispatched++
        }
        // Emit a lightweight heartbeat so UI can reflect queue state (throttled)
        publishHeartbeat()
    }

    private fun executeTask(task: TaskModel) {
        val client: LL


ring {
	GinkgoHelper()
	pool := &tfv1.GPUPool{}
	Eventually(func(g Gomega) {
		pool = tfEnv.GetGPUPool(0)
		newHash := utils.GetObjectHash(pool.Spec.ComponentConfig.Client)
		g.Expect(newHash).ShouldNot(Equal(oldHash))
		g.Expect(pool.Status.ComponentStatus.ClientVersion).To(Equal(newHash))
	}).Should(Succeed())

	return pool.Status.ComponentStatus.ClientVersion
}

func verifyGpuPoolHypervisorHash(tfEnv *TensorFusionEnv, oldHash string) string {
	GinkgoHelper()
	pool := &tfv1.GPUPool{}
	Eventually(func(g Gomega) {
		pool = tfEnv.GetGPUPool(0)
		newHash := utils.GetObjectHash(pool.Spec.ComponentConfig.Hypervisor)
		g.Expect(newHash).ShouldNot(Equal(oldHash))
		g.Expect(pool.Status.ComponentStatus.HypervisorVersion).To(Equal(newHash))
	}).Should(Succeed())

	return pool.Status.ComponentStatus.HypervisorVersion
}

func verifyGpuPoolWorkerHash(tfEnv *TensorFusionEnv, oldHash string) string {
	GinkgoHelper()
	pool := &tfv1.GPUPool{}
	Eventually(func(g Gomega) {
		pool = tfEnv.GetGPUPool(0)
		newHash := utils.GetObjectHash(pool.Spec.ComponentConfig.Worker)
		g.Expect(newHash).ShouldNot(Equal(oldHash))
		g.Expect(pool.Status.ComponentStatus.WorkerVersion).To(Equal(newHash))
	}).Should(Succeed())

	return pool.Status.ComponentStatus.WorkerVersion
}

func verifyHypervisorPodHash(gpuNode *tfv1.GPUNode, hash string) {
	GinkgoHelper()
	Eventually(func(g Gomega) {
		pod := &corev1.Pod{}
		g.Expect(k8sClient.Get(ctx, client.ObjectKey{
			Name:      fmt.Sprintf("hypervisor-%s", gpuNode.Name),
			Namespace: utils.CurrentNamespace(),
		}, pod)).Should(Succeed())
		g.Expect(pod.Labels[constants.LabelKeyPodTemplateHash]).Should(Equal(hash))
		updatePodPhaseToRunning(pod, hash)
	}).Should(Succeed())
}

func verifyClientPodHash(index int, hash string) {
	GinkgoHelper()
	Eventually(func(g Gomega) {
		pod := &corev1.Pod{}
		key := client.ObjectKey{Namespace: utils.CurrentNamespace(), Name: getClientPodName(index)}
		g.Expect(k8sClient.Get(ctx, key, pod)).Should(Succeed())
		g.Expect(pod.Labels[constants.LabelKeyPodTemplateHash]).Should(Equal(hash))
	}).Should(Succeed())
}

func verifyClientPodHashConsistently(index int, hash string) {
	GinkgoHelper()
	Consistently(func(g Gomega) {
		pod := &corev1.Pod{}
		key := client.ObjectKey{Namespace: utils.CurrentNamespace(), Name: getClientPodName(index)}
		err := k8sClient.Get(ctx, key, pod)
		g.Expect(err).Should(Succeed())
		g.Expect(pod.Labels[constants.LabelKeyPodTemplateHash]).Should(Equal(hash))
	}).Should(Succeed())
}

func verifyHypervisorPodHashConsistently(gpuNode *tfv1.GPUNode, hash string) {
	GinkgoHelper()
	Consistently(func(g Gomega) {
		pod := &corev1.Pod{}
		g.Expect(k8sClient.Get(ctx, client.ObjectKey{
			Name:      fmt.Sprintf("hypervisor-%s", gpuNode.Name),
			Namespace: utils.CurrentNamespace(),
		}, pod)).Should(Succeed())
		g.Expect(pod.Labels[constants.LabelKeyPodTemplateHash]).Should(Equal(hash))
		updatePodPhaseToRunning(pod, hash)


.newCall(request).execute()
        response.use {
            return it.parseData(EpisodesListDto.serializer())
        }
    }

    private fun apiUrlBuilder(vararg segments: String): HttpUrl.Builder {
        val apiBase = "$baseUrl/$API_PATH".toHttpUrl().newBuilder()
        segments.forEach(apiBase::addPathSegment)
        return apiBase
    }

    private fun <T> Response.parseData(serializer: KSerializer<T>): T {
        val element = parseDataElement()
        return json.decodeFromJsonElement(serializer, element)
    }

    private fun Response.parseDataElement(): JsonElement {
        val root = json.parseToJsonElement(body.string()).jsonObject
        if (root["error"]?.jsonPrimitive?.booleanOrNull == true) {
            val message = root["message"]?.jsonPrimitive?.contentOrNull ?: "Error desconocido"
            throw Exception(message)
        }
        return root["data"] ?: throw Exception("Respuesta vacía de la API")
    }

    private fun PostDto.toSAnime(): SAnime = SAnime.create().apply {
        title = this@toSAnime.title
        thumbnail_url = resolveThumbnailUrl()
        description = overview?.takeIf { it.isNotBlank() }
        author = originalTitle?.takeIf { it.isNotBlank() }
        status = SAnime.UNKNOWN
        setUrlWithoutDomain(buildAnimeUrl(this@toSAnime))
    }

    private fun EpisodeDto.toSEpisode(seriesId: Long, context: AnimeContext): SEpisode {
        val season = (seasonNumber ?: 1).coerceAtLeast(1)
        val number = (episodeNumber ?: 1).coerceAtLeast(1)
        val baseName = sequenceOf(name, title)
            .mapNotNull { it?.takeIf(String::isNotBlank) }
            .firstOrNull()
            ?: "Episodio $number"

        val displayName = "T${season}x$number - $baseName"
        val episodeFloat = "$season.${number.toString().padStart(3, '0')}".toFloatOrNull() ?: number.toFloat()
        val episodeUrl = buildEpisodeUrl(id, seriesId, context, season, number)

        return SEpisode.create().also { episode ->
            episode.name = displayName
            episode.episode_number = episodeFloat
            episode.date_upload = parseDate(date)
            episode.setUrlWithoutDomain(episodeUrl)
        }
    }

    private fun buildEpisodeUrl(episodeId: Long, seriesId: Long, context: AnimeContext, season: Int?, episode: Int?): String {
        val builder = StringBuilder("/player")
        builder.append("?postId=").append(episodeId)
        builder.append("&seriesId=").append(seriesId)
        builder.append("&type=").append(context.type)
        builder.append("&slug=").append(context.slug)
        season?.let { builder.append("&season=").append(it) }
        episode?.let { builder.append("&episode=").append(it) }
        return builder.toString()
    }

    private fun parseDate(value: String?): Long {
        if (value.isNullOrBlank()) return 0L
        return DATE_FORMATS.firstNotNullOfOrNull { format ->
            runCatching { format.parse(value)?.time }.getOrNull()
        } ?: 0L
    }

    private fun PostDto.resolveThumbnailUrl(): String? {
        val lamovieHosts = primaryImageHosts()

        return sequenceOf(
            buildImageUrls(images?.poster, lamovieHosts),
            buildImageUrls(images?.poster, TMDB_POSTER_HOSTS),
            buildImageUrls(gallery, TMDB_GALLERY_HOSTS),
            buildImageUrls(images?.backdrop, lamovieHosts),
            buildImageUrls(images?.backdrop, TMDB_BACKDROP_HOSTS),
        )
            .flatMap(List<String>::asSequence)
            .map


WS_QUANTITY", INT32),
            new Column("WS_WHOLESALE_COST", DECIMAL),
            new Column("WS_LIST_PRICE", DECIMAL),
            new Column("WS_SALES_PRICE", DECIMAL),
            new Column("WS_EXT_DISCOUNT_AMT", DECIMAL),
            new Column("WS_EXT_SALES_PRICE", DECIMAL),
            new Column("WS_EXT_WHOLESALE_COST", DECIMAL),
            new Column("WS_EXT_LIST_PRICE", DECIMAL),
            new Column("WS_EXT_TAX", DECIMAL),
            new Column("WS_COUPON_AMT", DECIMAL),
            new Column("WS_EXT_SHIP_COST", DECIMAL),
            new Column("WS_NET_PAID", DECIMAL),
            new Column("WS_NET_PAID_INC_TAX", DECIMAL),
            new Column("WS_NET_PAID_INC_SHIP", DECIMAL),
            new Column("WS_NET_PAID_INC_SHIP_TAX", DECIMAL),
            new Column("WS_NET_PROFIT", DECIMAL)
    ) {
        @Override
        public String insertPrepareStatement() {
            return "INSERT INTO " + tableName() + " VALUES (?::integer, ?::integer, ?::integer, ?::integer, ?::integer,"
                    + " ?::integer, ?::integer, ?::integer, ?::integer, ?::integer, ?::integer, ?::integer,"
                    + " ?::integer, ?::integer, ?::integer, ?::integer, ?::integer, ?::integer, ?::integer,"
                    + " ?::numeric(7, 2), ?::numeric(7, 2), ?::numeric(7, 2), ?::numeric(7, 2),"
                    + " ?::numeric(7, 2), ?::numeric(7, 2), ?::numeric(7, 2), ?::numeric(7, 2),"
                    + " ?::numeric(7, 2), ?::numeric(7, 2), ?::numeric(7, 2), ?::numeric(7, 2),"
                    + " ?::numeric(7, 2), ?::numeric(7, 2), ?::numeric(7, 2));";
        }
    },

    DATE_DIM(
            new long[] {73_049, 73_049, 73_049, 73_049, 73_049, 73_049},
            new Column("d_date_sk", INT32),
            new Column("d_date_id", STRING),
            new Column("d_date", DATE),
            new Column("d_month_seq", INT32),
            new Column("d_week_seq", INT32),
            new Column("d_quarter_seq", INT32),
            new Column("d_year", INT32),
            new Column("d_dow", INT32),
            new Column("d_moy", INT32),
            new Column("d_dom", INT32),
            new Column("d_qoy", INT32),
            new Column("d_fy_year", INT32),
            new Column("d_fy_quarter_seq", INT32),
            new Column("d_fy_week_seq", INT32),
            new Column("d_day_name", STRING),
            new Column("d_quarter_name", STRING),
            new Column("d_holiday", STRING),
            new Column("d_weekend", STRING),
            new Column("d_following_holiday", STRING),
            new Column("d_first_dom", INT32),
            new Column("d_last_dom", INT32),
            new Column("d_same_day_ly", INT32),
            new Column("d_same_day_lq", INT32),
            new Column("d_current_day", STRING),
            new Column("d_current_week", STRING),
            new Column("d_current_month", STRING),
            new Column("d_current_quarter", STRING),
            new Column("d_current_year", STRING)
    )


oduct,
			Category:  tpRef[i].Category,
		})
	}
	sp, tp := GetQuickCheckPairs(dr)
	if !reflect.DeepEqual(sp, spRef) {
		t.Fatalf("sp expected to be equal to spRef. sp: %v spRef: %v", sp, spRef)
	}
	if !reflect.DeepEqual(tp, tpRef) {
		t.Fatalf("tp expected to be equal to tpRef. tp: %v tpRef: %v", tp, tpRef)
	}
}

func TestQuickCheck(t *testing.T) {
	type tpTest struct {
		pair     []TaxoPair
		evt      event.NormalizedEvent
		expected bool
	}

	var tpTbl = []tpTest{
		{
			[]TaxoPair{{Product: []string{"P1", "P2"}, Category: "C1"}},
			event.NormalizedEvent{Product: "P1", Category: "C1"},
			true,
		},
		{
			[]TaxoPair{{Product: []string{"P1", "P2"}, Category: "C1"}},
			event.NormalizedEvent{Product: "P1", Category: "C2"},
			false,
		},
		{
			[]TaxoPair{{Product: []string{"P1", "P2"}, Category: "C1"}},
			event.NormalizedEvent{Product: "P3", Category: "C1"},
			false,
		},
	}

	for _, tt := range tpTbl {
		actual := QuickCheckTaxoRule(tt.pair, &tt.evt)
		if actual != tt.expected {
			t.Fatalf("QuickCheck taxo actual != expected. TaxoPair: %v, Event: %v",
				tt.pair, tt.evt)
		}
	}

	type spTest struct {
		pair     []SIDPair
		evt      event.NormalizedEvent
		expected bool
	}

	var spTbl = []spTest{
		{
			[]SIDPair{{PluginID: 10, PluginSID: []int{1, 2}}},
			event.NormalizedEvent{PluginID: 10, PluginSID: 1},
			true,
		},
		{
			[]SIDPair{{PluginID: 10, PluginSID: []int{1, 2}}},
			event.NormalizedEvent{PluginID: 10, PluginSID: 3},
			false,
		},
		{
			[]SIDPair{{PluginID: 10, PluginSID: []int{1, 2}}},
			event.NormalizedEvent{PluginID: 9, PluginSID: 1},
			false,
		},
	}

	for _, tt := range spTbl {
		actual := QuickCheckPluginRule(tt.pair, &tt.evt)
		if actual != tt.expected {
			t.Fatalf("QuickCheck SID actual != expected. SIDPair: %v, Event: %v",
				tt.pair, tt.evt)
		}
	}

}

func TestRule(t *testing.T) {

	d, err := test.DirEnv(false)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("Using base dir %s", d)
	err = asset.Init(path.Join(d, "configs"))
	if err != nil {
		t.Fatal(err)
	}

	type ruleTests struct {
		n        int
		e        event.NormalizedEvent
		r        DirectiveRule
		s        *StickyDiffData
		expected bool
	}

	e1 := event.NormalizedEvent{
		PluginID:    1001,
		PluginSID:   50001,
		Product:     "IDS",
		Category:    "Malware",
		SubCategory: "C&C Communication",
		SrcIP:       "192.168.0.1",
		DstIP:       "8.8.8.200",
		SrcPort:     31337,
		DstPort:


        "AttributePOC.PortfolioManager_underControl_AttributePOC.Fund",
        Convert2ScalaUtil.toScalaImmutableSet(Sets.newHashSet("holdRet")));
    Catalog catalog = new PropertyGraphCatalog(Convert2ScalaUtil.toScalaImmutableMap(schema));
    catalog.init();
    task.setCatalog(catalog);

    LocalReasonerRunner runner = new LocalReasonerRunner();
    LocalReasonerResult result = runner.run(task);
    System.out.println(result);
    Assert.assertEquals(result.getRows().size(), 1);
    Assert.assertEquals(result.getRows().get(0)[0], "u1");
    Assert.assertEquals(result.getRows().get(0)[1], "0.02");
    clear();
  }

  @Test
  public void doTestMax() {
    String dsl =
        "Define (s: AttributePOC.User)-[p: holdPMProduct2]->(o: AttributePOC.PortfolioManager) {\n"
            + "    GraphStructure {\n"
            + "\t(s)-[p1:holdProduct]->(u1:AttributePOC.Fund)<-[p2:underControl]-(o)\n"
            + "    }\n"
            + "    Rule {\n"
            + "        avgProfit = group(s,o).max(p1.holdRet)\n"
            + "        p.avgProfit = avgProfit\n"
            + "    }\n"
            + "}";
    dsl +=
        "GraphStructure {\n"
            + "  (s: AttributePOC.User)-[p: holdPMProduct2]->(o: AttributePOC.PortfolioManager)\n"
            + "}\n"
            + "Rule {\n"
            + "}\n"
            + "Action {\n"
            + "  get(s.id,p.avgProfit)\n"
            + "}";

    LocalReasonerTask task = new LocalReasonerTask();
    task.setDsl(dsl);
    task.setGraphLoadClass("com.antgroup.openspg.reasoner.runner.local.loader.TestFundGraphLoader");

    // use test catalog
    /*
    dslParams.put("projId", "363000092");
    Catalog catalog = CatalogFactory.createCatalog(dslParams);
     */

    // add mock catalog
    Map<String, scala.collection.immutable.Set<String>> schema = new HashMap<>();
    schema.put("AttributePOC.User", Convert2ScalaUtil.toScalaImmutableSet(Sets.newHashSet("id")));
    schema.put(
        "AttributePOC.PortfolioManager",
        Convert2ScalaUtil.toScalaImmutableSet(Sets.newHashSet("id")));
    schema.put("AttributePOC.Fund", Convert2ScalaUtil.toScalaImmutableSet(Sets.newHashSet("id")));
    schema.put(
        "AttributePOC.User_holdProduct_AttributePOC.Fund",
        Convert2ScalaUtil.toScalaImmutableSet(Sets.newHashSet("holdRet")));
    schema.put(
        "AttributePOC.PortfolioManager_underControl_AttributePOC.Fund",
        Convert2ScalaUtil.toScalaImmutableSet(Sets.newHashSet("holdRet")));
    Catalog catalog = new PropertyGraphCatalog(Convert2ScalaUtil.toScalaImmutableMap(schema));
    catalog.init();
    task.setCatalog(catalog);

    LocalReasonerRunner runner = new LocalReasonerRunner();
    LocalReasonerResult result = runner.run(task);
    System.out.println(result);
    Assert.assertEquals(result.getRows().size(), 1);
    Assert.assertEquals(result.getRows().get(0)[0], "u1");
    Assert.assertEquals(result.getRows().get(0)[1], "0.02");
    clear();
  }

  @Test
  pu


dataCollector: contDataCollector,
        )
          ..setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
          ..setFieldValue(Field.FIELD_AVG, 90.0)
          ..setFieldValue(Field.FIELD_MAX, 100.0)
          ..setFieldValue(Field.FIELD_MIN, 80.0)
          ..setFieldValue(Field.LAST, 85.0)
      ];

      final HealthRecord healthRecord = HealthRecord(
        startTime: startTime,
        endTime: endTime,
        metadata: 'Data',
        dataCollector: DataCollector(
          dataStreamName: 'such as step count',
          packageName: packageName,
          dataType: HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA,
          dataGenerateType: DataGenerateType.DATA_TYPE_RAW,
        ),
      )
        ..setSubDataSummary(subDataSummary)
        ..setSubDataDetails(subDataDetails)
        ..setFieldValue(HealthFields.FIELD_THRESHOLD, 42.0)
        ..setFieldValue(HealthFields.FIELD_MAX_HEART_RATE, 48.0)
        ..setFieldValue(HealthFields.FIELD_MIN_HEART_RATE, 42.0)
        ..setFieldValue(HealthFields.FIELD_AVG_HEART_RATE, 45.0);

      final String? result = await HealthRecordController.addHealthRecord(
        HealthRecordInsertOptions(
          healthRecord: healthRecord,
        ),
      );
      log(
        'addHealthRecord',
        _healthTextController,
        LogOptions.success,
        result: result.toString(),
      );
    } on PlatformException catch (e) {
      log(
        'addHealthRecord',
        _healthTextController,
        LogOptions.error,
        error: e.message,
      );
    }
  }

  void getHealthRecord() async {
    log(
      'getHealthRecord',
      _healthTextController,
      LogOptions.call,
    );
    try {
      final DateTime startTime = DateTime(2023, 5, 11);
      final DateTime endTime = DateTime(2023, 5, 13);

      HealthRecordReply result = await HealthRecordController.getHealthRecord(
        HealthRecordReadOptions(
          packageName: packageName,
        )
          ..setSubDataTypeList(
            <DataType>[
              DataType.DT_INSTANTANEOUS_HEART_RATE,
            ],
          )
          ..setTimeInterval(
            startTime,
            endTime,
            TimeUnit.MILLISECONDS,
          )
          ..readByDataType(
            HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA,
          )
          ..readHealthRecordsFromAllApps(),
      );
      log(
        'getHealthRecord',
        _healthTextController,
        LogOptions.success,
        result: result.healthRecords[0].toJson(),
      );
    } on PlatformException catch (e) {
      log(
        'getHealthRecord',
        _healthTextController,
        LogOptions.error,
        error: e.message,
      );
    }
  }

  void updateHealthRecord() async {
    log(
      'updateHealthRecord',
      _healthTextController,
      LogOptions.call,
    );
    try {
      final DateTime startTime = DateTime(2022, 10, 11);
      final DateTime endTime = DateTime(2022, 10, 12);
      final HealthRecord healthRecord = HealthRecord(
        startTime: startTime,
        endTime: endTime,
        metadata: 'Data',
        dataCollector: DataCollector(
          dataStreamName: 'such as step count',
          packageName: packageName,
          dataType: HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA,
          dataGenerateType: DataGenerateType.DATA_TYPE_RAW,
        ),
      )
        ..setFieldValue(HealthFields.FIELD_THRESHOLD, 41.9)
        ..setFieldValue(HealthFields.FIELD_MAX_HEART_RATE, 49.1)
        ..setFieldValue(HealthFields.FIELD_MIN_HEART_RATE, 4


     /// Gets or sets the feedback message to display when <see cref="IValidator.IsInvalid"/> is true.
        /// </summary>
        public string FeedbackMessage
        {
            get => this.feedbackMessage.IsNullOrWhiteSpace()
                ? Resources.RequiredValidator_FeedbackMessage
                : this.feedbackMessage;
            set => this.feedbackMessage = value;
        }

        /// <summary>
        /// Executes data validation on the provided <paramref name="value"/>.
        /// </summary>
        /// <param name="value">The value to be validated.</param>
        public void Validate(object value)
        {
            this.IsInvalid = DetermineIsInvalid(value);
            this.IsDirty = true;
        }

        private static bool DetermineIsInvalid(object value)
        {
            return value switch
            {
                null => true,
                ICollection collection => collection.Count <= 0,
                bool isTrue => !isTrue,
                string str => str.IsNullOrWhiteSpace(),
                _ => false
            };
        }
    }
}


0 K1 ["props"]
  GETTABLEKS R2 R3 K2 ["Stylizer"]
  GETTABLEKS R3 R2 K3 ["searchOptions"]
  GETTABLEKS R5 R0 K1 ["props"]
  GETTABLEKS R4 R5 K4 ["LiveSearchData"]
  GETTABLEKS R5 R1 K5 ["minDuration"]
  GETTABLEKS R6 R1 K6 ["maxDuration"]
  GETTABLEKS R8 R0 K1 ["props"]
  GETTABLEKS R7 R8 K7 ["Localization"]
  LOADK R10 K8 ["General"]
  LOADK R11 K9 ["SearchOptionAudioLength"]
  NAMECALL R8 R7 K10 ["getText"]
  CALL R8 3 1
  LOADK R11 K8 ["General"]
  LOADK R12 K11 ["SearchOptionsIncludeUnverifiedDescription"]
  NAMECALL R9 R7 K10 ["getText"]
  CALL R9 3 1
  LOADK R12 K8 ["General"]
  LOADK R13 K12 ["SearchOptionsIncludeUnverifiedHeader"]
  NAMECALL R10 R7 K10 ["getText"]
  CALL R10 3 1
  LOADK R13 K8 ["General"]
  LOADK R14 K13 ["SearchOptionsIncludeUnverifiedTooltip"]
  NAMECALL R11 R7 K10 ["getText"]
  CALL R11 3 1
  GETTABLEKS R13 R0 K1 ["props"]
  GETTABLEKS R12 R13 K14 ["categoryName"]
  GETUPVAL R14 0
  GETTABLEKS R13 R14 K15 ["categoryIsAudio"]
  MOVE R14 R12
  CALL R13 1 1
  LOADB R14 1
  GETUPVAL R15 1
  CALL R15 0 1
  JUMPIFNOT R15 [+1]
  LOADB R14 0
  NEWTABLE R15 0 5
  DUPTABLE R16 K18 [{"Key", "Text"}]
  LOADK R17 K19 ["Relevance"]
  SETTABLEKS R17 R16 K16 ["Key"]
  LOADK R19 K8 ["General"]
  LOADK R20 K20 ["SortByRelevance"]
  NAMECALL R17 R7 K10 ["getText"]
  CALL R17 3 1
  SETTABLEKS R17 R16 K17 ["Text"]
  DUPTABLE R17 K18 [{"Key", "Text"}]
  LOADK R18 K21 ["MostTaken"]
  SETTABLEKS R18 R17 K16 ["Key"]
  LOADK R20 K8 ["General"]
  LOADK R21 K22 ["SortByMostTaken"]
  NAMECALL R18 R7 K10 ["getText"]
  CALL R18 3 1
  SETTABLEKS R18 R17 K17 ["Text"]
  DUPTABLE R18 K18 [{"Key", "Text"}]
  LOADK R19 K23 ["Favorites"]
  SETTABLEKS R19 R18 K16 ["Key"]
  LOADK R21 K8 ["General"]
  LOADK R22 K24 ["SortByFavorites"]
  NAMECALL R19 R7 K10 ["getText"]
  CALL R19 3 1
  SETTABLEKS R19 R18 K17 ["Text"]
  DUPTABLE R19 K18 [{"Key", "Text"}]
  LOADK R20 K25 ["Updated"]
  SETTABLEKS R20 R19 K16 ["Key"]
  LOADK R22 K8 ["General"]
  LOADK R23 K26 ["SortByUpdated"]
  NAMECALL R20 R7 K10 ["getText"]
  CALL R20 3 1
  SETTABLEKS R20 R19 K17 ["Text"]
  DUPTABLE R20 K18 [{"Key", "Text"}]
  LOADK R21 K27 ["Ratings"]
  SETTABLEKS R21 R20 K16 ["Key"]
  LOADK R23 K8 ["General"]
  LOADK R24 K28 ["SortByRatings"]
  NAMECALL R21 R7 K10 ["getText"]
  CALL R21 3 1
  SETTABLEKS R21 R20 K17 ["Text"]


import json

# Import necessary modules from the 'ontoaligner' library
from ontoaligner import ontology, encoder
from ontoaligner.aligner import SimpleFuzzySMLightweight
from ontoaligner.utils import metrics, xmlify

# Create a task object for material information ontology matching using a predefined dataset
task = ontology.MaterialInformationMatOntoOMDataset()

# Print the test task information (for debugging or confirmation purposes)
print("Test Task:", task)

# Collect the dataset for ontology matching, including source, target, and reference matching
# The paths to the source ontology, target ontology, and reference matching files are provided
dataset = task.collect(source_ontology_path="../assets/MI-MatOnto/mi_ontology.xml",
                       target_ontology_path="../assets/MI-MatOnto/matonto_ontology.xml",
                       reference_matching_path="../assets/MI-MatOnto/matchings.xml")

# Initialize the encoder model to map concepts between the source and target ontologies
# 'ConceptParentLightweightEncoder' is used here to generate embeddings for matching
encoder_model = encoder.ConceptParentLightweightEncoder()

# Encode the source and target datasets using the encoder model
# The encoder generates embeddings of the concepts in both the source and target ontologies
encoder_output = encoder_model(source=dataset['source'], target=dataset['target'])

# Initialize the SimpleFuzzySMLightweight ontology matcher
# The matcher uses a fuzzy threshold (0.2) to match concepts between the source and target ontologies
model = SimpleFuzzySMLightweight(fuzzy_sm_threshold=0.2)

# Generate the matching results using the encoded source and target data
# This step applies the fuzzy matching algorithm to align concepts from the source and target ontologies
matchings = model.generate(input_data=encoder_output)

# Evaluate the matching results using an evaluation report
# The 'metrics.evaluation_report' function compares the predicted matchings against the references of source and target ontologies.
evaluation = metrics.evaluation_report(predicts=matchings, references=dataset['reference'])

# Print the evaluation report as a formatted JSON string for easy reading
print("Evaluation Report:", json.dumps(evaluation, indent=4))

# Convert the generated matchings into an XML alignment format using 'xmlify.xml_alignment_generator'
# This will produce an XML string that represents the ontology matchings
xml_str = xmlify.xml_alignment_generator(matchings=matchings)

# Write the XML alignment string to a file
# The file is saved with the name 'matchings.xml' in the current directory
with open("matchings.xml", "w", encoding="utf-8") as xml_file:
    xml_file.write(xml_str)


.0f,
        pathFillType = PathFillType.EvenOdd,
    ) {
        // Subpath 1
        moveTo(13.2986f, 1.31202f)
        curveTo(13.604f, 1.4446f, 13.7855f, 1.76265f, 13.7442f, 2.09302f)
        lineTo(13.1445f, 6.89073f)
        curveTo(13.0931f, 7.30175f, 12.7182f, 7.59329f, 12.3072f, 7.54192f)
        curveTo(11.8962f, 7.49054f, 11.6047f, 7.1157f, 11.656f, 6.70468f)
        lineTo(11.9385f, 4.44534f)
        lineTo(11.1489f, 5.39278f)
        curveTo(10.8837f, 5.71099f, 10.4108f, 5.75398f, 10.0926f, 5.48881f)
        curveTo(9.77441f, 5.22364f, 9.73141f, 4.75072f, 9.99659f, 4.43251f)
        lineTo(12.4238f, 1.51986f)
        curveTo(12.6369f, 1.26408f, 12.9932f, 1.17944f, 13.2986f, 1.31202f)
        close()
        // Subpath 2 (hole)
        moveTo(2.46967f, 2.46967f)
        curveTo(2.76256f, 2.17677f, 3.23744f, 2.17677f, 3.53033f, 2.46967f)
        lineTo(8.52493f, 7.46426f)
        curveTo(8.52899f, 7.46824f, 8.533f, 7.47225f, 8.53696f, 7.47629f)
        lineTo(16.525f, 15.4643f)
        curveTo(16.529f, 15.4683f, 16.533f, 15.4722f, 16.5369f, 15.4763f)
        lineTo(21.5303f, 20.4697f)
        curveTo(21.8232f, 20.7626f, 21.8232f, 21.2374f, 21.5303f, 21.5303f)
        curveTo(21.2374f, 21.8232f, 20.7626f, 21.8232f, 20.4697f, 21.5303f)
        lineTo(16.0504f, 17.1111f)
        lineTo(11.5762f, 22.4801f)
        curveTo(11.363f, 22.7359f, 11.0068f, 22.8205f, 10.7014f, 22.688f)
        curveTo(10.3959f, 22.5554f, 10.2145f, 22.2373f, 10.2558f, 21.907f)
        lineTo(11.1504f, 14.75f)
        lineTo(4.67816f, 14.75f)
        curveTo(4.43165f, 14.75f, 4.19802f, 14.7501f, 4.01026f, 14.7331f)
        curveTo(3.83045f, 14.7168f, 3.53396f, 14.6759f, 3.28186f, 14.4722f)
        curveTo(2.98305f, 14.2308f, 2.81187f, 13.8653f, 2.81766f, 13.4811f)
        curveTo(2.82255f, 13.1571f, 2.981f, 12.9032f, 3.0836f, 12.7546f)
        curveTo(3.19074f, 12.5995f, 3.34032f, 12.42f, 3.49815f, 12.2307f)
        lineTo(6.98536f, 8.04602f)
        lineTo(2.46967f, 3.53033f)
        curveTo(2.17678f, 3.23743f


 sentinel at end
	lastj := n
	for i := n - 1; i >= 0; i-- {
		if L[i] == k && J[i] < lastj {
			seq[k] = pair{xi[i], yi[J[i]]}
			k--
		}
	}
	seq[0] = pair{0, 0} // sentinel at start
	return seq
}
package parse

import (
	"strings"
	"testing"

	"src.elv.sh/pkg/tt"
)

var n = mustParse("ls $x[0]$y[1];echo done >/redir-dest")

var pprintASTTests = []*tt.Case{
	Args(n).Rets(
		`Chunk
  Pipeline/Form
    Compound/Indexing/Primary ExprCtx=CmdExpr Type=Bareword Value="ls"
    Compound ExprCtx=NormalExpr
      Indexing ExprCtx=NormalExpr
        Primary ExprCtx=NormalExpr Type=Variable Value="x"
        Array/Compound/Indexing/Primary ExprCtx=NormalExpr Type=Bareword Value="0"
      Indexing ExprCtx=NormalExpr
        Primary ExprCtx=NormalExpr Type=Variable Value="y"
        Array/Compound/Indexing/Primary ExprCtx=NormalExpr Type=Bareword Value="1"
  Pipeline/Form
    Compound/Indexing/Primary ExprCtx=CmdExpr Type=Bareword Value="echo"
    Compound/Indexing/Primary ExprCtx=NormalExpr Type=Bareword Value="done"
    Redir Mode=Write RightIsFd=false
      Compound/Indexing/Primary ExprCtx=NormalExpr Type=Bareword Value="/redir-dest"
`),
}

func TestPPrintAST(t *testing.T) {
	pprintAST := func(n Node) string {
		var b strings.Builder
		pprintAST(n, &b)
		return b.String()
	}
	tt.Test(t, tt.Fn(pprintAST).Named("pprintAST"), pprintASTTests...)
}

var pprintParseTreeTests = []*tt.Case{
	Args(n).Rets(
		`Chunk "ls $x[0]$y...redir-dest" 0-36
  Pipeline/Form "ls $x[0]$y[1]" 0-13
    Compound/Indexing/Primary "ls" 0-2
    Sep " " 2-3
    Compound "$x[0]$y[1]" 3-13
      Indexing "$x[0]" 3-8
        Primary "$x" 3-5
        Sep "[" 5-6
        Array/Compound/Indexing/Primary "0" 6-7
        Sep "]" 7-8
      Indexing "$y[1]" 8-13
        Primary "$y" 8-10
        Sep "[" 10-11
        Array/Compound/Indexing/Primary "1" 11-12
        Sep "]" 12-13
  Sep ";" 13-14
  Pipeline/Form "echo done >/redir-dest" 14-36
    Compound/Indexing/Primary "echo" 14-18
    Sep " " 18-19
    Compound/Indexing/Primary "done" 19-23
    Sep " " 23-24
    Redir ">/redir-dest" 24-36
      Sep ">" 24-25
      Compound/Indexing/Primary "/redir-dest" 25-36
`),
}

func TestPPrintParseTree(t *testing.T) {
	pprintParseTree := func(n Node) string {
		var b strings.Builder
		pprintParseTree(n, &b)
		return b.String()
	}
	tt.Test(t, tt.Fn(pprintParseTree).Named("pprintParseTree"), pprintParseTreeTests...)
}

func mustParse(src string) Node {
	tree, err := Parse(SourceForTest(src), Config{})
	if err != nil {
		panic(err)
	}
	return tree.Root
}
package testutil

import (


Number duration] )

[method:AnimationAction crossFadeFrom]( [page:AnimationAction fadeOutAction], [page:Number duration], [page:Boolean warp] )

[method:AnimationAction crossFadeTo]( [page:AnimationAction fadeInAction], [page:Number duration], [page:Boolean warp] )

[method:AnimationAction stopFading]()

[method:AnimationAction setEffectiveTimeScale]( [page:Number timeScale] )

[method:Number getEffectiveTimeScale]()

[method:AnimationAction setDuration]( [page:Number duration] )

[method:AnimationAction syncWith]( [page:AnimationAction action] )

[method:AnimationAction halt]( [page:Number duration] )

[method:AnimationAction warp]( [page:Number startTimeScale], [page:Number endTimeScale], [page:Number duration] )

[method:AnimationAction stopWarping]()

[method:AnimationMixer getMixer]()

[method:AnimationClip getClip]()

[method:Object3D getRoot]()

Static Methods

[method:AnimationClip parse]( [page:Object json] )

    json -- JSON object

[method:Object toJSON]( [page:AnimationClip clip] )

    clip -- AnimationClip

[method:AnimationClip CreateFromMorphTargetSequence]( [page:String name], [page:Array morphTargetSequence], [page:Number fps], [page:Boolean noLoop] )

    name -- Name for the new clip

    morphTargetSequence -- Array of morph targets

    fps -- Number of frames per second

    noLoop -- Whether looping occurs automatically.

[method:AnimationClip parseAnimation]( [page:Object animation], [page:Array bones] )

    Parses the animation.hierarchy format and returns an AnimationClip.

Source

    [link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]

<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../" />

		<link type="text/css" rel="stylesheet" href="page.css" />

[name]

		This contains methods for setting up an [link:https://developer.mozilla.org/en-US/docs/Web/API/AudioContext AudioContext].

		Used internally by the [page:AudioListener AudioListener] and [page:AudioLoader AudioLoader] classes.

		This uses the [link:https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API Web Audio API].

Methods

[method:AudioContext getContext]()

		Return the value of the variable *context* in the outer scope, if defined,
		otherwise set it to a new [link:https://developer.mozilla.org/en-US/docs/Web/API/AudioContext AudioContext].


unter4 (Not implemented)
        pub d9: atmega_hal::port::PB5 = pb5,
        /// `D10`
        ///
        /// * **PWM**: [atmega32u4_hal::timer::Timer1Pwm]
        /// * `OC1B`: Output Compare Channel `B` for Timer/Counter1
        /// * `OC4B`: Output Compare Channel `B` for Timer/Counter4 (Not implemented)
        pub d10: atmega_hal::port::PB6 = pb6,
        /// `D11`
        ///
        /// * **PWM**: [atmega32u4_hal::timer::Timer0Pwm]
        /// * `OC0A`: Output Compare Channel `B` for Timer/Counter0
        /// * `OC1C`: Output Compare Channel `C` for Timer/Counter1
        pub d11: atmega_hal::port::PB7 = pb7,
        /// `D12`
        ///
        /// * `#OC4D`: Inverted Output Compare Channel `D` for Timer/Counter4 (Not implemented)
        pub d12: atmega_hal::port::PD6 = pd6,
        /// `D13` / `LED_BUILTIN`
        ///
        /// * Onboard LED
        /// * **PWM**: [atmega32u4_hal::timer::Timer4Pwm]
        /// * `OC4A`: Output Compare Channel `A` for Timer/Counter4
        pub d13: atmega_hal::port::PC7 = pc7,
        /// `RX`
        ///
        /// Led for indicating inbound data.  Also the CS pin.
        pub led_rx: atmega_hal::port::PB0 = pb0,
        /// `TX`
        ///
        /// Led for indicating outbound data
        pub led_tx: atmega_hal::port::PD5 = pd5,
        /// `SCLK`
        ///
        /// ICSP SCLK pin
        pub sck: atmega_hal::port::PB1 = pb1,
        /// `MOSI`
        ///
        /// ICSP MOSI pin
        pub mosi: atmega_hal::port::PB2 = pb2,
        /// `MISO`
        ///
        /// ICSP MISO pin
        pub miso: atmega_hal::port::PB3 = pb3,
        /// `A0`
        ///
        /// * `ADC7` channel
        pub a0: atmega_hal::port::PF7 = pf7,
        /// `A1`
        ///
        /// * `ADC6` channel
        pub a1: atmega_hal::port::PF6 = pf6,
        /// `A2`
        ///
        /// * `ADC5` channel
        pub a2: atmega_hal::port::PF5 = pf5,
        /// `A3`
        ///
        /// * `ADC4` channel
        pub a3: atmega_hal::port::PF4 = pf4,
        /// `A4`
        ///
        /// * `ADC1` channel
        pub a4: atmega_hal::port::PF1 = pf1,
        /// `A5`
        ///
        /// * `ADC0` channel
        pub a5: atmega_hal::port::PF0 = pf0,
    }
}
<filename>src/bin/p27.rs
// Euler discovered the remarkable quadratic formula:

// n^2+n+41
// It turns out that the formula will produce 40 primes for the consecutive integer values
// 0≤n≤39. However, when n=40, 40^2+40+41=40(40+1)+41 is divisible by 41, and certainly when n=41,
// 41^2+41+41 is clearly divisible by 41.

// The incredible formula n^2−79n+1601 was discovered, which produces 80 primes for the consecutive
// values 0≤n≤79. The product of the coefficients, −79 and 1601, is −126479.

// Considering quadratics of the form:

// n^2+an+b, where |a|<1000 and |b|≤1000

// where |n| is the modulus/absolute value of n
//


Enabled:      true,
				AllowOrigins: []string{"  http://localhost:3000  ", "\thttps://example.com\n", " http://test.com "},
			},
		}

		mux := testNewChiMux(t)

		// Should handle whitespace in origins without panicking
		require.NotPanics(t, func() {
			server.applyCORS(mux)
		})
	})
}

func TestAPIServer_CORSIntegration(t *testing.T) {
	t.Parallel()

	t.Run("CORS disabled - applyCORS should not be called", func(t *testing.T) {
		t.Parallel()

		deps, err := NewAPIDependencies(
			hclog.NewNullLogger(),
			NewClientManager(),
			NewHealthTracker([]string{"test-server"}),
			"localhost:8090",
		)
		require.NoError(t, err)

		// Create server with CORS disabled (default)
		server, err := NewAPIServer(deps)
		require.NoError(t, err)
		require.False(t, server.cors.Enabled)

		// This is more of an integration test - in actual usage,
		// applyCORS would only be called when CORS is enabled
	})

	t.Run("CORS enabled with various configurations", func(t *testing.T) {
		t.Parallel()

		deps, err := NewAPIDependencies(
			hclog.NewNullLogger(),
			NewClientManager(),
			NewHealthTracker([]string{"test-server"}),
			"localhost:8090",
		)
		require.NoError(t, err)

		corsConfigs := []struct {
			name    string
			options []APIOption
		}{
			{
				name: "basic CORS with origins",
				options: []APIOption{
					WithCORSEnabled(true),
					WithCORSAllowOrigins([]string{"http://localhost:3000", "https://app.example.com"}),
				},
			},
			{
				name: "CORS with all options",
				options: []APIOption{
					WithCORSEnabled(true),
					WithCORSAllowOrigins([]string{"http://localhost:3000"}),
					WithCORSAllowMethods([]string{"GET", "POST", "PUT", "DELETE"}),
					WithCORSAllowHeaders([]string{"Content-Type", "Authorization", "X-API-Key"}),
					WithCORSExposeHeaders([]string{"X-Total-Count", "X-Page-Count"}),
					WithCORSAllowCredentials(true),
					WithCORSMaxAge(1 * time.Hour),
				},
			},
			{
				name: "CORS with wildcard",
				options: []APIOption{
					WithCORSEnabled(true),
					WithCORSAllowOrigins([]string{"*"}),
					WithCORSAllowCredentials(false), // Required with wildcard
				},
			},
		}

		for _, config := range corsConfigs {
			t.Run(config.name, func(t *testing.T) {
				t.Parallel()

				server, err := NewAPIServer(deps, config.options...)
				require.NoError(t, err)
				require.True(t, server.cors.Enabled)

				// Verify CORS can be applied without panicking
				mux := testNewChiMux(t)
				require.NotPanics(t, func() {
					server.applyCORS(mux)
				})
			})
		}
	})
}

// Test helper to create a chi mux for testing
func testNewChiMux(t *testing.T) *chi.Mux {
	t.Helper()
	return chi.NewMux()
}

func TestMapError(t *testing.T) {
	t.Parallel()

	logger := hclog.NewNullLogger()

	tests := []struct {
		name           string
		err            error
		expectedStatus int
	}{
		{
			name:           "ErrBadRequest maps to 400",
			err:            errors.ErrBadRequest,
			expectedStatus: 400,
		},
		{
			name:           "ErrServerNotFound maps to 404",
			err:            errors.ErrServerNotFound,
			expectedStatus: 404,


ent, final int style) {
		super(parent, style | SWT.DOUBLE_BUFFERED);
		addPaintListener(this);
		addListeners();
	}

	@Override
	public void handleEvent(final Event e) {
		switch (e.type) {
			case SWT.MouseExit:
				doHover(false);
				break;
			case SWT.MouseMove:
				break;
			case SWT.MouseEnter:
			case SWT.MouseHover:
				doHover(true);
				e.doit = true;
				break;
			case SWT.MouseUp:
				if (e.button == 1 && getClientArea().contains(e.x, e.y)) { doButtonUp(); }
				break;
			case SWT.MouseDown:
				if (e.button == 1 && getClientArea().contains(e.x, e.y)) { doButtonDown(); }
				break;
			default:
				;
		}
	}

	/**
	 * SelectionListeners are notified when the button is clicked
	 *
	 * @param listener
	 */
	public void addSelectionListener(final SelectionListener listener) {
		if (listener == null) return;
		addListener(SWT.Selection, new TypedListener(listener));
	}

	/**
	 * Do button down.
	 */
	public void doButtonDown() {
		if (!enabled) return;
		down = true;
		if (!isDisposed()) { redraw(); }
	}

	/**
	 * Do button up.
	 */
	private void doButtonUp() {
		if (!enabled) return;
		final Event e = new Event();
		e.item = this;
		e.widget = this;
		e.type = SWT.Selection;
		notifyListeners(SWT.Selection, e);
		down = false;
		if (!isDisposed()) { redraw(); }
	}

	/**
	 * Do hover.
	 *
	 * @param hover
	 *            the hover
	 */
	private void doHover(final boolean hover) {
		hovered = hover;
		if (!hover) { down = false; }
		if (!isDisposed()) { redraw(); }
	}

	@Override
	public void paintControl(final PaintEvent e) {
		final GC gc = e.gc;
		gc.setAntialias(SWT.ON);
		Font f = getFont();
		gc.setFont(f);
		int v_inset;
		if (preferredHeight < getBounds().height) {
			v_inset = (getBounds().height - preferredHeight) / 2;
		} else {
			v_inset = 0;
		}
		final Rectangle rect = new Rectangle(0, v_inset, preferredWidth - rightPadding, preferredHeight);
		setBackground(getParent().getBackground());
		GamaUIColor color = GamaColors.get(colorCode);
		Color background = color == null ? getParent().getBackground() : hovered ? color.lighter() : color.color();
		final Color foreground = GamaColors.getTextColorForBackground(background).color();
		gc.setForeground(foreground);
		gc.setBackground(background);

		if (down) {
			gc.fillRoundRectangle(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2, 8, 8);
		} else {
			gc.fillRoundRectangle(rect.x, rect.y, rect.width, rect.height, 8, 8);
		}

		int x = FlatButton.innerMarginWidth;
		final Image im = getImage();
		int y_text = 0;
		final String text = newText();
		if (text != null) { y_text += (getBounds().height - gc.textExtent(text).y) / 2; }

		if (imageStyle == IMAGE_RIGHT) {
			gc.drawString(text, x, y_text);
			if (im != null) {
				int y_image = (getBounds().height - im.getBounds().height) / 2;
				x = rect.width - x - im.getBounds().width;
				drawImage(im, gc, x, y_image);
			}
		} else {
			if (im != null) {
				int y_image = (getBounds().height - im.getBounds().height) / 2;
				x = drawImage(im, gc, x, y_image);
			}
			gc.drawString(text, x, y_text);
		}
		if (addMenuSign) {
			int y_image = (getBounds().height - menuImage.


m",
	"item_glimmer_cape",--
	"item_pipe",--
    "item_aghanims_shard",
	"item_assault",--
	"item_heavens_halberd",--
    "item_shivas_guard",--
    "item_refresher",--
    "item_ultimate_scepter_2",
    "item_moon_shard",
}

X['sBuyList'] = sRoleItemsBuyList[sRole]

X['sSellList'] = {
	"item_heavens_halberd",
	"item_quelling_blade",

	"item_assault",
	"item_quelling_blade",

	"item_abyssal_blade",
	"item_magic_wand",

	"item_assault",
	"item_ancient_janggo",
}

if J.Role.IsPvNMode() or J.Role.IsAllShadow() then X['sBuyList'], X['sSellList'] = { 'PvN_antimage' }, {} end

nAbilityBuildList, nTalentBuildList, X['sBuyList'], X['sSellList'] = J.SetUserHeroInit( nAbilityBuildList, nTalentBuildList, X['sBuyList'], X['sSellList'] )

X['sSkillList'] = J.Skill.GetSkillList( sAbilityList, nAbilityBuildList, sTalentList, nTalentBuildList )

X['bDeafaultAbility'] = false
X['bDeafaultItem'] = false

function X.MinionThink(hMinionUnit)
	Minion.MinionThink(hMinionUnit)
end

local ThunderClap       = bot:GetAbilityByName('brewmaster_thunder_clap')
local CinderBrew        = bot:GetAbilityByName('brewmaster_cinder_brew')
local DrunkenBrawler    = bot:GetAbilityByName('brewmaster_drunken_brawler')
local PrimalCompanion   = bot:GetAbilityByName('brewmaster_primal_companion')
local PrimalSplit       = bot:GetAbilityByName('brewmaster_primal_split')

local ThunderClapDesire
local CinderBrewDesire, CinderBrewLocation
local DrunkenBrawlerDesire, ActionType
local PrimalCompanionDesire
local PrimalSplitDesire

local drunkenBrawlerState = 1

function X.SkillsComplement()
	if J.CanNotUseAbility(bot) then return end

    CinderBrewDesire, CinderBrewLocation = X.ConsiderCinderBrew()
    if CinderBrewDesire > 0
    then
        J.SetQueuePtToINT(bot, false)
        bot:ActionQueue_UseAbilityOnLocation(CinderBrew, CinderBrewLocation)
        return
    end

    ThunderClapDesire = X.ConsiderThunderClap()
    if ThunderClapDesire > 0
    then
        J.SetQueuePtToINT(bot, false)
        bot:ActionQueue_UseAbility(ThunderClap)
        return
    end

    PrimalSplitDesire = X.ConsiderPrimalSplit()
    if PrimalSplitDesire > 0
    then
        bot:Action_UseAbility(PrimalSplit)
        return
    end

    DrunkenBrawlerDesire, State = X.ConsiderDrunkenBrawler()
    if DrunkenBrawlerDesire > 0
    then
        if drunkenBrawlerState ~= State then
            bot:Action_UseAbility(DrunkenBrawler)
            drunkenBrawlerState = (drunkenBrawlerState % 4) + 1
        end
    end

    Primal


 else {
			// build packages hierarchy
			List<JPackage> rootPkgs = getHierarchyPackages(wrapper.getPackages());
			for (JPackage jPackage : rootPkgs) {
				jPackage.update();
				add(jPackage);
			}
		}
	}

	/**
	 * Convert packages list to hierarchical packages representation
	 *
	 * @param packages input packages list
	 * @return root packages
	 */
	List<JPackage> getHierarchyPackages(List<JavaPackage> packages) {
		Map<String, JPackage> pkgMap = new HashMap<String, JPackage>();
		for (JavaPackage pkg : packages) {
			addPackage(pkgMap, new JPackage(pkg));
		}
		// merge packages without classes
		boolean repeat;
		do {
			repeat = false;
			for (JPackage pkg : pkgMap.values()) {
				if (pkg.getInnerPackages().size() == 1 && pkg.getClasses().isEmpty()) {
					JPackage innerPkg = pkg.getInnerPackages().get(0);
					pkg.getInnerPackages().clear();
					pkg.getInnerPackages().addAll(innerPkg.getInnerPackages());
					pkg.getClasses().addAll(innerPkg.getClasses());
					pkg.setName(pkg.getName() + "." + innerPkg.getName());

					innerPkg.getInnerPackages().clear();
					innerPkg.getClasses().clear();

					repeat = true;
					break;
				}
			}
		} while (repeat);

		// remove empty packages
		for (Iterator<Map.Entry<String, JPackage>> it = pkgMap.entrySet().iterator(); it.hasNext(); ) {
			JPackage pkg = it.next().getValue();
			if (pkg.getInnerPackages().isEmpty() && pkg.getClasses().isEmpty()) {
				it.remove();
			}
		}
		// use identity set for collect inner packages
		Set<JPackage> innerPackages = Collections.newSetFromMap(new IdentityHashMap<JPackage, Boolean>());
		for (JPackage pkg : pkgMap.values()) {
			innerPackages.addAll(pkg.getInnerPackages());
		}
		// find root packages
		List<JPackage> rootPkgs = new ArrayList<JPackage>();
		for (JPackage pkg : pkgMap.values()) {
			if (!innerPackages.contains(pkg)) {
				rootPkgs.add(pkg);
			}
		}
		Collections.sort(rootPkgs);
		return rootPkgs;
	}

	private void addPackage(Map<String, JPackage> pkgs, JPackage pkg) {
		String pkgName = pkg.getName();
		JPackage replaced = pkgs.put(pkgName, pkg);
		if (replaced != null) {
			pkg.getInnerPackages().addAll(replaced.getInnerPackages());
			pkg.getClasses().addAll(replaced.getClasses());
		}
		int dot = pkgName.lastIndexOf('.');
		if (dot > 0) {
			String prevPart = pkgName.substring(0, dot);
			String shortName = pkgName.substring(dot + 1);
			pkg.setName(shortName);
			JPackage prevPkg = pkgs.get(prevPart);
			if (prevPkg == null) {
				prevPkg = new JPackage(prevPart);
				addPackage(pkgs, prevPkg);
			}
			prevPkg.getInnerPackages().add(pkg);
		}
	}

	@Override
	public Icon getIcon() {
		return ROOT_ICON;
	}

	@Override
	public JClass getJParent() {
		return null;
	}

	@Override
	public String makeString() {
		return "Source code";
	}
}
package jadx.tests.integration;

import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.IntegrationTest;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.C


SectionId::makerTags, signedShort, -1, EXV_PRINT_TAG(canonPictureStyle)},
    {0x000b, "ModifiedDigitalGain", N_("Modified Param Flag"), N_("Modified Param Flag"), IfdId::canonMoID,
     SectionId::makerTags, signedShort, -1, printValue},
};

const TagInfo* CanonMakerNote::tagListMo() {
  return tagInfoMo_;
}

// Canon Preview Quality Info, tag 0x0001
constexpr TagDetails canonPreviewQuality[] = {
    {-1, N_("n/a")},      {1, N_("Economy")}, {2, N_("Normal")},         {3, N_("Fine")},        {4, N_("RAW")},
    {5, N_("Superfine")}, {7, N_("CRAW")},    {130, N_("Normal Movie")}, {131, N_("Movie (2)")},
};

// Canon Preview Image Info Tag
constexpr TagInfo CanonMakerNote::tagInfoPreI_[] = {
    {0x0001, "PreviewQuality", N_("Preview Quality"), N_("Preview Quality"), IfdId::canonPreID, SectionId::makerTags,
     unsignedLong, -1, EXV_PRINT_TAG(canonPreviewQuality)},
    {0x0002, "PreviewImageLength", N_("Preview Image Length"), N_("Preview Image Length"), IfdId::canonPreID,
     SectionId::makerTags, unsignedLong, -1, printValue},
    {0x0003, "PreviewImageWidth", N_("Preview Image Width"), N_("Preview Image Width"), IfdId::canonPreID,
     SectionId::makerTags, unsignedLong, -1, printValue},
    {0x0004, "PreviewImageHeight", N_("Preview Image Height"), N_("Preview Image Height"), IfdId::canonPreID,
     SectionId::makerTags, unsignedLong, -1, printValue},
    {0x0005, "PreviewImageStart", N_("Preview Image Start"), N_("Preview Image Start"), IfdId::canonPreID,
     SectionId::makerTags, unsignedLong, -1, printValue},
};

const TagInfo* CanonMakerNote::tagListPreI() {
  return tagInfoPreI_;
}

// Canon Color Info Tag
constexpr TagInfo CanonMakerNote::tagInfoCi_[] = {
    {0x0001, "Saturation", N_("Saturation"), N_("Saturation"), IfdId::canonCiId, SectionId::makerTags, signedShort, -1,
     printValue},
    {0x0002, "ColorTone", N_("Color Tone"), N_("Color Tone"), IfdId::canonCiId, SectionId::makerTags, signedShort, -1,
     printValue},
    {0x0003, "ColorSpace", N_("Color Space"), N_("Color Space"), IfdId::canonCiId, SectionId::makerTags, signedShort,
     -1, EXV_PRINT_TAG(canonColorSpace)},
};

const TagInfo* CanonMakerNote::tagListCi() {
  return tagInfoCi_;
}

// Canon AFMicroAdjMode Quality Info, tag 0x0001
constexpr TagDetails canonAFMicroAdjMode[] = {
    {0, N_("Disable")},
    {1, N_("Adjust all by the same amount")},
    {2, N_("Adjust by lens")},
};

// Canon AFMicroAdj Info Tag
constexpr TagInfo CanonMakerNote::tagInfoAfMiAdj_[] = {
    {0x0001, "AFMicroAdjMode", N_("AFMicroAdjMode"), N_("AFMicroAdjMode"), IfdId::canonAfMiAdjId, SectionId::makerTags,
     signedLong, -1, EXV_PRINT_TAG(canonAFMicroAdjMode)},
    {0x0002, "AFMicroAdjValue", N_("AF Micro Adj Value"), N_("AF Micro Adj Value"), IfdId::canonAfMiAdjId,
     SectionId::makerTags, signedRational, -1, printValue},
    {0xffff, "(UnknownCanonA


      background: no-repeat -0px -4px url("/images/mlsec/model-2-10.png") #fff;
    }
    &.n6 {
      background: no-repeat -0px -4px url("/images/mlsec/model-2-10.png") #fff;
    }
    &.n7 {
      background: no-repeat -0px -4px url("/images/mlsec/model-2-10.png") #fff;
    }
    &.n8 {
      background: no-repeat -0px -4px url("/images/mlsec/model-2-10.png") #fff;
    }
    &.n9 {
      background: no-repeat -0px -4px url("/images/mlsec/model-2-10.png") #fff;
    }
    &.n10 {
      background: no-repeat -0px -4px url("/images/mlsec/model-2-10.png") #fff;
    }
    &.nJ {
      background: no-repeat -0px -4px url("/images/mlsec/model-J-A.png") #fff;
    }
    &.nQ {
      background: no-repeat -0px -4px url("/images/mlsec/model-J-A.png") #fff;
    }
    &.nK {
      background: no-repeat -0px -4px url("/images/mlsec/model-J-A.png") #fff;
    }
    &.nA {
      background: no-repeat -0px -4px url("/images/mlsec/model-J-A.png") #fff;
    }
    &.nJ, &.nQ, &.nK, &.nA, &.n2, &.n3, &.n4, &.n5, &.n6, &.n7, &.n8, &.n9, &.n10 {
      background-size: cover;
    }

    &.n2, &.n3, &.n4, &.n5, &.n6, &.n7, &.n8, &.n9, &.n10 {
      background-position: 4px -4px;
    }
  }

  &.input-risk {
    .left-value {
      //background: rgb(2, 113, 55)
    }

    .value {
      //color: rgb(185, 217, 165);
    }

    &.nJ, &.nQ, &.nK, &.nA {
      //background: rgb(116, 187, 99);

      .main-content {
        color: rgb(42, 10, 60);
      }

      .left-value {
        color: rgb(42, 10, 60);
        text-shadow: 2px 2px 2px rgba(42, 10, 60, 0.2);
      }
    }

    &.n10 {
      .left-value {
        left: clamp(166px, 16.6vw, 201px);
      }
    }

    &.n2 {
      background: no-repeat -0px -4px url("/images/mlsec/input-2-10.png") #fff;
    }
    &.n3 {
      background: no-repeat -0px -4px url("/images/mlsec/input-2-10.png") #fff;
    }
    &.n4 {
      background: no-repeat -0px -4px url("/images/mlsec/input-2-10.png") #fff;
    }
    &.n5 {
      background: no-repeat -0px -4px url("/images/mlsec/input-2-10.png") #fff;
    }
    &.n6 {
      background: no-repeat -0px -4px url("/images/mlsec/input-2-10.png") #fff;
    }
    &.n7 {
      background: no-repeat -0px -4px url("/images/mlsec/input-2-10.png") #fff;
    }
    &.n8 {
      background: no-re


.equ CV_SIGNATURE_C13, 4
.equ DEBUG_S_SYMBOLS, 0xf1

.equ T_VOID, 0x0003
.equ T_UQUAD, 0x0023
.equ T_UINT4, 0x0075

.equ LF_MODIFIER, 0x1001
.equ LF_POINTER, 0x1002
.equ LF_PROCEDURE, 0x1008
.equ LF_MFUNCTION, 0x1009
.equ LF_ARGLIST, 0x1201
.equ LF_FIELDLIST, 0x1203
.equ LF_CLASS, 0x1504
.equ LF_STRUCTURE, 0x1505
.equ LF_MEMBER, 0x150d
.equ LF_ONEMETHOD, 0x1511
.equ LF_FUNC_ID, 0x1601
.equ LF_MFUNC_ID, 0x1602

.equ LF_UQUADWORD, 0x800a

.equ S_END, 0x0006
.equ S_CONSTANT, 0x1107
.equ S_UDT, 0x1108
.equ S_LDATA32, 0x110c
.equ S_GDATA32, 0x110d
.equ S_LPROC32, 0x110f
.equ S_GPROC32, 0x1110
.equ S_LTHREAD32, 0x1112
.equ S_GTHREAD32, 0x1113
.equ S_LPROC32_ID, 0x1146
.equ S_GPROC32_ID, 0x1147
.equ S_PROC_ID_END, 0x114f

.equ CV_PTR_64, 0xc

.section ".debug$S", "rn"

.long CV_SIGNATURE_C13

.long DEBUG_S_SYMBOLS
.long .syms_end - .syms_start

.syms_start:

.ldata1:
.short .ldata1a - .ldata1 - 2
.short S_LDATA32
.long 0x1000 /* const uint32_t */
.secrel32 lvar1
.secidx lvar1
.asciz "lvar1"

.ldata1a: /* duplicate with same address */
.short .ldata1b - .ldata1a - 2
.short S_LDATA32
.long 0x1000 /* const uint32_t */
.secrel32 lvar1
.secidx lvar1
.asciz "lvar1"

.ldata1b: /* duplicate with different address */
.short .ldata2 - .ldata1b - 2
.short S_LDATA32
.long 0x1000 /* const uint32_t */
.secrel32 lvar1a
.secidx lvar1a
.asciz "lvar1"

.ldata2:
.short .gdata1 - .ldata2 - 2
.short S_LDATA32
.long 0x1000 /* const uint32_t */
.secrel32 lvar2
.secidx lvar2
.asciz "lvar2"

.gdata1:
.short .gdata2 - .gdata1 - 2
.short S_GDATA32
.long 0x1000 /* const uint32_t */
.secrel32 gvar1
.secidx gvar1
.asciz "gvar1"

.gdata2:
.short .gproc1 - .gdata2 - 2
.short S_GDATA32
.long 0x1000 /* const uint32_t */
.secrel32 gvar2
.secidx gvar2
.asciz "gvar2"

.gproc1:
.short .gproc1_end - .gproc1 - 2
.short S_GPROC32
.long 0 /* parent */
.long 0 /* end */
.long 0 /* next symbol */
.long .proc1_end - proc1 /* length */
.long 0 /* debug start offset */
.long 0 /* debug end offset */
.long 0x1002 /* type */
.secrel32 proc1
.secidx proc1
.byte 0 /* flags */
.asciz "proc1"
.byte 0xf3 /* padding */
.byte 0xf2 /* padding */
.byte 0xf1 /* padding */

.gproc1_end:
.short .gproc2 - .gproc1_end - 2
.short S_END

.gproc2:
.short .udt


trigok.Title_10.TextWrapped = true
trigok.Title_10.BorderSizePixel = 0
trigok.Title_10.TextScaled = true
trigok.Title_10.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
trigok.Title_10.FontFace = Font.new("rbxasset://fonts/families/FredokaOne.json", Enum.FontWeight.Regular, Enum.FontStyle.Normal)
trigok.Title_10.TextSize = 14
trigok.Title_10.Name = "Title"
trigok.Title_10.Size = UDim2.new(0.261373, 0, 0.111787, 0)
trigok.Title_10.TextColor3 = Color3.fromRGB(180, 193, 216)
trigok.Title_10.BorderColor3 = Color3.fromRGB(0, 0, 0)
trigok.Title_10.Text = "Script Name:"
trigok.Title_10.Position = UDim2.new(0.00832818, 0, 0.361132, 0)
trigok.Title_10.BackgroundTransparency = 1
trigok.Title_10.Parent = trigok.addFrame

trigok.TextLabel_5.TextWrapped = true
trigok.TextLabel_5.BorderSizePixel = 0
trigok.TextLabel_5.TextScaled = true
trigok.TextLabel_5.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
trigok.TextLabel_5.FontFace = Font.new("rbxasset://fonts/families/Inconsolata.json", Enum.FontWeight.Regular, Enum.FontStyle.Normal)
trigok.TextLabel_5.TextSize = 14
trigok.TextLabel_5.Size = UDim2.new(0.961488, 0, 0.222536, 0)
trigok.TextLabel_5.TextColor3 = Color3.fromRGB(225, 225, 225)
trigok.TextLabel_5.BorderColor3 = Color3.fromRGB(0, 0, 0)
trigok.TextLabel_5.Text = "Note: You just need to set the script name. The script will be added from your clipboard, so make sure to copy it before adding it."
trigok.TextLabel_5.Position = UDim2.new(0.0158422, 0, 0.0507511, 0)
trigok.TextLabel_5.BackgroundTransparency = 1
trigok.TextLabel_5.TextXAlignment = Enum.TextXAlignment.Left
trigok.TextLabel_5.Parent = trigok.addFrame

trigok.confrim_btn.BorderSizePixel = 0
trigok.confrim_btn.Size = UDim2.new(0.345421, 0, 0.157611, 0)
trigok.confrim_btn.Position = UDim2.new(0.542995, 0, 0.709694, 0)
trigok.confrim_btn.BorderColor3 = Color3.fromRGB(0, 0, 0)
trigok.confrim_btn.Name = "confrim_btn"
trigok.confrim_btn.BackgroundColor3 = Color3.fromRGB(55, 60, 76)
trigok.confrim_btn.Parent = trigok.addFrame

trigok.TextButton_3.TextWrapped = true
trigok.TextButton_3.BorderSizePixel = 0
trigok.TextButton_3.RichText = true
trigok.TextButton_3.TextScaled = true
trigok.TextButton_3.BackgroundColor3 = Color3.fromRGB(55, 60, 76)
trigok.TextButton_3.FontFace = Font.new("rbxasset://fonts/families/FredokaOne.json", Enum.FontWeight.Regular, Enum.FontStyle.Normal)
trigok.TextButton_3.Position = UDim2.new(0.0427491, 0, 0.159589, 0)
trigok.TextButton_3.TextSize = 14
trigok.TextButton_3.Size = UDim2.new(0.909


:Article6) RETURN a")

        neo4j.executeTransactionally("""
                    UNWIND range(1, 26) AS index
                    MATCH (a:Article6) WITH a ORDER BY a.id
                    WITH collect(a) AS articles
                    CALL apoc.nlp.gcp.classify.graph(articles, {
                      key: ${'$'}apiKey,
                      nodeProperty: "body",
                      unsupportedDummyClient: true
                    })
                    YIELD graph AS g
                    RETURN g.nodes AS nodes, g.relationships AS relationships
                """.trimIndent(), mapOf("apiKey" to apiKey)) {

            assertTrue(it.hasNext())
            val row1 = it.next()
            Assert.assertEquals(51, (row1["nodes"] as List<Node>).size) // 50 dummy nodes + source node

            assertTrue(it.hasNext())
            val row2 = it.next()

            val nodes: List<Node> = row2["nodes"] as List<Node>
            val relationships = row2["relationships"] as List<Relationship>
            Assert.assertEquals(3, nodes.size) // 2 dummy nodes + source node

            val dummyLabels = listOf( Label {"Category"})

            assertThat(nodes, hasItem(nodeMatcher))
            assertThat(nodes, hasItem(NodeMatcher(dummyLabels, mapOf("text" to "category-1-index-0-batch-1"))))
            assertThat(nodes, hasItem(NodeMatcher(dummyLabels, mapOf("text" to "category-2-index-0-batch-1"))))

            Assert.assertEquals(2, relationships.size)
            assertThat(relationships, hasItem(RelationshipMatcher(virtualSourceNode, VirtualNode(dummyLabels.toTypedArray(), mapOf("text" to "category-1-index-0-batch-1")), "CATEGORY", mapOf("score" to 0.1))))
            assertThat(relationships, hasItem(RelationshipMatcher(virtualSourceNode, VirtualNode(dummyLabels.toTypedArray(), mapOf("text" to "category-2-index-0-batch-1")), "CATEGORY", mapOf("score" to 0.2))))
        }
    }

    @Test
    fun `create virtual entity graph based on salience cut off`() {
        neo4j.executeTransactionally("""CREATE (a:Article7 {id: 1234, body:${'$'}body})""", mapOf("body" to "test"))

        val (sourceNode, virtualSourceNode, nodeMatcher) = commonNlpInit(neo4j, "MATCH (a:Article7) RETURN a")

        neo4j.executeTransactionally("""
                    MATCH (a:Article7) WITH a ORDER BY a.id
                    WITH collect(a) AS articles
                    CALL apoc.nlp.gcp.entities.graph(articles, {
                      key: ${'$'}apiKey,
                      nodeProperty: "body",
                      unsupportedDummyClient: true,
                      scoreCutoff: 0.15,
                      writeRelationshipType: "HAS_ENTITY",
                      writeRelationshipProperty: "gcpScore"
                    })
                    YIELD graph AS g
                    RETURN g.nodes AS nodes, g.relationships AS relationships
                """.trimIndent(), mapOf("apiKey" to apiKey)) {

            assertTrue(it.hasNext())
            val row = it.next()

            val nodes: List<Node> = row["nodes"] as List<Node>
            val relationships = row["relationships"] as List<Relationship>
            Assert.assertEquals(2, nodes.size) // 1 dummy node + source node

            val dummyLabels2 = listOf(Label { "Location"}, Label {"Entity"})

            assertThat(nodes, hasItem(nodeMatcher))
            assertThat(nodes, hasItem(NodeMatcher(dummyLabels2, mapOf("text" to "token-2-index-0-batch-0", "type" to "LOCATION"))))

            Assert.assertEquals(1, relationships.size)
            assertThat(relations


ZO_Dialogs_RegisterCustomDialog("HOUSE_TOURS_SEARCH_FILTERS_KEYBOARD",
    {
        customControl = control,
        setup = function(dialog, data)
            dialog.object:PerformDeferredInitialize()
            local filterData = data.filterData
            dialog.object:SetFilterData(filterData)
        end,
        title =
        {
            text = SI_HOUSE_TOURS_ALL_FILTERS,
        },
        buttons =
        {
            {
                control = control:GetNamedChild("Reset"),
                keybind = "DIALOG_RESET",
                text = SI_HOUSE_TOURS_RESET_FILTERS_KEYBIND,
                noReleaseOnClick = true,
                callback = function(dialog)


@property
def summary_str(self):
    return str(self)


;
            CheckAndPutCondition checkAndPutCondition1 =
                    new CheckAndPutCondition(checkColumn1, op, 1234L, null);
            if (op == CheckCompareOp.IS_NULL || op == CheckCompareOp.IS_NOT_NULL) {
                // 已有数据与null做比较：old column is null
                Assert.assertEquals(
                        " old.\"TEST_Column\" " + op.getOperatorString(),
                        builder.buildCheckAndPutPattern(checkAndPutCondition1));
            } else {
                Assert.assertEquals(
                        " '1234'::bigint " + op.getOperatorString() + " old.\"TEST_Column\"",
                        builder.buildCheckAndPutPattern(checkAndPutCondition1));
            }
        }

        // 常量与已有数据做比较：checkValue checkOp old column, 已有数据为null时进行coalesce
        for (CheckCompareOp op : CheckCompareOp.values()) {
            Column checkColumn1 = new Column();
            checkColumn1.setName("TEST_Column");
            checkColumn1.setType(Types.BIGINT);
            checkColumn1.setTypeName("bigint");
            CheckAndPutCondition checkAndPutCondition1 =
                    new CheckAndPutCondition(checkColumn1, op, 1234L, 0L);
            if (op == CheckCompareOp.IS_NULL || op == CheckCompareOp.IS_NOT_NULL) {
                Assert.assertEquals(
                        " coalesce(old.\"TEST_Column\", '0'::bigint) " + op.getOperatorString(),
                        builder.buildCheckAndPutPattern(checkAndPutCondition1));
            } else {
                Assert.assertEquals(
                        " '1234'::bigint "
                                + op.getOperatorString()
                                + " coalesce(old.\"TEST_Column\", '0'::bigint)",
                        builder.buildCheckAndPutPattern(checkAndPutCondition1));
            }
        }
    }

    @Test
    public void testBuildCheckAndDeletePattern() {
        HoloConfig config = buildConfig();
        UpsertStatementBuilder builder = new UpsertStatementBuilder(config);
        // 准备删除的数据与已有数据做比较： new column checkOp old column
        for (CheckCompareOp op : CheckCompareOp.values()) {
            Column checkColumn1 = new Column();
            checkColumn1.setName("TEST_Column");
            checkColumn1.setType(Types.BIGINT);
            checkColumn1.setTypeName("bigint");
            CheckAndPutCondition checkAndPutCondition1 =
                    new CheckAndPutCondition(checkColumn1, op, null, null);
            if (op == CheckCompareOp.IS_NULL || op == CheckCompareOp.IS_NOT_NULL) {
                // 已有数据与null做比较：old column is null
                Assert.assertEquals(
                        " \"TEST_Column\" " + op.getOperatorString(),
                        builder.buildCheckAndDeletePattern(checkAndPutCondition1));
            } else {
                Assert.assertEquals(
                        " ? " + op.getOperatorString() + " \"TEST_Column\"",
                        builder.buildCheckAndDeletePattern(checkAndPutCondition1));
            }
        }

        // 准备删除的数据与已有数据做比较： new column checkOp old column, 已有数据为null时进行coalesce
        for (CheckCompareOp op : CheckCompareOp.values()) {
            Column checkColumn1 = new Column();
            checkColumn1.setName("TEST_Column");
            checkColumn1.setType(Types.BIGINT);
            checkColumn1.setTypeName("bigint");
            CheckAndPutCondition checkAndPutCondition1 =
                    new CheckAndPutCondition(checkColumn1, op, null, 0L);
            if (op == CheckCompareOp.IS_NULL || op == CheckCompareOp.IS_NOT_NULL) {
                // 已有数据与null做比较：old column is null
                Assert.assertEquals(
                        " coalesce


        f(&mut w);
        self.register.set(w.bits);
    }
    #[doc = r" Writes the reset value to the register"]
    #[inline]
    pub fn reset(&self) {
        self.write(|w| w)
    }
}
#[doc = "Possible values of the field `OUTDIV4`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OUTDIV4R {
    #[doc = "Divide-by-1."]
    _000,
    #[doc = "Divide-by-2."]
    _001,
    #[doc = "Divide-by-3."]
    _010,
    #[doc = "Divide-by-4."]
    _011,
    #[doc = "Divide-by-5."]
    _100,
    #[doc = "Divide-by-6."]
    _101,
    #[doc = "Divide-by-7."]
    _110,
    #[doc = "Divide-by-8."]
    _111,
}
impl OUTDIV4R {
    #[doc = r" Value of the field as raw bits"]
    #[inline]
    pub fn bits(&self) -> u8 {
        match *self {
            OUTDIV4R::_000 => 0,
            OUTDIV4R::_001 => 1,
            OUTDIV4R::_010 => 2,
            OUTDIV4R::_011 => 3,
            OUTDIV4R::_100 => 4,
            OUTDIV4R::_101 => 5,
            OUTDIV4R::_110 => 6,
            OUTDIV4R::_111 => 7,
        }
    }
    #[allow(missing_docs)]
    #[doc(hidden)]
    #[inline]
    pub fn _from(value: u8) -> OUTDIV4R {
        match value {
            0 => OUTDIV4R::_000,
            1 => OUTDIV4R::_001,
            2 => OUTDIV4R::_010,
            3 => OUTDIV4R::_011,
            4 => OUTDIV4R::_100,
            5 => OUTDIV4R::_101,
            6 => OUTDIV4R::_110,
            7 => OUTDIV4R::_111,
            _ => unreachable!(),
        }
    }
    #[doc = "Checks if the value of the field is `_000`"]
    #[inline]
    pub fn is_000(&self) -> bool {
        *self == OUTDIV4R::_000
    }
    #[doc = "Checks if the value of the field is `_001`"]
    #[inline]
    pub fn is_001(&self) -> bool {
        *self == OUTDIV4R::_001
    }
    #[doc = "Checks if the value of the field is `_010`"]
    #[inline]
    pub fn is_010(&self) -> bool {
        *self == OUTDIV4R::_010
    }
    #[doc = "Checks if the value of the field is `_011`"]
    #[inline]
    pub fn is_011(&self) -> bool {
        *self == OUTDIV4R::_011
    }
    #[doc = "Checks if the value of the field is `_100`"]
    #[inline]
    pub fn is_100(&self) -> bool {
        *self == OUTDIV4R::_100
    }
    #[doc = "Checks if the value of the field is `_101`"]
    #[inline]
    pub fn is_101(&self) -> bool {
        *self == OUTDIV4R::_101
    }
    #[doc = "Checks if the value of the field is `_110`"]
    #[inline]
    pub fn is_110(&self) -> bool {
        *self == OUTDIV4R::_110
    }
    #[doc = "Checks if the value of the field is `_111`"]
    #[inline]
    pub fn is_111(&


using System;
using System.Globalization;
using UnityEngine;
using UnityEngine.Serialization;

namespace AutoLootHeavies;

public static class Config
{
    private static Options _options;
    private static ConfigReader _con;

    public static void WriteOptions()
    {
        _con.UpdateValue("TeleportToDumpSiteWhenAllStockPilesFull", _options.teleportToDumpSiteWhenAllStockPilesFull.ToString());
        _con.UpdateValue("DesignatedTimberLocation",
            $"{_options.designatedTimberLocation.x},{_options.designatedTimberLocation.y},{_options.designatedTimberLocation.z}".ToString(CultureInfo.InvariantCulture));
        _con.UpdateValue("DesignatedOreLocation",
            $"{_options.designatedOreLocation.x},{_options.designatedOreLocation.y},{_options.designatedOreLocation.z}".ToString(CultureInfo.InvariantCulture));
        _con.UpdateValue("DesignatedStoneLocation",
            $"{_options.designatedStoneLocation.x},{_options.designatedStoneLocation.y},{_options.designatedStoneLocation.z}".ToString(CultureInfo.InvariantCulture));
    }

    public static Options GetOptions(bool external = false)
    {
        _options = new Options();
        _con = new ConfigReader(external);

        bool.TryParse(_con.Value("TeleportToDumpSiteWhenAllStockPilesFull", "true"), out var teleportToDumpSiteWhenAllStockPilesFull);
        _options.teleportToDumpSiteWhenAllStockPilesFull = teleportToDumpSiteWhenAllStockPilesFull;

        bool.TryParse(_con.Value("DisableImmersionMode", "false"), out var disableImmersionMode);
        _options.disableImmersionMode = disableImmersionMode;

        bool.TryParse(_con.Value("Debug", "false"), out var debug);
        _options.debug = debug;

        var tempT = _con.Value("DesignatedTimberLocation", "-3712.003,6144,1294.643".ToString(CultureInfo.InvariantCulture)).Split(',');
        var tempO = _con.Value("DesignatedOreLocation", "-3712.003,6144,1294.643".ToString(CultureInfo.InvariantCulture)).Split(',');
        var tempS = _con.Value("DesignatedStoneLocation", "-3712.003,6144,1294.643".ToString(CultureInfo.InvariantCulture)).Split(',');

        _options.designatedTimberLocation =
            new Vector3(float.Parse(tempT[0], CultureInfo.InvariantCulture), float.Parse(tempT[1], CultureInfo.InvariantCulture), float.Parse(tempT[2], CultureInfo.InvariantCulture));
        _options.designatedOreLocation =
            new Vector3(float.Parse(tempO[0], CultureInfo.InvariantCulture), float.Parse(tempO[1], CultureInfo.InvariantCulture), float.Parse(tempO[2], CultureInfo.InvariantCulture));
        _options.designatedStoneLocation =
            new Vector3(float.Parse(tempS[0], CultureInfo.InvariantCulture), float.Parse(tempS[1], CultureInfo.InvariantCulture), float.Parse(tempS[2], CultureInfo.InvariantCulture));

        var a1 = Enum.TryParse<KeyCode>(_con.Value("ToggleTeleportToDumpSiteKeybind", "Alpha6"), true, out var a2);
        if (a1)
        {
            _options.toggleTeleportToDumpSiteKeybind = a2;
            if (!external)
            {
                Debug.LogWarning($"[AutoLootHeavies]: Parsed '{a2}' for 'ToggleTeleportToDumpSiteKeybind'.");
            }
        }
        else
        {
            _options.toggleTeleportToDumpSiteKeybind = KeyCode.Alpha6;
            if (!external)
            {
                Debug.LogWarning($"[AutoLootHeavies]: Failed to parse key for 'ToggleTeleportToDumpSiteKeybind'. Setting to default Alpha6.");
            }
        }

        var b1 = Enum.TryParse<KeyCode>(_con.Value("SetTimberLocationKeybind", "Alpha7"), true, out v


type to struct and vice versa.
        return when (type.typeName) {
            Struct.TYPE,
            UnsupportedOneOf.TYPE ->
                DSL.field(
                    CASE_STATEMENT_NO_ELSE_SQL_TEMPLATE,
                    jsonTypeOf(field).eq("object"),
                    DSL.cast(field, structType)
                )
            Array.TYPE ->
                DSL.field(
                    CASE_STATEMENT_NO_ELSE_SQL_TEMPLATE,
                    jsonTypeOf(field).eq("array"),
                    DSL.cast(field, arrayType)
                )
            Union.TYPE -> castedField(field, (type as Union).chooseType(), useExpensiveSaferCasting)
            else -> throw IllegalArgumentException("Unsupported AirbyteType: $type")
        }
    }

    override fun extractRawDataFields(
        columns: LinkedHashMap<ColumnId, AirbyteType>,
        useExpensiveSaferCasting: Boolean
    ): MutableList<Field<*>> {
        return columns.entries
            .stream()
            .map { column: Map.Entry<ColumnId, AirbyteType> ->
                castedField(
                        DSL.field(
                            DSL.quotedName(
                                JavaBaseConstants.COLUMN_NAME_DATA,
                                column.key.originalName
                            )
                        ),
                        column.value,
                        useExpensiveSaferCasting
                    )
                    .`as`(column.key.name)
            }
            .collect(Collectors.toList<Field<*>>())
    }

    private fun jsonTypeOf(field: Field<*>): Field<String> {
        return DSL.function("JSON_TYPEOF", SQLDataType.VARCHAR, field)
    }

    private fun jsonSerialize(field: Field<*>): Field<String> {
        return DSL.function("JSON_SERIALIZE", SQLDataType.VARCHAR, field)
    }

    /**
     * Redshift ARRAY_CONCAT supports only 2 arrays. Iteratively nest ARRAY_CONCAT to support more
     * than 2
     *
     * @param arrays
     * @return
     */
    private fun arrayConcatStmt(arrays: List<Field<*>?>): Field<*>? {
        if (arrays.isEmpty()) {
            return DSL.field("ARRAY()") // Return an empty string if the list is empty
        }

        var result = arrays[0]
        for (i in 1 until arrays.size) {
            // We lose some nice indentation but thats ok. Queryparts
            // are intentionally rendered here to avoid deep stack for function sql rendering.
            result =
                DSL.field(
                    dslContext.renderNamedOrInlinedParams(
                        DSL.function("ARRAY_CONCAT", superType, result, arrays[i])
                    )
                )
        }
        return result
    }

    private fun toCastingErrorCaseStmt(column: ColumnId, type: AirbyteType): Field<*> {
        val field: Field<*> =
            DSL.field(DSL.quotedName(JavaBaseConstants.COLUMN_NAME_DATA, column.originalName))
        // Just checks if data is not null but casted data is null. This also accounts for
        // conditional
        // casting result of array and struct.
        // TODO: Timestamp format issues can result in null values when cast, add regex check if
        // destination
        // supports regex functions.
        return DSL.field(
            CASE_STATEMENT_SQL_TEMPLATE,
            field.isNotNull().and(castedField(field, type, true).`as`(column.name).isNull()),
            DSL.function(
                "ARRAY",
                superType,
                DSL.function(
                    "JSON_PARSE",
                    superType,
                    DSL.`val`(
                        "{\"field\": \"" +
                            column.name +
                            "\",


using System;
using System.Xml.Serialization;

namespace Aop.Api.Domain
{
    /// <summary>
    /// RegisterApplyInfoDTO Data Structure.
    /// </summary>
    [Serializable]
    public class RegisterApplyInfoDTO : AopObject
    {
        /// <summary>
        /// 申请id
        /// </summary>
        [XmlElement("apply_id")]
        public string ApplyId { get; set; }

        /// <summary>
        /// 申请时间
        /// </summary>
        [XmlElement("apply_time")]
        public string ApplyTime { get; set; }

        /// <summary>
        /// 审核备注
        /// </summary>
        [XmlElement("audit_remark")]
        public string AuditRemark { get; set; }

        /// <summary>
        /// 审核状态
        /// </summary>
        [XmlElement("audit_status")]
        public string AuditStatus { get; set; }

        /// <summary>
        /// 审核时间
        /// </summary>
        [XmlElement("audit_time")]
        public string AuditTime { get; s