B, 0x1A,// VEX_Vfnmsub132sd_xmm_xmm_xmmm64
		0x00,// Invalid
		0x00,// Invalid

	// 160 = 0xA0
	0x02,// Dup
		0x06,// 6
		0x00,// Invalid

	// 166 = 0xA6
	0x0B,// MandatoryPrefix2_4
		0x00,// Invalid
		0x09,// W
			0x0E,// VectorLength
				0x29,// VHW_2
					0x4D,// XMM0
					0xE6, 0x1A,// VEX_Vfmaddsub213ps_xmm_xmm_xmmm128
				0x29,// VHW_2
					0x6D,// YMM0
					0xE7, 0x1A,// VEX_Vfmaddsub213ps_ymm_ymm_ymmm256
			0x0E,// VectorLength
				0x29,// VHW_2
					0x4D,// XMM0
					0xE8, 0x1A,// VEX_Vfmaddsub213pd_xmm_xmm_xmmm128
				0x29,// VHW_2
					0x6D,// YMM0
					0xE9, 0x1A,// VEX_Vfmaddsub213pd_ymm_ymm_ymmm256
		0x00,// Invalid
		0x00,// Invalid

	// 167 = 0xA7
	0x0B,// MandatoryPrefix2_4
		0x00,// Invalid
		0x09,// W
			0x0E,// VectorLength
				0x29,// VHW_2
					0x4D,// XMM0
					0xF0, 0x1A,// VEX_Vfmsubadd213ps_xmm_xmm_xmmm128
				0x29,// VHW_2
					0x6D,// YMM0
					0xF1, 0x1A,// VEX_Vfmsubadd213ps_ymm_ymm_ymmm256
			0x0E,// VectorLength
				0x29,// VHW_2
					0x4D,// XMM0
					0xF2, 0x1A,// VEX_Vfmsubadd213pd_xmm_xmm_xmmm128
				0x29,// VHW_2
					0x6D,// YMM0
					0xF3, 0x1A,// VEX_Vfmsubadd213pd_ymm_ymm_ymmm256
		0x00,// Invalid
		0x00,// Invalid

	// 168 = 0xA8
	0x0B,// MandatoryPrefix2_4
		0x00,// Invalid
		0x09,// W
			0x0E,// VectorLength
				0x29,// VHW_2
					0x4D,// XMM0
					0xFA, 0x1A,// VEX_Vfmadd213ps_xmm_xmm_xmmm128
				0x29,// VHW_2
					0x6D,// YMM0
					0xFB, 0x1A,// VEX_Vfmadd213ps_ymm_ymm_ymmm256
			0x0E,// VectorLength
				0x29,// VHW_2
					0x4D,// XMM0
					0xFC, 0x1A,// VEX_Vfmadd213pd_xmm_xmm_xmmm128
				0x29,// VHW_2
					0x6D,// YMM0
					0xFD, 0x1A,// VEX_Vfmadd213pd_ymm_ymm_ymmm256
		0x00,// Invalid
		0x00,// Invalid

	// 169 = 0xA9
	0x0B,// MandatoryPrefix2_4
		0x00,// Invalid
		0x09,// W
			0x29,// VHW_2
				0x4D,// XMM0
				0x84, 0x1B,


" preserveAspectRatio="xMidYMid meet" viewBox="0 0 16 16"><path fill="currentColor" d="M15.825.12a.5.5 0 01.132.584c-1.53 3.43-4.743 8.17-7.095 10.64a6.067 6.067 0 01-2.373 1.534c-.018.227-.06.538-.16.868-.201.659-.667 1.479-1.708 1.74a8.118 8.118 0 01-3.078.132 3.659 3.659 0 01-.562-.135 1.382 1.382 0 01-.466-.247.714.714 0 01-.204-.288.622.622 0 01.004-.443c.095-.245.316-.38.461-.452.394-.197.625-.453.867-.826.095-.144.184-.297.287-.472l.117-.198c.151-.255.326-.54.546-.848.528-.739 1.201-.925 1.746-.896.126.007.243.025.348.048.062-.172.142-.38.238-.608.261-.619.658-1.419 1.187-2.069 2.176-2.67 6.18-6.206 9.117-8.104a.5.5 0 01.596.04zM4.705 11.912a1.23 1.23 0 00-.419-.1c-.246-.013-.573.05-.879.479-.197.275-.355.532-.5.777l-.105.177c-.106.181-.213.362-.32.528a3.39 3.39 0 01-.76.861c.69.112 1.736.111 2.657-.12.559-.139.843-.569.993-1.06a3.122 3.122 0 00.126-.75l-.793-.792zm1.44.026c.12-.04.277-.1.458-.183a5.068 5.068 0 001.535-1.1c1.9-1.996 4.412-5.57 6.052-8.631-2.59 1.927-5.566 4.66-7.302 6.792-.442.543-.795 1.243-1.042 1.826-.121.288-.214.54-.275.72v.001l.575.575zm-4.973 3.04.007-.005a.031.031 0 01-.007.004zm3.582-3.043.002.001h-.002z"/></svg>';
  static const String brush_fill =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16" height="16" preserveAspectRatio="xMidYMid meet" viewBox="0 0 16 16"><path fill="currentColor" d="M15.825.12a.5.5 0 01.132.584c-1.53 3.43-4.743 8.17-7.095 10.64a6.067 6.067 0 01-2.373 1.534c-.018.227-.06.538-.16.868-.201.659-.667 1.479-1.708 1.74a8.118 8.118 0 01-3.078.132 3.659 3.659 0 01-.562-.135 1.382 1.382 0 01-.466-.247.714.714 0 01-.204-.288.622.622 0 01.004-.443c.095-.245.316-.38.461-.452.394-.197.625-.453.867-.826.095-.144.184-.297.287-.472l.117-.198c.151-.255.326-.54.546-.848.528-.739 1.201-.925 1.746-.896.126.007.243.025.348.048.062-.172.142-.38.238-.608.261-.619.658-1.419 1.187-2.069 2.176-2.67


 #else
 #include <QDesktopServices>
 #endif

 #define IPC_READ
#endif

using namespace Global;

#define CUSTOM_STATUS

#define TOO_CHAPTERS_WORKAROUND

MPVProcess::MPVProcess(QObject * parent)
	: PlayerProcess(parent)
	, notified_mplayer_is_running(false)
	, notified_pause(false)
	, received_end_of_file(false)
	, last_sub_id(-1)
	, mplayer_svn(-1) // Not found yet
	, verbose(false)
#if NOTIFY_SUB_CHANGES
	, subtitle_info_received(false)
	, subtitle_info_changed(false)
	, selected_subtitle(-1)
#endif
#if NOTIFY_AUDIO_CHANGES
	, audio_info_changed(false)
	, selected_audio(-1)
#endif
#if NOTIFY_VIDEO_CHANGES
	, video_info_changed(false)
	, selected_video(-1)
#endif
#if NOTIFY_CHAPTER_CHANGES
	, chapter_info_changed(false)
#endif
	, dvd_current_title(-1)
	, br_current_title(-1)
	//, dwidth(0)
	//, dheight(0)
	, duration(0)
	, idle(true)
{
	player_id = PlayerID::MPV;

	connect( this, SIGNAL(lineAvailable(QByteArray)),
			 this, SLOT(parseLine(QByteArray)) );

	connect( this, SIGNAL(finished(int,QProcess::ExitStatus)),
             this, SLOT(processFinished(int,QProcess::ExitStatus)) );

	connect( this, SIGNAL(error(QProcess::ProcessError)),
             this, SLOT(gotError(QProcess::ProcessError)) );

	/* int svn = MplayerVersion::mplayerVersion("mpv unknown version (C)"); */

	initializeOptionVars();
	initializeRX();

#ifdef USE_IPC
	socket = new QLocalSocket(this);
	connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead()));
	#if QT_VERSION >= 0x050000
	QString temp_dir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
	#else
	QString temp_dir = QDesktopServices::storageLocation(QDesktopServices::TempLocation);
	#endif
	socket_name = temp_dir + "/smplayer-mpv-" + QString::number(QCoreApplication::applicationPid(), 16);
	qDebug() << "MPVProcess::MPVProcess: socket_name:" << socket_name;
#endif
}

MPVProcess::~MPVProcess() {
#ifdef USE_IPC
	if (QFile::exists(socket_name)) {
		QFile::remove(socket_name);
	}
#endif
}

#ifdef USE_IPC
void MPVProcess::setSocketName(const QString & name) {
	// Remove old socket
	if (!socket_name.isEmpty() && QFile::exists(socket_name)) {
		QFile::remove(socket_name);
	}
	socket_name = name;
	qDebug() << "MPVProcess::setSocketName:" << socket_name;
}
#endif

bool MPVProcess::start() {
	md.reset();
	notified_mplayer_is_running = false;
	notified_pause = false;
	last_sub_id = -1;
	mplayer_svn = -1; // Not found yet
	received_end_of_file = false;

#if NOTIFY_SUB_CHANGES
	subs.clear();
	subtitle_info_received = false;
	subtitle_info_changed = false;
	selected_subtitle = -1;
#endif

#if NOTIFY_AUDIO_CHANGES
	audios.clear();
	audio_info_changed = false;
	selected_audio = -1;
#endif

#if NOTIFY_VIDEO_CHANGES
	videos.clear();
	video_info_changed = false;
	selected_video = -1;
#endif

#if NOTIFY_CHAPTER_CHANGES
	chapters.clear();
	chapter_info_changed = false;
#endif

	dvd_current_title = -1;
	br_current_title = -1;

	//dwidth = 0;
	//dheight


import uuid

from sqlmodel import select
from typing import List, Union
from uuid import UUID
from fastapi import HTTPException

from clueless.app.db.crud.base import BaseCRUD
from clueless.app.db.models.room import RoomBase, Room, RoomRead, RoomCreate, RoomUpdate, RoomCreateUI

class RoomCRUD(BaseCRUD):

    def get_by_id_or_key(self, _id: Union[str, UUID]) -> RoomRead:
        """
        Gets the room by either the alphanumeric room key or by the ID
        :param _id:
        :return:
        """
        # try string to UUID conversion
        if isinstance(_id, str):
            try:
                uuid_obj = UUID(_id)
                _id = uuid_obj
            except ValueError:
                pass

        # Get room by uuid
        if isinstance(_id, UUID):
            return self.get(_id=_id)
        # Get room by room_key
        elif isinstance(_id, str):
            return self.get_by_room_key(room_key=_id)
        # Invalid ID
        else:
            raise HTTPException(status_code=500, detail=f"Invalid type for id, {type(_id)}")

    def get_by_room_key(self, room_key: str) -> RoomRead:
        return self.session.exec(select(Room).where(Room.room_key == room_key)).one()

    def get(self, _id: UUID) -> RoomRead:
        room = self.session.get(Room, _id)
        if not room:
            raise HTTPException(status_code=404, detail="Room not found")
        return room

    def get_all(self) -> List[RoomRead]:
        rooms = self.session.exec(select(Room)).all()
        return rooms

    def create(self, room: RoomCreate) -> RoomRead:
        print("CREATE")
        # room.users = [str(room.host)]
        db_room = Room.model_validate(room)
        db_room.users = [str(room.host)]
        self.session.add(db_room)
        self.session.commit()
        self.session.refresh(db_room)

        return db_room

    def delete(self, _id: UUID) -> RoomRead:
        room = self.session.get(Room, _id)
        if not room:
            raise HTTPException(status_code=404, detail="Hero not found")
        self.session.delete(room)
        self.session.commit()
        return True

    def update(self, _id: UUID, room: RoomUpdate) -> RoomRead:
        db_room = self.session.get(Room, _id)
        if not db_room:
            raise HTTPException(status_code=404, detail="Room not found")
        room_data = room.model_dump(exclude_unset=True)
        db_room.sqlmodel_update(room_data)
        self.session.add(db_room)
        self.session.commit()
        self.session.refresh(db_room)
        return db_room

    def add_player(self, _id: UUID, player_id: UUID) -> RoomRead:
        room = self.get(_id=_id)

        new_room = RoomUpdate(users=room.users)
        new_room.users.append(str(player_id))

        return self.update(_id=_id, room=new_room)


r0, #1
	strh	r2, [r4, r3]	@ movhi
	movw	r3, #3160
	str	r5, [r4, #2592]
	strh	r5, [r4, r3]	@ movhi
	movw	r3, #3206
	str	r5, [r4, #2576]
	strh	r5, [r4, r3]	@ movhi
	movw	r3, #3242
	str	r5, [r4, #2564]
	strh	r5, [r4, r3]	@ movhi
	str	r5, [r4, #2560]
	str	r5, [r4, #2568]
	str	r5, [r4, #2572]
	str	r5, [r4, #2556]
	str	r5, [r4, #2596]
	str	r5, [r4, #2600]
	str	r5, [r4, #2608]
	str	r5, [r4, #2612]
	str	r5, [r4, #2616]
	str	r5, [r4, #3272]
	str	r5, [r4, #3164]
	str	r5, [r4, #3280]
	str	r5, [r4, #3156]
	str	r5, [r4, #3284]
	bl	ftl_malloc
	str	r0, [r4, #3192]
	ldrh	r0, [r4, r6]
	mul	r0, r7, r0
	bl	ftl_malloc
	ldrh	r6, [r4, #232]
	str	r0, [r4, #3200]
	mul	r8, r8, r6
	mov	r0, r8
	bl	ftl_malloc
	mov	r3, #20
	str	r0, [r4, #3288]
	mul	r6, r3, r6
	mov	r0, r6
	bl	ftl_malloc
	str	r0, [r4, #3292]
	mov	r0, r8
	movw	r8, #310
	bl	ftl_malloc
	str	r0, [r4, #3296]
	mov	r0, r6
	bl	ftl_malloc
	str	r0, [r4, #3268]
	mov	r0, r6
	bl	ftl_malloc
	ldrh	r3, [r4, #232]
	ldrh	r6, [r4, r8]
	str	r0, [r4, #3184]
	lsl	r3, r3, #1
	mov	r0, r6
	add	r3, r3, #1
	str	r3, [r4, #3188]
	bl	ftl_malloc
	str	r0, [r4, #3300]
	mov	r0, r6
	bl	ftl_malloc
	str	r0, [r4, #3304]
	mov	r0, r6
	bl	ftl_malloc
	str	r0, [r4, #3308]
	ldr	r0, [r4, #3188]
	mul	r0, r0, r6
	bl	ftl_malloc
	str	r0, [r4, #3176]
	mov	r0, r6
	bl	ftl_malloc
	str	r0, [r4, #3312]
	mov	r0, r6
	bl	ftl_malloc
	str	r0, [r4, #3316]
	ldr	r0, [r4, #3188]
	mul	r0, r7, r0
	bl	ftl_malloc
	str	r0, [r4, #3172]


态服务器的调度相关信息
     */
    fun getCustomerDispatcherWithCache(organizationId: Int, userId: Long): Mono<CustomerDispatcherDto> {
        return messageService.findStaffIdOrShuntIdOfCustomer(organizationId, userId)
            .cache()
    }

    /**
     * 通过 机构id[organizationId] 和 用户id[userId] 获取上缓存服务器上的会话信息
     */
    fun getLastConversationWithCache(organizationId: Int, userId: Long): Mono<ConversationStatusDto> {
        return messageService.findConversationByUserId(organizationId, userId)
            .cache()
    }

    /**
     * 设置会话结束
     */
    fun endConversation(conversationStatusDto: Mono<ConversationStatusDto>): Mono<Unit> {
        return conversationStatusDto
            .transform { messageService.endConversation(it) }
    }

    /**
     * 更新会话信息
     * 然后 发送分配消息到消息服务器
     * 消息服务器会发送消息给客服
     */
    fun saveConversation(conversationStatusDto: Mono<ConversationStatusDto>): Mono<ConversationStatusDto> {
        val conversationStatusWithId = conversationStatusDto
            .doOnNext {
                it.closeReason = null
                it.endTime = null
            }
            .transform {
                messageService.saveConversation(it)
            }.cache()
        return conversationStatusWithId
            .filter { cov -> cov.interaction == 1 }
            .flatMap {
                val mono = it.toMono()
                messageService.sendAssignmentSignal(mono).then(mono)
            }
            .switchIfEmpty(conversationStatusWithId)
    }

    /**
     * 通过 [staffChangeStatusDto] 调用客服状态服务器分配座席信息，成功就返回然后新建会话信息
     */
    fun assignmentCustomer(staffChangeStatusDto: Mono<StaffChangeStatusDto>): Mono<ResponseEntity<Void>> {
        return messageService.assignmentCustomer(staffChangeStatusDto)
    }

    /**
     * 根据 [customerDispatcherDto] 用户的接待组信息等 分配机器人会话
     */
    fun getBot(customerDispatcherDto: Mono<CustomerDispatcherDto>): Mono<ConversationStatusDto> {
        return assignment(customerDispatcherDto) { messageService.findIdleBotStaff(it.organizationId, it.shuntId) }
    }

    /**
     * 根据 [customerDispatcherDto] 用户的接待组信息等 分配人工会话
     */
    fun getStaff(customerDispatcherDto: Mono<CustomerDispatcherDto>): Mono<ConversationStatusDto> {
        return assignment(customerDispatcherDto) { messageService.findIdleStaff(it.organizationId, it.shuntId) }
    }

    /**
     * 把机构 [customerDispatcherDto] 对应的 客户 放入列队里面
     */
    fun pushIntoQueue(customerDispatcherDto: Mono<CustomerDispatcherDto>): Mono<ConversationViewDto> {
        // staff 方法获取客服为空时 进行排队
        return customerDispatcherDto
            .flatMap {
                // 客户 插入到 redis 列队
                hashOps.put(
                    "queue:${it.shuntId}",
                    it.userId.toString(),
                    UserQueue(it.organizationId, it.shuntId, it.userId).toJson()
                ).flatMap { _ -> Mono.zip(hashOps.size("queue:${it.shuntId}"), it.toMono()) }
            }
            .map { ConversationViewDto(it.t2.organizationId, it.t2.userId, it.t2.shuntId, it.t1) }
    }

    fun cr


        var cipherblock = "";
        var aeskey = my.generateAESKey();
        try
        {
            var publickey = my.publicKeyFromString(publickeystring);
            cipherblock += my.b16to64(publickey.encrypt(my.bytes2string(aeskey))) + "?";
        }
        catch(err)
        {
            return {status: "Invalid public key"};
        }
        if(signingkey)
        {
            signString = cryptico.b16to64(signingkey.signString(plaintext, "sha256"));
            plaintext += "::52cee64bb3a38f6403386519a39ac91c::";
            plaintext += cryptico.publicKeyString(signingkey);
            plaintext += "::52cee64bb3a38f6403386519a39ac91c::";
            plaintext += signString;
        }
        cipherblock += my.encryptAESCBC(plaintext, aeskey);
        return {status: "success", cipher: cipherblock};
    }

    my.decrypt = function(ciphertext, key)
    {
        var cipherblock = ciphertext.split("?");
        var aeskey = key.decrypt(my.b64to16(cipherblock[0]));
        if(aeskey == null)
        {
            return {status: "failure"};
        }
        aeskey = my.string2bytes(aeskey);
        var plaintext = my.decryptAESCBC(cipherblock[1], aeskey).split("::52cee64bb3a38f6403386519a39ac91c::");
        if(plaintext.length == 3)
        {
            var publickey = my.publicKeyFromString(plaintext[1]);
            var signature = my.b64to16(plaintext[2]);
            if(publickey.verifyString(plaintext[0], signature))
            {
                return {status: "success",
                        plaintext: plaintext[0],
                        signature: "verified",
                        publicKeyString: my.publicKeyString(publickey)};
            }
            else
            {
                return {status: "success",
                        plaintext: plaintext[0],
                        signature: "forged",
                        publicKeyString: my.publicKeyString(publickey)};
            }
        }
        else
        {
            return {status: "success", plaintext: plaintext[0], signature: "unsigned"};
        }
    }

    return my;

}());

/**
*
*  Secure Hash Algorithm (SHA256)
*  http://www.webtoolkit.info/
*
*  Original code by Angel Marin, Paul Johnston.
*
**/

function SHA256(s){

	var chrsz   = 8;
	var hexcase = 0;

	func


using System;
using System.Collections.Generic;
using System.Linq;

namespace CurlUnity
{
    public class CurlMulti : IDisposable
    {
        public delegate void MultiPerformCallback(CURLE result, CurlMulti multi);

        private IntPtr multiPtr;
        private CurlShare share;
        private Dictionary<IntPtr, CurlEasy> workingEasies = new Dictionary<IntPtr, CurlEasy>();

        public CurlMulti(IntPtr ptr = default)
        {
            if (ptr != IntPtr.Zero)
            {
                multiPtr = ptr;
            }
            else
            {
                multiPtr = Lib.curl_multi_init();
            }

            Lib.curl_multi_setopt_int(multiPtr, CURLMOPT.PIPELINING, (long)CURLPIPE.MULTIPLEX);

            share = new CurlShare();
            share.SetOpt(CURLSHOPT.SHARE, (long)CURLLOCKDATA.SSL_SESSION);
        }

        internal void CleanUp()
        {
            if (multiPtr != IntPtr.Zero)
            {
                if (CurlMultiUpdater.Instance != null) CurlMultiUpdater.Instance.RemoveMulti(this);
                Lib.curl_multi_cleanup(multiPtr);
                multiPtr = IntPtr.Zero;
            }
        }

        public void Dispose()
        {
            Abort();
        }

        public void Abort()
        {
            if (multiPtr != IntPtr.Zero)
            {
                CurlEasy[] easies = null;

                lock (this)
                {
                    easies = workingEasies.Values.ToArray();
                }

                foreach (var easy in easies)
                {
                    easy.Abort();
                }

                CleanUp();
            }
        }

        internal void AddEasy(CurlEasy easy)
        {
            Lib.curl_multi_add_handle(multiPtr, (IntPtr)easy);
            easy.SetOpt(CURLOPT.SHARE, (IntPtr)share);

            int workingCount = 0;

            lock (this)
            {
                workingEasies[(IntPtr)easy] = easy;
                workingCount = workingEasies.Count;
            }

            if (workingCount == 1 && CurlMultiUpdater.Instance != null)
            {


"18: Select baseband controller SPI_CSN as source"]
    RF_SPI_CSN_SRC_BB_SPI_CSN = 18,
}
impl From<CSN_A> for u8 {
    #[inline(always)]
    fn from(variant: CSN_A) -> Self {
        variant as _
    }
}
#[doc = "Reader of field `CSN`"]
pub type CSN_R = crate::R<u8, CSN_A>;
impl CSN_R {
    #[doc = r"Get enumerated values variant"]
    #[inline(always)]
    pub fn variant(&self) -> crate::Variant<u8, CSN_A> {
        use crate::Variant::*;
        match self.bits {
            0 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_0),
            1 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_1),
            2 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_2),
            3 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_3),
            4 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_4),
            5 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_5),
            6 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_6),
            7 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_7),
            8 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_8),
            9 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_9),
            10 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_10),
            11 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_11),
            12 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_12),
            13 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_13),
            14 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_14),
            15 => Val(CSN_A::RF_SPI_CSN_SRC_DIO_15),
            16 => Val(CSN_A::RF_SPI_CSN_SRC_CONST_LOW),
            17 => Val(CSN_A::RF_SPI_CSN_SRC_CONST_HIGH),
            18 => Val(CSN_A::RF_SPI_CSN_SRC_BB_SPI_CSN),
            i => Res(i),
        }
    }
    #[doc = "Checks if the value of the field is `RF_SPI_CSN_SRC_DIO_0`"]
    #[inline(always)]
    pub fn is_rf_spi_csn_src_dio_0(&self) -> bool {
        *self == CSN_A::RF_SPI_CSN_SRC_DIO_0
    }
    #[doc = "Checks if the value of the field is `RF_SPI_CSN_SRC_DIO_1`"]
    #[inline(always)]
    pub fn is_rf_spi_csn_src_dio_1(&self) -> bool {
        *self == CSN_A::RF_SPI_CSN_SRC_DIO_1
    }
    #[doc = "Checks if the value of the field is `RF_SPI_CSN_SRC_DIO_2`"]
    #[inline(always)]
    pub fn is_rf_spi_csn_src_dio_2(&self) -> bool {
        *self == CSN_A::RF_SPI_CSN_SRC_DIO_2
    }
    #[doc = "Checks if the value of the field is `RF_SPI_CSN_SRC_DIO_3`"]
    #[inline(


       assertDoesNotThrow(() -> {
            this.conn.prepareCall("{call #{call}\n Proc2(?, ?) }");
        });
        assertDoesNotThrow(() -> {
            this.stmt.executeQuery("select {fn/*Comment*/ abs(-1.5) }");
        });
        assertDoesNotThrow(() -> {
            this.stmt.executeQuery("select {fn#Comment\n abs(-1.5) }");
        });
        assertDoesNotThrow(() -> {
            this.stmt.executeQuery("select {fn-- Comment\n abs(-1.5) }");
        });
        Assertions.assertThrows(SQLException.class, () -> {
            this.stmt.executeQuery("select {fn--Comment abs(-1.5) }");
        });
        Assertions.assertThrows(SQLException.class, () -> {
            this.stmt.executeQuery("select {fn#Co\nmment abs(-1.5) }");
        });
        Assertions.assertThrows(SQLException.class, () -> {
            this.stmt.executeQuery("select {fn/*Comment abs(-1.5) }");
        });
    }

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

package org.axonframework.deadline.quartz;

import org.axonframework.common.transaction.TransactionManager;
import org.axonframework.deadline.DeadlineManagerSpanFactory;
import org.axonframework.deadline.DeadlineMessage;
import org.axonframework.deadline.GenericDeadlineMessage;
import org.axonframework.messaging.ExecutionException;
import org.axonframework.messaging.Message;
import org.axonframework.messaging.MessageHandlerInterceptor;
import org.axonframework.messaging.MessageType;
import org.axonframework.messaging.Metadata;
import org.axonframework.messaging.ScopeAware;
import org.axonframework.messaging.ScopeAwareProvider;
import org.axonframework.messaging.ScopeDescriptor;
import org.axonframework.messaging.unitofwork.ProcessingContext;
import org.axonframework.serialization.SerializedObject;
import org.axonframework.serialization.Serializer;
import org.axonframework.serialization.SimpleSerializedObject;
import org.axonframework.tracing.Span;
import org.axonframework.tracing.SpanScope;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

import static org.axonframework.deadline.quartz.DeadlineJob.DeadlineJobDataBinder.deadlineMessage;
import static org.axonframework.deadline.quartz.DeadlineJob.DeadlineJobDataBinder.deadlineScope;

/**
 * Quartz job which depicts handling of a scheduled deadline message. The {@link DeadlineMessage} and
 * {@link ScopeDescriptor} are retrieved from the {@link JobExecutionContext}. The {@link TransactionManager} and
 * {@link ScopeAware} components are fet


ENDING",
            "RUNNING",
            "STOPPED",
            "STOPPING",
        ]
    }
}
impl AsRef<str> for Status {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}
<reponame>snoopy3476/eth-blockies-rs
//! A lightweight library to get Ethereum blockies raw data,
//! which can be used for creating blockies icon images, printing to terminal, etc.
//!
//! Useful when getting raw data of Ethereum blockies, not a full image file.
//!
//! * Rust implementation of following JavaScript package: <https://www.npmjs.com/package/ethereum-blockies-base64>
//!
//!
//! # Example
//!
//! * For all functions, each address argument for Ethereum (`eth_addr`) should be all lowercase, with leading '`0x`'.
//!   This can be done with [`addr_canonicalize`](eth_addr::EthAddr::addr_canonicalize).
//! ```
//! use eth_blockies::*;
//!
//! // "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC"
//! // -> "0xe686c14ff9c11038f2b1c9ad617f2346cfb817dc"
//! let addr =
//!     "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC".to_owned()
//!     .addr_canonicalize();
//! assert_eq!(addr, "0xe686c14ff9c11038f2b1c9ad617f2346cfb817dc");
//!
//! let blockies_data = eth_blockies_data(addr);
//! ```
//!
//! * Get a raw blockies data
//! ```
//! use eth_blockies::*;
//!
//! let addr = "0xe686c14FF9C11038F2B1c9aD<KEY>"
//!      .addr_canonicalize();
//!
//!
//! // get 2D array of (r, g, b)
//! {
//!     let blockies_data_rgb = eth_blockies_data(&addr);
//! }
//!
//!
//! // get 2D array of grayscale
//! {
//!     fn rgb_to_grayscale((r, g, b): RgbPixel) -> u8 {
//!         (r as f64 * 0.299 + g as f64 * 0.587 + b as f64 * 0.114)
//!             as u8
//!     }
//!
//!     let blockies_data_grayscale =
//!         eth_blockies_data_mapped(&addr, rgb_to_grayscale);
//! }
//!
//!
//! // get (color palette, palette index of each pixel)
//! {
//!     let (color_palette, palette_idx_bitmap) =
//!         eth_blockies_indexed_data(&addr);
//! }
//! ```
//!
//!
//!
//! * Write a generated blockies to png file `text.png`,
//!   on Rust binary/library target
//! ```
//! use eth_blockies::*;
//!
//! let addr = "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC"
//!      .addr_canonicalize();
//! let dimension = (128, 128);
//! let img_png_data = eth_blockies_png_data(addr, dimension);
//!
//! use std::io::Write;
//! std::fs::File::create("test.png").unwrap()
//!     .write_all(&img_png_data);
//! ```
//!
//!

#![no_std]
extern crate alloc;
use alloc::vec::Vec;

mod colorclass;
pub use colorclass::{ColorClass, ColorClassArrayMap};
mod eth_addr;
pub use eth_addr::EthAddr;
mod indexed_png;
use indexed_png::*;

/// Unit RGB pixel data
pub type RgbPixel = (u8, u8, u8);

/// Dimension of Ethereum blockies data
const BLOCKIES_SIZE: usize = 8;

/// E


	}finally{
			try{
				data.close();
			}catch(Exception eClose){}
			if(dataMsg!=null){
				try{
					dataMsg.close();
				}catch(Exception eClose){}
			}
		}
	}

	/**
	 * Test SSLtoBASIC
	 **/
	Repository repositoryLetturaCredenzialeSSLtoBASIC_PA=new Repository();
	Date dataLetturaCredenzialeSSLtoBASIC_PA = null;
	@Test(groups={CostantiConnettori.ID_GRUPPO_CONNETTORI,LetturaCredenzialiIngresso.ID_GRUPPO,LetturaCredenzialiIngresso.ID_GRUPPO+".LETTURA_CREDENZIALI_SSLtoBASIC_PA"})
	public void testLetturaCredenzialeSSLtoBASIC_PA() throws TestSuiteException, Exception{

		this.dataLetturaCredenzialeSSLtoBASIC_PA = new Date();

		DatabaseComponent dbComponentErogatore = null;
		try{

			String egov=UtilitiesEGov.getIDEGov(CostantiTestSuite.SPCOOP_NOME_SOGGETTO_FRUITORE,
					CostantiTestSuite.SPCOOP_NOME_SOGGETTO_FRUITORE+CostantiTestSuite.SPCOOP_PORTA_DOMINIO);
			this.repositoryLetturaCredenzialeSSLtoBASIC_PA.add(egov);
			String bustaSOAP=UtilitiesEGov.getBustaEGov(CostantiTestSuite.SPCOOP_TIPO_SOGGETTO_FRUITORE,
					CostantiTestSuite.SPCOOP_NOME_SOGGETTO_FRUITORE,
					CostantiTestSuite.SPCOOP_TIPO_SOGGETTO_EROGATORE,
					CostantiTestSuite.SPCOOP_NOME_SOGGETTO_EROGATORE,
					SPCoopCostanti.PROFILO_COLLABORAZIONE_ONEWAY,
					CostantiTestSuite.SPCOOP_TIPO_SERVIZIO_ONEWAY,
					CostantiTestSuite.SPCOOP_NOME_SERVIZIO_ONEWAY,
					egov,
					false,
					SPCoopCostanti.PROFILO_TRASMISSIONE_CON_DUPLICATI,
					false,null);

			java.io.ByteArrayInputStream bin =
				new java.io.ByteArrayInputStream(bustaSOAP.getBytes());
			Message msg=new Message(bin);
			msg.getSOAPPartAsBytes();

			// Contesto SSL
			java.util.Map<String, String> sslContext = null;
			sslContext = new HashMap<>();
			sslContext.put("trustStoreLocation", "/etc/govway/keys/sil1.jks");
			sslContext.put("keyStoreLocation", "/etc/govway/keys/sil1.jks");
			sslContext.put("trustStorePassword", "openspcoopjks");
			sslContext.put("keyStorePassword", "openspcoopjks");
			sslContext.put("keyPassword", "openspcoop");
			sslContext.put("hostnameVerifier", "false");

			ClientHttpGenerico client=new ClientHttpGenerico(this.repositoryLetturaCredenzialeSSLtoBASIC_PA,sslContext);
			client.setSoapAction("\"TEST\"");
			client.setUrlPortaDiDominio(Utilities.testSuiteProperties.getServizioRicezioneBusteErogatore_httpsConAutenticazioneClient());
			client.connectToSoapEngine();
			client.setProperty(GestoreCredenzialiTest.TEST_CREDENZIALI_BASIC_USERNAME, "adminSilY");
			client.setProperty(GestoreCredenzialiTest.TEST_CREDENZIALI_BASIC_PASSWORD, "123456");
			client.setMessage(msg);
			client.setRispostaDaGestire(true);

			// AttesaTerminazioneMessaggi
			if(Utilities.testSuiteProperties


'\u0cef',  // Negative
            '-'
        )
    }
}/*
 *  This file is part of AndroidIDE.
 *
 *  AndroidIDE is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AndroidIDE is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *   along with AndroidIDE.  If not, see <https://www.gnu.org/licenses/>.
 */

package com.itsaky.androidide.editor.language.newline

import io.github.rosemoe.sora.lang.smartEnter.NewlineHandler
import io.github.rosemoe.sora.lang.styling.Styles
import io.github.rosemoe.sora.lang.styling.StylesUtils
import io.github.rosemoe.sora.text.CharPosition
import io.github.rosemoe.sora.text.Content
import kotlin.math.max
import kotlin.math.min

/**
 * Base class for new line handler implementations.
 *
 * @author Akash Yadav
 */
abstract class BaseNewlineHandler : NewlineHandler {

  protected val openingBrackets = mutableListOf<String>()
  protected val closingBrackets = mutableListOf<String>()

  override fun matchesRequirement(text: Content, position: CharPosition, style: Styles?): Boolean {
    val line = text.getLine(position.line)
    return !StylesUtils.checkNoCompletion(style, position) &&
      (getNonEmptyTextBefore(line, position.column, 1) in openingBrackets) &&
      (getNonEmptyTextAfter(line, position.column, 1) in closingBrackets)
  }

  @Suppress("SameParameterValue")
  protected open fun getNonEmptyTextBefore(text: CharSequence, index: Int, length: Int): String {
    var idx = index
    while (idx > 0 && Character.isWhitespace(text[idx - 1])) {
      idx--
    }
    return text.subSequence(max(0, idx - length), idx).toString()
  }

  @Suppress("SameParameterValue")
  protected open fun getNonEmptyTextAfter(text: CharSequence, index: Int, length: Int): String {
    var idx = index
    while (idx < text.length && Character.isWhitespace(text[idx])) {
      idx++
    }
    return text.subSequence(idx, min(idx + length, text.length)).toString()
  }
}/*
 *  This file is part of AndroidIDE.
 *
 *  AndroidIDE is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AndroidIDE is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *   along with AndroidIDE.  If not, see <https://www.gnu.org/licenses/>.
 */

package com.itsaky.androidide.editor.language.treesitter

import com.itsaky.androidide.editor.language.treesitter.internal.TSLanguageRegistryImpl

/**
 * Registry for managing [TreeSitterLanguage factories][TreeSitterLanguage.Factory].
 *
 * @author Akash Yadav
 */
interface TSLanguageRegistry {

  companion object {

    @JvmStatic
    val instance by lazy { TSLanguageRegistryImpl() }
  }

  /**
   * Registers the given [factory] for the given file types.
   *
   * @param fileType The fil


Gamma);
    idx = k.set(idx, nbins);

    return k.run(2, globalThreads, localThreads, false);
}

static bool ocl_computeGradient(InputArray img, UMat grad, UMat qangle, int nbins, Size effect_size, bool gamma_correction, bool signedGradient)
{
    float angleScale = signedGradient ? (float)(nbins/(2.0*CV_PI)) : (float)(nbins/CV_PI);

    return ocl_compute_gradients_8UC1(effect_size.height, effect_size.width, img,
         angleScale, grad, qangle, gamma_correction, nbins);
}

#define CELL_WIDTH 8
#define CELL_HEIGHT 8
#define CELLS_PER_BLOCK_X 2
#define CELLS_PER_BLOCK_Y 2

static bool ocl_compute_hists(int nbins, int block_stride_x, int block_stride_y, int height, int width,
                              UMat grad, UMat qangle, UMat gauss_w_lut, UMat block_hists, size_t block_hist_size)
{
    ocl::Kernel k("compute_hists_lut_kernel", ocl::objdetect::objdetect_hog_oclsrc);
    if(k.empty())
        return false;

    int img_block_width = (width - CELLS_PER_BLOCK_X * CELL_WIDTH + block_stride_x)/block_stride_x;
    int img_block_height = (height - CELLS_PER_BLOCK_Y * CELL_HEIGHT + block_stride_y)/block_stride_y;
    int blocks_total = img_block_width * img_block_height;

    int qangle_elem_size = CV_ELEM_SIZE1(qangle.type());
    int grad_quadstep = (int)grad.step >> 2;
    int qangle_step = (int)qangle.step / qangle_elem_size;

    int blocks_in_group = 4;
    size_t localThreads[3] = { (size_t)blocks_in_group * 24, 2, 1 };
    size_t globalThreads[3] = {((img_block_width * img_block_height + blocks_in_group - 1)/blocks_in_group) * localThreads[0], 2, 1 };

    int hists_size = (nbins * CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y * 12) * sizeof(float);
    int final_hists_size = (nbins * CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y) * sizeof(float);

    int smem = (hists_size + final_hists_size) * blocks_in_group;

    int idx = 0;
    idx = k.set(idx, block_stride_x);
    idx = k.set(idx, block_stride_y);
    idx = k.set(idx, nbins);
    idx = k.set(idx, (int)block_hist_size);
    idx = k.set(idx, img_block_width);
    idx = k.set(idx, blocks_in_group);
    idx = k.set(idx, blocks_total);
    idx = k.set(idx, grad_quadstep);
    idx = k.set(idx, qangle_step);
    idx = k.set(idx, ocl::KernelArg::PtrReadOnly(grad));
    idx = k.set(idx, ocl::KernelArg::PtrReadOnly(qangle));
    idx = k.set(idx, ocl::KernelArg::PtrReadOnly(gauss_w_lut));
    idx = k.set(idx, ocl::KernelArg::PtrWriteOnly(block_hists));
    idx = k.set(idx, (void*)NULL, (size_t)smem);

    return k.run(2, globalThreads, localThreads, false);
}

static int power_2up(unsigned int n)


///                             break;
    ///                     }
    ///                 }
    ///             }
    ///         }
    ///     }
    /// }
    ///
    /// </example>
    public delegate void ProcessTask(ITask task);

    ///
    /// This delegate is implemented to start a Manual Task
    ///
    /// <remarks>
    /// Use of the bpmn:extension element to add additional components to the Task is recommended in order to implement your own piece of functionality used in handling of a Task.
    /// </remarks>
    /// <param name="task">The Task being started</param>
    /// <example>
    /// <![CDATA[
    /// XML:
    /// <bpmn:manualTask id="ManualTask_0ikjhwl">
    ///  <bpmn:extensionElements>
    ///    <Question prompt="What is the answer to the life, universe and everything" answer_property="answer"/>
    ///  </bpmn:extensionElements>
    ///  <bpmn:outgoing>SequenceFlow_1kh3jxa</bpmn:outgoing>
    /// </bpmn:startEvent>
    /// ]]>
    ///
    /// public void _ProcessManualTask(IManualTask task)
    ///     if (task.ExtensionElement != null){
    ///         foreach (XmlNode xn in task.ExtensionElement.SubNodes){
    ///             if (xn.NodeType == XmlNodeType.Element)
    ///             {
    ///                 if (xn.Name=="Question"){
    ///                     Console.WriteLine(string.format("{0}?",xn.Attributes["prompt"].Value));
    ///                     task.Variables[xn.Attributes["answer_property"].Value] = Console.ReadLine();
    ///                 }
    ///             }
    ///         }
    ///     }
    ///     task.MarkComplete();
    /// }
    ///
    /// </example>
    public delegate void StartManualTask(IManualTask task);
    ///
    /// This delegate is implemented to start a User Task
    ///
    /// <remarks>
    /// Use of the bpmn:extension element to add additional components to the Task is recommended in order to implement your own piece of functionality used in handling of a Task.
    /// </remarks>
    /// <param name="task">The Task being started</param>
    /// <example>
    /// <![CDATA[
    /// XML:
    /// <bpmn:userTask id="UserTask_0ikjhwl">
    ///  <bpmn:extensionElements>
    ///    <Question prompt="What is the answer to the life, universe and everything" answer_property="answer"/>
    ///  </bpmn:extensionElements>
    ///  <bpmn:outgoing>SequenceFlow_1kh3jxa</bpmn:outgoing>
    /// </bpmn:startEvent>
    /// ]]>
    ///
    /// public void _ProcessUserTask(IUserTask task)
    ///     if (task.ExtensionElement != null){
    ///         foreach (XmlNode xn in task.ExtensionElement.SubNodes){
    ///             if (xn.NodeType == XmlNodeType.Element)


 skip_serializing_if = "Option::is_none")]
    pub channel_type: Option<Box<crate::model::ChannelType>>,
    /// The audio.
    #[serde(rename = "Audio", skip_serializing_if = "Option::is_none")]
    pub audio: Option<Box<crate::model::ProgramAudio>>,
    /// A value indicating whether this instance is movie.
    #[serde(rename = "IsMovie", skip_serializing_if = "Option::is_none")]
    pub is_movie: Option<bool>,
    /// A value indicating whether this instance is sports.
    #[serde(rename = "IsSports", skip_serializing_if = "Option::is_none")]
    pub is_sports: Option<bool>,
    /// A value indicating whether this instance is series.
    #[serde(rename = "IsSeries", skip_serializing_if = "Option::is_none")]
    pub is_series: Option<bool>,
    /// A value indicating whether this instance is live.
    #[serde(rename = "IsLive", skip_serializing_if = "Option::is_none")]
    pub is_live: Option<bool>,
    /// A value indicating whether this instance is news.
    #[serde(rename = "IsNews", skip_serializing_if = "Option::is_none")]
    pub is_news: Option<bool>,
    /// A value indicating whether this instance is kids.
    #[serde(rename = "IsKids", skip_serializing_if = "Option::is_none")]
    pub is_kids: Option<bool>,
    /// A value indicating whether this instance is premiere.
    #[serde(rename = "IsPremiere", skip_serializing_if = "Option::is_none")]
    pub is_premiere: Option<bool>,
    /// The timer identifier.
    #[serde(rename = "TimerId", skip_serializing_if = "Option::is_none")]
    pub timer_id: Option<String>,
    /// The current program.
    #[serde(rename = "CurrentProgram", skip_serializing_if = "Option::is_none")]
    pub current_program: Option<Box<crate::model::BaseItemDto>>,
}
<gh_stars>0
const INPUT: &str = include_str!("../input/day17.txt");

#[derive(Debug)]
struct Parsed {
    left: i64,
    right: i64,
    up: i64,
    down: i64,
}

type Point = (i64, i64);
type Velocity = (i64, i64);

impl Parsed {
    fn from_input(input: &str) -> Self {
        let val_str = input.trim_end().split_once(": ").unwrap().1;
        let (x_str, y_str) = val_str.split_once(", ").unwrap();
        let (xa, xb) = x_str[2..].split_once("..").unwrap();
        let (ya, yb) = y_str[2..].split_once("..").unwrap();
        let left = xa.parse().unwrap();
        let right = xb.parse().unwrap();
        let up = yb.parse().unwrap();
        let down = ya.parse().unwrap();
        debug_assert!(left < right);
        debug_assert!(up > down);

        Self {
            left,
            right,
            up,
            down,
        }
    }
    fn contains(&self, pt: &Point) -> bool {
        self.left <= pt.0 && pt.0 <= self.right && pt.1 <= self.up && pt.1 >= self.down
    }
}

fn simulate_point(initial_velocity: Velocity, bounds: &Parsed) -> Option<i64> {
    let mut point = (0, 0);
    let mut velocity = initial_velocity;
    let mut y_max = point.1;

    // terminate if point has overshot bounds
    while point.0 <= bounds.right && point


00'] = '甘肃省庆阳市';
	areaArray['621001'] = '甘肃省庆阳市';
	areaArray['621002'] = '甘肃省庆阳市西峰区';
	areaArray['621021'] = '甘肃省庆阳市庆城县';
	areaArray['621022'] = '甘肃省庆阳市环县';
	areaArray['621023'] = '甘肃省庆阳市华池县';
	areaArray['621024'] = '甘肃省庆阳市合水县';
	areaArray['621025'] = '甘肃省庆阳市正宁县';
	areaArray['621026'] = '甘肃省庆阳市宁县';
	areaArray['621027'] = '甘肃省庆阳市镇原县';
	areaArray['621100'] = '甘肃省定西市';
	areaArray['621101'] = '甘肃省定西市';
	areaArray['621102'] = '甘肃省定西市安定区';
	areaArray['621121'] = '甘肃省定西市通渭县';
	areaArray['621122'] = '甘肃省定西市陇西县';
	areaArray['621123'] = '甘肃省定西市渭源县';
	areaArray['621124'] = '甘肃省定西市临洮县';
	areaArray['621125'] = '甘肃省定西市漳县';
	areaArray['621126'] = '甘肃省定西市岷县';
	areaArray['621200'] = '甘肃省陇南市';
	areaArray['621201'] = '甘肃省陇南市';
	areaArray['621202'] = '甘肃省陇南市武都区';
	areaArray['621221'] = '甘肃省陇南市成县';
	areaArray['653000'] = '新疆维吾尔自治区克孜勒苏柯尔克孜自治州';
	areaArray['653001'] = '新疆维吾尔自治区克孜勒苏柯尔克孜自治州阿图什市';
	areaArray['653022'] = '新疆维吾尔自治区克孜勒苏柯尔克孜自治州阿克陶县';
	areaArray['653023'] = '新疆维吾尔自治区克孜勒苏柯尔克孜自治州阿合奇县';
	areaArray['659003'] = '新疆维吾尔自治区图木舒克市';
	areaArray['659004'] = '新疆维吾尔自治区五家渠市';
	areaArray['710000'] = '台湾省';
	areaArray['810000'] = '香港特别行政区';
	areaArray['820000'] = '澳门特别行政区';
	areaArray['A00000'] = '亚洲';
	areaArray['B00000'] = '非洲';
	areaArray['C00000'] = '欧洲';
	areaArray['


OuTG4zCUXTvGMIwyoWroSgxqwpoagAKsk1ApBibMHmfYsXQP6j7pJJqQSiaT5MFVibldDdRwKVQ/640?wx_fmt=jpeg "")

图 3.2
### 3.3 越权访问测试实践

水平越权测试：首先确定所有测试接口，以万家 APP 中订单详情接口测试为例，抓包得到接口入参为：

{"from":"","orderId":"239703099155","sdkClient":"plugin_apple","appName":"apollo","isPublish":"","apolloId":"ca3d","apolloSecret":"7157","wjPin":"ceshibu3"}

分析入参：由于入参中存在 orderId 和 wjPin 两个字段来标识用户身份，因此修改其为其他同级别权限用户信息，进行水平越权测试。修改前和修改后的请求及返回结果如图 3.3 所示，令当前登录用户为 A 用户，修改请求入参的用户信息为 B 用户，可以发现，修改入参后，A 用户依然可以访问到 B 用户的订单详情，也就是当前登录用户可以访问到其他用户的订单详情，说明该接口存在水平越权逻辑漏洞。

![](https://mmbiz.qpic.cn/sz_mmbiz_jpg/3ZX4O1QxGtOiboxOuTG4zCUXTvGMIwyoWXSdIEAWFguticicFkl07JfepCIicm8WW8Ce2wyEK2AwiagSY5NjDmJVgeQ/640?wx_fmt=jpeg "")

图 3.3

垂直越权测试：在万家 APP 业务中，店主的权限高于店员的权限，因此需要进行垂直越权测试来验证店主的信息是否存在泄漏风险。

首先确定店主比店员多的具体权限，需要具体到每个接口。然后使用店主权限登录万家 APP，找到只有店主权限才能看到的应用，进行请求、抓包、分析参数、修改参数、重新请求的测试过程。其中，修改参数指将店主身份的 cookie 修改为店员身份的 cookie，如图 3.4 所示，重新请求后可以正常返回结果，说明该接口存在垂直越权逻辑漏洞。

![](https://mmbiz.qpic.cn/sz_mmbiz_jpg/3ZX4O1QxGtOiboxOuTG4zCUXTvGMIwyoW9tlc237e788XvHz2ueicCOqceLp7SOdoMV9ibapjgiciaSv8vcm1rXrYkA/640?wx_fmt=jpeg "")


家。我還是……

長老：說什麼話，你是羽裳的丈夫，就是我們的族人。

長老：今晚是大家光顧著慶祝，才讓毒蛛鑽了空子，跑到了村裡來。

姜雲凡：長老，你們經常被怪物攻擊嗎？

長老：這……唉……

長老：幾位尊貴的客人，感謝你們幫忙除去毒蛛。只是這隻能找到這兒來，就怕還會有更多的蠱獸跟來。

長老：本來想請客人多住幾天，現在還是請幾位明早就離開。

小蠻：嘿！我知道啦！

龍幽：怎麼了？！

小蠻：本姑娘知道這毒蛛身上的蠱術氣息是怎麼一回事了～

長老：小姑娘，你也懂得蠱術？

小蠻：嗯！它是被蠱術操縱，追著大哥哥的氣息來的。

祝有涯：……

小蠻：？？

唐雨柔：抱歉，如果小蠻說錯了什麼……

祝有涯：小姑娘說的一點沒錯。

祝有涯：……其實，這毒蛛……是我娘派出來找我的。

龍幽：你娘？

祝有涯：嗯。娘她……

羽裳：涯哥……

羽裳：婆婆……不喜歡涯哥和我在一起……涯哥帶我回村子來，婆婆不高興，就讓它們來找我們。

祝有涯：娘只有我這麼一個兒子，爹又死的早……再加上羽裳不是普通人……

祝有涯：娘太擔心我了。

龍幽：託辭。

龍幽：你是她唯一的親人和依靠，就這樣拋下她孤苦伶仃一個人，讓她如何是好。

羽裳：不是涯哥不好，是羽裳不夠好……

祝有涯：……我對不起娘……

祝有涯：可我一定要娶羽裳為妻。

羽裳：等寶寶生下來了，我們就回去跟婆婆道歉。�


   "psrldq $8, %%xmm4                 \n" // 0:e1+f1
         "pslldq $8, %%xmm3                 \n" // e0+f0:0
         "pxor %%xmm4, %%xmm2               \n" // d1:d0+e1+f1
         "pxor %%xmm3, %%xmm1               \n" // c1+e0+f1:c0

         /*
          * Now shift the result one bit to the left,
          * taking advantage of [CLMUL-WP] eq 27 (p. 20)
          */
         "movdqa %%xmm1, %%xmm3             \n" // r1:r0
         "movdqa %%xmm2, %%xmm4             \n" // r3:r2
         "psllq $1, %%xmm1                  \n" // r1<<1:r0<<1
         "psllq $1, %%xmm2                  \n" // r3<<1:r2<<1
         "psrlq $63, %%xmm3                 \n" // r1>>63:r0>>63
         "psrlq $63, %%xmm4                 \n" // r3>>63:r2>>63
         "movdqa %%xmm3, %%xmm5             \n" // r1>>63:r0>>63
         "pslldq $8, %%xmm3                 \n" // r0>>63:0
         "pslldq $8, %%xmm4                 \n" // r2>>63:0
         "psrldq $8, %%xmm5                 \n" // 0:r1>>63
         "por %%xmm3, %%xmm1                \n" // r1<<1|r0>>63:r0<<1
         "por %%xmm4, %%xmm2                \n" // r3<<1|r2>>62:r2<<1
         "por %%xmm5, %%xmm2                \n" // r3<<1|r2>>62:r2<<1|r1>>63

         /*
          * Now reduce modulo the GCM polynomial x^128 + x^7 + x^2 + x + 1
          * using [CLMUL-WP] algorithm 5 (p. 20).
          * Currently xmm2:xmm1 holds x3:x2:x1:x0 (already shifted).
          */
         /* Step 2 (1) */
         "movdqa %%xmm1, %%xmm3             \n" // x1:x0
         "movdqa %%xmm1, %%xmm4             \n" // same
         "movdqa %%xmm1, %%xmm5             \n" // same
         "psllq $63, %%xmm3                 \n" // x1<<63:x0<<63 = stuff:a
         "psllq $62, %%xmm4                 \n" // x1<<62:x0<<62 = stuff:b
         "psllq $57, %%xmm5                 \n" // x1<<57:x0<<57 = stuff:c

         /* Step 2 (2) */
         "pxor %%xmm4, %%xmm3               \n" // stuff:a+b
         "pxor %%xmm5, %%xmm3               \n" // stuff:a+b+c
         "pslldq $8, %%xmm3                 \n" // a+b+c:0
         "pxor %%xmm3, %%xmm1               \n" // x1+a+b+c:x0 = d:x0

         /* Steps 3 and 4 */
         "movdqa %%xmm1,%%xmm0              \n" // d:x0
         "movdqa %%xmm1,%%xmm4              \n" // same
         "movdqa %%xmm1,%%xmm5              \n" // same
         "psrlq $1, %%xmm0                  \n" // e1:x0>>1 = e1


position );
                _owner.navMeshAgent.isStopped = false;

                // set execution time limit
                timeExpectedEnd = time + 5f;
            }
            else
            {
                _owner.navMeshAgent.isStopped = true;

                // set execution time limit
                timeExpectedEnd = time + 1f;
            }
            // todo: play animation, etc.
        }

        public override void OnExit ( SimpletonState next )
        {

        }

        public override void Tick ( float time )
        {
            completed |= _owner.navMeshAgent.remainingDistance<1f;
        }

    }
}


  34: 1, // page down
  37: 1, // left
  38: 1, // up
  39: 1, // right
  40: 1  // down
};

/**
 * Calls all the plugins of the given operation, in sequence, with the
 * given arguments. This is short-circuiting: once one plugin cancels
 * the event, no more plugins will be invoked.
 * @param {goog.editor.Plugin.Op} op A plugin op.
 * @param {...*} var_args The arguments to the plugin.
 * @return {boolean} True if one of the plugins cancel the event, false
 *    otherwise.
 * @private
 */
goog.editor.Field.prototype.invokeShortCircuitingOp_ = function(op, var_args) {
  var plugins = this.indexedPlugins_[op];
  var argList = goog.array.slice(arguments, 1);
  for (var i = 0; i < plugins.length; ++i) {
    // If the plugin returns true, that means it handled the event and
    // we shouldn't propagate to the other plugins.
    var plugin = plugins[i];
    if ((plugin.isEnabled(this) ||
         goog.editor.Plugin.IRREPRESSIBLE_OPS[op]) &&
        plugin[goog.editor.Plugin.OPCODE[op]].apply(plugin, argList)) {
      // Only one plugin is allowed to handle the event. If for some reason
      // a plugin wants to handle it and still allow other plugins to handle
      // it, it shouldn't return true.
      return true;
    }
  }

  return false;
};

/**
 * Invoke this operation on all plugins with the given arguments.
 * @param {goog.editor.Plugin.Op} op A plugin op.
 * @param {...*} var_args The arguments to the plugin.
 * @private
 */
goog.editor.Field.prototype.invokeOp_ = function(op, var_args) {
  var plugins = this.indexedPlugins_[op];
  var argList = goog.array.slice(arguments, 1);
  for (var i = 0; i < plugins.length; ++i) {
    var plugin = plugins[i];
    if (plugin.isEnabled(this) ||
        goog.editor.Plugin.IRREPRESSIBLE_OPS[op]) {
      plugin[goog.editor.Plugin.OPCODE[op]].apply(plugin, argList);
    }
  }
};

/**
 * Reduce this argument over all plugins. The result of each plugin invocation
 * will be passed to the next plugin invocation. See goog.array.reduce.
 * @param {goog.editor.Plugin.Op} op A plugin op.
 * @param {string} arg The argument to reduce. For now, we assume it's a
 *     string, but we should widen this later if there are reducing
 *     plugins that don't operate on strings.
 * @param {...*} var_args Any extra arguments to pass to the plugin. These args
 *     will not be reduced.
 * @return {string} The reduced argument.
 * @private
 */
goog.editor.Field.prototype.reduceOp_ = function(op, arg, var_args) {
  var plugins = this.indexedPlugins_[op];
  var argList = goog.array.slice(arguments, 1);
  for (var i = 0; i < plugins.length; ++i) {
    var plugin = plugins[i];
    if (plugin.isEnabled(this) ||
        goog.editor.Plugin.IRREPRESSIBLE_OPS[op]) {
      argList[0] = plugin[goog.editor.Plugin.OPCODE[op]].apply(
          plugin, argList);
    }
  }
  return argList[0];
};

/**
 * Prepare the given contents, then inject them into the editable field.
 * @param {?string} contents The contents to prepare.
 * @param {Element} field The field element.
 * @protected
 */
goog.editor.Field.prototype.injectContents = function(contents, field) {
  var styles = {};
  var newHtml = this.getInjectableContents(contents, styles);
  goog.style.setStyle(field


index: 88;
    }

  }

  @if $triangle == top {
    margin-left: 0;
    margin-top: -$f-dropdown-margin-bottom;

    &:before {
      @include css-triangle($f-dropdown-triangle-size, $f-dropdown-triangle-color, top);
      bottom: -($f-dropdown-triangle-size * 2);
      position: absolute;
      top: auto;
      #{$default-float}: $f-dropdown-triangle-side-offset;
      #{$opposite-direction}: auto;
      z-index: 89;
    }
    &:after {
      @include css-triangle($f-dropdown-triangle-size + 1, $f-dropdown-border-color, top);
      bottom: -($f-dropdown-triangle-size * 2) - 2;
      position: absolute;
      top: auto;
      #{$default-float}: $f-dropdown-triangle-side-offset - 1;
      #{$opposite-direction}: auto;
      z-index: 88;
    }

  }

  @if $max-width { max-width: $max-width; }
  @else { max-width: $f-dropdown-max-width; }

}

// @MIXIN
//
// We use this to style the list elements or content inside the dropdown.

@mixin dropdown-style {
  cursor: $cursor-pointer-value;
  font-size: $f-dropdown-font-size;
  line-height: $f-dropdown-line-height;
  margin: 0;

  &:hover,
  &:focus { background: $f-dropdown-list-hover-bg; }

  a {
    display: block;
    padding: $f-dropdown-list-padding;
    color: $f-dropdown-font-color;
  }
}

@include exports("dropdown") {
  @if $include-html-dropdown-classes {

    /* Foundation Dropdowns */
    .f-dropdown {
      @include dropdown-container(list, bottom);

      &.drop-#{$opposite-direction} {
        @include dropdown-container(list, #{$default-float});
      }

      &.drop-#{$default-float} {
        @include dropdown-container(list, #{$opposite-direction});
      }

      &.drop-top {
        @include dropdown-container(list, top);
      }
      // max-width: none;

      li { @include dropdown-style; }

      // You can also put custom content in these dropdowns
      &.content { @include dropdown-container(content, $triangle:false); }

      // Radius of Dropdown
      &.radius { @include radius($f-dropdown-radius); }

      // Sizes
      &.tiny    { max-width: 200px; }
      &.small   { max-width: 300px; }
      &.medium  { max-width: 500px; }
      &.large   { max-width: 800px; }
      &.mega    {
        width:100%!important;
        max-width:100%!important;

        &.open{
          left:0!important;
        }
      }
    }

  }
}
//
// A partial implementation of the Ruby display functions from Compass:
// https://github.com/Compass/compass/blob/stable/core/lib/compass/core/sass_extensions/functions/display.rb
//

@function elements-of-type($type){
    @if ($type == block){
        @return address, article, aside, blockquote, center, dir, div, dd, details, dl, dt, fieldset, figcaption, figure, form, footer, frameset, h1, h2, h3, h4, h5, h6, hr, header, hgroup, isindex, main, menu, nav, noframes, noscript, ol, p


 }

  /// setOptLevel - Set the optimization level for the JIT.  This option
  /// defaults to CodeGenOpt::Default.
  EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
    OptLevel = l;
    return *this;
  }

  /// setTargetOptions - Set the target options that the ExecutionEngine
  /// target is using. Defaults to TargetOptions().
  EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
    Options = Opts;
    return *this;
  }

  /// setRelocationModel - Set the relocation model that the ExecutionEngine
  /// target is using. Defaults to target specific default "Reloc::Default".
  EngineBuilder &setRelocationModel(Reloc::Model RM) {
    RelocModel = RM;
    return *this;
  }

  /// setCodeModel - Set the CodeModel that the ExecutionEngine target
  /// data is using. Defaults to target specific default
  /// "CodeModel::JITDefault".
  EngineBuilder &setCodeModel(CodeModel::Model M) {
    CMModel = M;
    return *this;
  }

  /// setMArch - Override the architecture set by the Module's triple.
  EngineBuilder &setMArch(StringRef march) {
    MArch.assign(march.begin(), march.end());
    return *this;
  }

  /// setMCPU - Target a specific cpu type.
  EngineBuilder &setMCPU(StringRef mcpu) {
    MCPU.assign(mcpu.begin(), mcpu.end());
    return *this;
  }

  /// setVerifyModules - Set whether the JIT implementation should verify
  /// IR modules during compilation.
  EngineBuilder &setVerifyModules(bool Verify) {
    VerifyModules = Verify;
    return *this;
  }

  /// setMAttrs - Set cpu-specific attributes.
  template<typename StringSequence>
  EngineBuilder &setMAttrs(const StringSequence &mattrs) {
    MAttrs.clear();
    MAttrs.append(mattrs.begin(), mattrs.end());
    return *this;
  }

  TargetMachine *selectTarget();

  /// selectTarget - Pick a target either via -march or by guessing the native
  /// arch.  Add any CPU features specified via -mcpu or -mattr.
  TargetMachine *selectTarget(const Triple &TargetTriple,
                              StringRef MArch,
                              StringRef MCPU,
                              const SmallVectorImpl<std::string>& MAttrs);

  ExecutionEngine *create() {
    return create(selectTarget());
  }

  ExecutionEngine *create(TargetMachine *TM);
};

// Create wrappers for C Binding types (see CBindingWrapping.h).
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)

} // End llvm namespace

#endif


_flush(void) */

sio_flush:	xorl %ecx,%ecx			# Timeout
		movb $0x80,%ch			#  counter
sio_flush.1:	call sio_ischar 		# Check for character
		jz sio_flush.2			# Till none
		loop sio_flush.1		#  or counter is zero
		movb $1, %al			# Exhausted all tries
sio_flush.2:	ret				# To caller

/* void sio_putc(int c) */

sio_putc:	pushl %eax
		movw $SIO_PRT+0x5,%dx		# Line status reg
		xor %ecx,%ecx			# Timeout
		movb $0x40,%ch			#  counter
sio_putc.1:	inb (%dx),%al			# Transmitter
		testb $0x20,%al 		#  buffer empty?
		loopz sio_putc.1		# No
		jz sio_putc.2			# If timeout
		popl %eax                       # Get the character
		subb $0x5,%dl			# Transmitter hold reg
		outb %al,(%dx)			# Write character
sio_putc.2:	ret				# To caller

/* int sio_getc(void) */

sio_getc:	call sio_ischar 		# Character available?
		jz sio_getc			# No
sio_getc.1:	subb $0x5,%dl			# Receiver buffer reg
		inb (%dx),%al			# Read character
		ret				# To caller

/* int sio_ischar(void) */

sio_ischar:	movw $SIO_PRT+0x5,%dx		# Line status register
		xorl %eax,%eax			# Zero
		inb (%dx),%al			# Received data
		andb $0x1,%al			#  ready?
		ret				# To caller


return ticks ~/ 1000;
  }
}

// Patch for List implementation.
@patch
class List<E> {
  @patch
  factory List([@undefined int? length]) {
    dynamic list;
    if (JS<bool>('!', '# === void 0', length)) {
      list = JS('', '[]');
    } else {
      int _length = JS('!', '#', length);
      if (length == null || _length < 0) {
        throw ArgumentError("Length must be a non-negative integer: $_length");
      }
      list = JS('', 'new Array(#)', _length);
      JS('', '#.fill(null)', list);
      JSArray.markFixedList(list);
    }
    return JSArray<E>.of(list);
  }

  @patch
  factory List.empty({bool growable = false}) {
    var list = JSArray<E>.of(JS('', 'new Array()'));
    if (!growable) JSArray.markFixedList(list);
    return list;
  }

  @patch
  factory List.filled(@nullCheck int length, E fill, {bool growable = false}) {
    var list = JSArray<E>.of(JS('', 'new Array(#)', length));
    JS('', '#.fill(#)', list, fill);
    if (!growable) JSArray.markFixedList(list);
    return list;
  }

  @patch
  factory List.from(Iterable elements, {bool growable = true}) {
    var list = JSArray<E>.of(JS('', '[]'));
    // Specialize the copy loop for the case that doesn't need a
    // runtime check.
    if (elements is Iterable<E>) {
      for (var e in elements) {
        // Unsafe add here to avoid extra casts and growable checks enforced by
        // the exposed add method.
        JS('', '#.push(#)', list, e);
      }
    } else {
      for (var e in elements) {
        // Unsafe add here to avoid extra casts and growable checks enforced by
        // the exposed add method.
        JS('', '#.push(#)', list, e as E);
      }
    }
    if (!growable) JSArray.markFixedList(list);
    return list;
  }

  @patch
  factory List.of(Iterable<E> elements, {bool growable = true}) {
    var list = JSArray<E>.of(JS('', '[]'));
    for (var e in elements) {
      // Unsafe add here to avoid extra casts and growable checks enforced by
      // the exposed add method.
      JS('', '#.push(#)', list, e);
    }
    if (!growable) JSArray.markFixedList(list);
    return list;
  }

  @patch
  factory List.generate(int length, E generator(int index),
      {bool growable = true}) {
    final result = JSArray<E>.of(JS('', 'new Array(#)', length));
    if (!growable) JSArray.markFixedList(result);
    for (int i = 0; i < length; i++) {
      // Unsafe assignment here to avoid extra casts enforced by the exposed
      // []= operator.
      JS('', '#[#] = #', result, i, generator(i));
    }
    return result;
  }

  @patch
  factory List.unmodifiable(Iterable elements) {
    var list = List<E>.from(elements);
    JSArray.markUnmodifiableList(list);
    return list;
  }
}

@patch
class Map<K, V> {
  @patch
  factory Map.unmodifiable(Map<dynamic, dynamic> other) {
    return UnmodifiableMapView<K, V>(Map<K, V>.from(other));
  }

  @patch
  factory Map() = LinkedMap<K, V>;
}

@patch
class String {
  @patch
  factory String.fromCharCodes(Iterable<int> charCodes,
      [int start = 0, int? end]) {
    if (charCodes is JSArray) {
      return _stringFromJSArray(charCodes, start


e;
import org.bukkit.block.data.Ageable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockGrowEvent;

import java.util.List;

/**
 * @author eccentric_nz
 */
public class TARDISGrowthListener implements Listener {

    private final TARDIS plugin;
    private final int chance;
    private final List<Material> plants = List.of(Material.AIR, Material.BEETROOTS, Material.CACTUS, Material.CARROTS, Material.COCOA, Material.WHEAT, Material.MELON_STEM, Material.NETHER_WART, Material.POTATOES, Material.PUMPKIN_STEM, Material.SUGAR_CANE);

    public TARDISGrowthListener(TARDIS plugin) {
        this.plugin = plugin;
        chance = this.plugin.getConfig().getInt("siege.growth");
    }

    @EventHandler(ignoreCancelled = true)
    public void onPlantGrowth(BlockGrowEvent event) {
        Block plant = event.getBlock();
        Material species = plant.getType();
        if (!plants.contains(species)) {
            return;
        }
        Location l = plant.getLocation();
        String w = l.getWorld().getName();
        if (!plugin.getTrackerKeeper().getSiegeGrowthAreas().containsKey(w)) {
            return;
        }
        for (TARDISSiegeArea area : plugin.getTrackerKeeper().getSiegeGrowthAreas().get(w)) {
            if (area.isInSiegeArea(l) && TARDISConstants.RANDOM.nextInt(100) < chance) {
                // grow an extra step
                if (species.isAir()) {
                    // with cactus and sugar cane the block returned is AIR
                    plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> plant.getRelative(BlockFace.UP).setBlockData(plant.getRelative(BlockFace.DOWN).getType().createBlockData()), 3L);
                } else if (plant instanceof Ageable ageable) {
                    // get current level
                    int age = ageable.getAge();
                    switch (species) {
                        case CACTUS, SUGAR_CANE -> {
                            // with cactus and sugar cane the block returned is AIR
                            plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> plant.getRelative(BlockFace.UP).setBlockData(plant.getRelative(BlockFace.DOWN).getType().createBlockData()), 3L);
                        }
                        case BEETROOTS, CARROTS, WHEAT, MELON_STEM, POTATOES, PUMPKIN_STEM -> {
                            // fully grown is 7
                            if (age < 6) {
                                plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> ageable.setAge(age + 2), 3L);
                            }
                        }
                        case COCOA -> {
                            // fully grown is 3
                            if (age < 4 && TARDISConstants.RANDOM.nextInt(100) < 25) {
                                plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> ageable.setAge(age + 8), 3L);
                            }
                        }
                        case NETHER_WART -> {
                            // fully grown is 3
                            if (age < 2 && TARDISConstants.RANDOM.nextInt(100) < 33) {
                                plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> ageable.setAge(age + 2), 3L);
                            }
                        }
                        default -> {
                            // not supported
                            // FROSTED_ICE, TWISTING_VINES, WEEPING_VINES, KELP, CHORUS_FLOWER


 = mOrigBamHashBamWriter.getHashBams();
        Map<Integer, File> newBamHashBams = mNewBamHashBamWriter.getHashBams();
        Set<Integer> hashBamKeys = new HashSet<>(origBamHashBams.keySet());
        hashBamKeys.addAll(newBamHashBams.keySet());

        Map<Integer, Pair<File, File>> hashBamPairs = new HashMap<>();

        for(Integer key : hashBamKeys)
        {
            File origHashBam = origBamHashBams.get(key);
            File newHashBam = newBamHashBams.get(key);

            // should not be null
            if(origHashBam == null || newHashBam == null)
            {
                throw new RuntimeException(String.format("missing hashbams with key: %d", key));
            }

            hashBamPairs.put(key, Pair.of(origHashBam, newHashBam));
        }
        return hashBamPairs;
    }
}
package net.harunote.quiz;

import java.util.Arrays;

/**
 * @Author : CodeVillains
 * @Description : findKim 함수(메소드)는 String형 배열 seoul을 매개변수로 받습니다.
 * seoul의 element중 "Kim"의 위치 x를 찾아, "김서방은 x에 있다"는 String을 반환하시오.
 * seoul에 "Kim"은 오직 한 번만 나타나며 잘못된 값이 입력되는 경우는 없습니다.
 */
public class FindKim {
    public String findKim(String[] seoul){
        //x에 김서방의 위치를 저장하시오.
        /*
        int x = 0;

        for (String str : seoul) {
            if ("Kim".equals(str)) {
                break;
            }
            x++;
        }
        */
        final String find = "Kim";
        int x = Arrays.asList(seoul).indexOf(find);

        return "김서방은 "+ x + "에 있다";
    }

    // 실행을 위한 테스트코드입니다.
    public static void main(String[] args) {
        FindKim kim = new FindKim();
        String[] names = {"Queen", "Tod","Kim"};
        System.out.println(kim.findKim(names));
    }
}package net.harunote.collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @Author : CodeVillains
 * @Description :
 */
public class HashMapDemo {

	public static void main(String args[]) {
		// 해시 맵을 만든다.
		Map<String, Double> hm = new HashMap<String, Double>();
		// 맵에 요소들을 넣는다.
		hm.put("홍길동이", new Double(1240.34));
		hm.put("김영순이", new Double(223.39));
		hm.put("퀵군", new Double(1378.00));
		hm.put("글라이더님", new Double(9999.55));
		hm.put("존 도", new Double(-122.08));
		hm.put("한효주님", null);

		// 맵 엔트리의 콜렉션 집합을 가져온다.
		Set<?> set = hm.entrySet();

		// 반복자를 얻는다.
		Iterator<?> i = set.iterator();

		// 요소들을 출력한다.
		while(i.hasNext()) {
			Map.Entry me = (Map.Entry)i.next();
			System.out.print(me.getKey() + ": ");
			System.out.println(me.getValue());
		}

		// 존 도의 계좌에 1000을 예금한다.
		double bonus = hm.get("존 도").doubleValue();
		hm.put("


LEB">: BFD_RELOC_NDS32_DWARF2_LEB

for dwarf2 debug_line.

: BFD_RELOC_NDS32_UPDATE_TA

for eliminate 16-bit instructions

: BFD_RELOC_NDS32_PLT_GOTREL_LO20

: BFD_RELOC_NDS32_PLT_GOTREL_LO15

: BFD_RELOC_NDS32_PLT_GOTREL_LO19

: BFD_RELOC_NDS32_GOT_LO15

: BFD_RELOC_NDS32_GOT_LO19

: BFD_RELOC_NDS32_GOTOFF_LO15

: BFD_RELOC_NDS32_GOTOFF_LO19

: BFD_RELOC_NDS32_GOT15S2

: BFD_RELOC_NDS32_GOT17S2

for PIC object relaxation

: BFD_RELOC_NDS32_5

NDS32 relocs.
This is a 5 bit absolute address.

: BFD_RELOC_NDS32_10_UPCREL

This is a 10-bit unsigned pc-relative reloc with the right 1 bit assumed to be 0.

: BFD_RELOC_NDS32_SDA_FP7U2_RELA

If fp were omitted, fp can used as another gp.

</dd


  #endregion fields

        #region properties

        /// <summary>
        /// Application's ID.
        /// </summary>
        public string ApplicationId { get; set; }

        /// <summary>
        /// Application's name.
        /// </summary>
        public string ApplicationName { get; set; }

        /// <summary>
        /// Availability of the application to be modified.
        /// </summary>
        public bool IsAvailable { get; set; }

        /// <summary>
        /// Badge counter string used to display.
        /// </summary>
        public string BadgeCounterString
        {
            get => _badgeCounterString;
            set => SetProperty(ref _badgeCounterString, value);
        }

        /// <summary>
        /// Actual badge counter value.
        /// </summary>
        public double BadgeCounter
        {
            get => _badgeCounter;
            set
            {
                if (_badgeCounter != value)
                {
                    _badgeCounter = value;
                    BadgeCounterString = value <= 99 ? value.ToString() : "99+";
                }
            }
        }

        #endregion properties
    }
}


, U+3bc3, U+3bcd, U+3bf0, U+3bf3, U+3c0f, U+3c26, U+3cc3, U+3cd2, U+3d11, U+3d1e, U+3d31, U+3d4e, U+3d64, U+3d9a, U+3dc0, U+3dcc, U+3dd4, U+3e05, U+3e3f-3e40, U+3e60, U+3e66, U+3e68, U+3e83, U+3e8a, U+3e94, U+3eda, U+3f57, U+3f72, U+3f75, U+3f77, U+3fae, U+3fb1, U+3fc9, U+3fd7, U+3fdc, U+4039, U+4058;
}
/* [52] */
@font-face {
  font-family: 'Noto Sans JP';
  font-style: normal;
  font-weight: 300;
  font-display: swap;
  src: url(https://fonts.gstatic.com/s/notosansjp/v40/-F6pfjtqLzI2JPCgQBnw7HFQaioq1xVxjfp_dakBof6Bs-tb3ab2FNISVac.52.woff2) format('woff2');
  unicode-range: U+32b5-332b, U+332d-3394;
}
/* [53] */
@font-face {
  font-family: 'Noto Sans JP';
  font-style: normal;
  font-weight: 300;
  font-display: swap;
  src: url(https://fonts.gstatic.com/s/notosansjp/v40/-F6pfjtqLzI2JPCgQBnw7HFQaioq1xVxjfp_dakBof6Bs-tb3ab2FNISVac.53.woff2) format('woff2');
  unicode-range: U+31c8-31e3, U+31f0-321e, U+3220-3230, U+3232-32b4;
}
/* [54] */
@font-face {
  font-family: 'Noto Sans JP';
  font-style: normal;
  font-weight: 300;
  font-display: swap;
  src: url(https://fonts.gstatic.com/s/notosansjp/v40/-F6pfjtqLzI2JPCgQBnw7HFQaioq1xVxjfp_dakBof6Bs-tb3ab2FNISVac.54.woff2) format('woff2');
  unicode-range: U+3028-303f, U+3094-3096, U+309f-30a0, U+30ee, U+30f7-30fa, U+30ff, U+3105-312f, U+3131-3163, U+3165-318e, U+3190-31bb, U+31c0-31c7;
}
/* [55] */
@font-face {
  font-family: 'Noto Sans JP';
  font-style: normal;
  font-weight: 300;
  font-display: swap;
  src: url(https://fonts.gstatic.com/s/notosansjp/v40/-F6pfjtqLzI2JPCgQBnw7HFQaioq1xVxjfp_dakBof6Bs-tb3ab2FNISVac.55.woff2) format('woff2');
  unicode-range: U+2f14-2fd5, U+2ff0-2ffb, U+3004, U+3013, U+3016-301b, U+301e, U+3020-3027;
}
/* [56] */
@font-face {
  font-fam


 "全法长靴",
[11823] = "渊博褶裙",
[11824] = "巨石指环",
[11825] = "炸弹宠物",
[11826] = "发条娃娃",
[11827] = "结构图：发条娃娃",
[11828] = "结构图：炸弹宠物",
[11829] = "安戈洛灰烬",
[11830] = "精细的双帆龙鳞片",
[11831] = "精细的翼手龙鳞片",
[11832] = "博学坠饰",
[11833] = "格里什皇后诱引剂",
[11834] = "极度粘稠的沥青",
[11835] = "格里什皇后的大脑",
[11837] = "格里什信息素",
[11838] = "Monster - Trident, Flame Wrath",
[11839] = "大石匠的眼镜",
[11840] = "主建筑师的衬衣",
[11841] = "主设计师的长裤",
[11842] = "首席测量员的衬肩",
[11843] = "银行赠券",
[11844] = "匹斯特苏格的安戈洛报告",
[11845] = "手工皮包",
[11846] = "维兹班恩的特殊饮料",
[11847] = "破碎的披风",
[11848] = "粗麻腰带",
[11849] = "锈铁护腕",
[11850] = "夜行蝙蝠斗篷",
[11851] = "食腐狼皮外套",
[11852] = "漂泊者护腿",
[11853] = "流浪之靴",
[11854] = "主动式负载平衡器螺丝刀",
[11855] = "双头扳手",
[11856] = "精灵典礼之刃",
[11857] = "修女魔棒",
[11858] = "征战斗篷",
[11859] = "碧月宝珠",
[11860] = "充能闪电魔棒",
[11861] = "报复束带",
[11862] = "白骨指环",
[11863] = "白骨切割者",
[11864] = "白骨长矛",
[11865] = "怨恨之靴",
[11866] = "娜玛拉的腰带",
[11867] = "狂乱护手",
[11868] = "窒息指环",
[11869] = "沙妮的戒指",
[11870] = "湮灭宝珠",
[11871] = "鲨鱼肩甲",
[11872] = "逃避胫甲",
[11873] = "灵雾斗篷",
[11874] = "云谷衬肩",
[11875] = "冷云护腕",
[11876] = "平原行者外套",
[11882] = "引导者护腿",
[11883] = "肮脏的背包",
[11884] = "月光披肩",


together.
        </xy-tab-content>
        <xy-tab-content label="tab2" disabled>
            A placeholder inside a web
            component that users can fill with their own markup,
            with the effect of composing different DOM trees
            together.
        </xy-tab-content>
        <xy-tab-content label="tab3" key="aaa">
            A placeholder inside a web
            component that users can fill with their own markup,
            with the effect of composing different DOM trees
            together.
        </xy-tab-content>
    </xy-tab>

scrollable

    <xy-tab>
        <xy-tab-content label="tab1">tab1</xy-tab-content>
        <xy-tab-content label="tab2">tab2</xy-tab-content>
        <xy-tab-content label="tab3">tab3</xy-tab-content>
        <xy-tab-content label="tab4">tab4</xy-tab-content>
        <xy-tab-content label="tab5">tab5</xy-tab-content>
        <xy-tab-content label="tab6">tab6</xy-tab-content>
        <xy-tab-content label="tab7">tab7</xy-tab-content>
        <xy-tab-content label="tab8">tab8</xy-tab-content>
        <xy-tab-content label="tab9">tab9</xy-tab-content>
        <xy-tab-content label="tab10">tab10</xy-tab-content>
    </xy-tab>

label with icon

    <xy-tab>
        <xy-tab-content label="home" icon="home">tab1</xy-tab-content>
        <xy-tab-content label="message" icon="message">tab2</xy-tab-content>
        <xy-tab-content label="user" icon="user">tab3</xy-tab-content>
    </xy-tab>

only icon

    <xy-tab>
        <xy-tab-content icon="home">tab1</xy-tab-content>
        <xy-tab-content icon="message">tab2</xy-tab-content>
        <xy-tab-content icon="user">tab3</xy-tab-content>
    </xy-tab>

layout

    <xy-layout class="layout">
        <xy-layout class="header">HEADER</xy-layout>
        <xy-layout row expand>
            <xy-layout class="side"></xy-layout>
            <xy-layout expand center class="main">
                <xy-layout center class="box">xy-layout</xy-layout>
            </xy-layout>
            <xy-layout class="side"></xy-layout>
        </xy-layout>
        <xy-layout class="footer">FOOTER</xy-layout>
    </xy-layout>

grid

    <xy-row gutter="10">
        <xy-col span="8">11</xy-col>
        <xy-col span="8">22</xy-col>
        <xy-col span="16">22</xy-col>
    </xy-row>

dialog

    <xy-button type="primary" onclick="showDialog()">open dialog</xy-button>
    <xy-button onclick="XyDialog.alert('alert')">alert</xy-button>
    <xy-button id="confirm-btn">confirm</xy-button>
    <xy-button onclick="XyDialog.info('info')">info</xy-button>
    <xy-button onclick="XyDialog.success({title:'成功',content:'success',oktext:


EIMAGEMASK;
                tvis.item.state |= CheckedInternal ? CHECKED : UNCHECKED;
            }
            else if (tv.StateImageList is not null && StateImageIndexer.ActualIndex >= 0)
            {
                tvis.item.mask |= TVITEM_MASK.TVIF_STATE;
                tvis.item.stateMask = TREE_VIEW_ITEM_STATE_FLAGS.TVIS_STATEIMAGEMASK;
                tvis.item.state = (TREE_VIEW_ITEM_STATE_FLAGS)((StateImageIndexer.ActualIndex + 1) << SHIFTVAL);
            }

            if (tvis.item.iImage >= 0)
            {
                tvis.item.mask |= TVITEM_MASK.TVIF_IMAGE;
            }

            if (tvis.item.iSelectedImage >= 0)
            {
                tvis.item.mask |= TVITEM_MASK.TVIF_SELECTEDIMAGE;
            }

            // If you are editing when you add a new node, then the edit control
            // gets placed in the wrong place. You must restore the edit mode
            // asynchronously (PostMessage) after the add is complete
            // to get the expected behavior.
            bool editing = false;
            nint editHandle = PInvokeCore.SendMessage(tv, PInvoke.TVM_GETEDITCONTROL);
            if (editHandle != 0)
            {
                // Currently editing.
                editing = true;
                PInvokeCore.SendMessage(tv, PInvoke.TVM_ENDEDITLABELNOW, (WPARAM)(BOOL)false);
            }

            HTREEITEMInternal = (HTREEITEM)PInvokeCore.SendMessage(tv, PInvoke.TVM_INSERTITEMW, 0, ref tvis);
            tv._nodesByHandle[HTREEITEMInternal] = this;

            // Lets update the Lparam to the Handle.
            UpdateNode(TVITEM_MASK.TVIF_PARAM);

            Marshal.FreeCoTaskMem((nint)tvis.item.pszText.Value);

            if (editing)
            {
                PInvokeCore.PostMessage(tv, PInvoke.TVM_EDITLABELW, default, (LPARAM)HTREEITEMInternal);
            }

            PInvoke.InvalidateRect(tv, lpRect: null, bErase: false);

            if (_parent._nodesCleared && (insertFirst || prev is null) && !tv.Scrollable)
            {
                // We need to Redraw the TreeView ...
                // If and only If we are not scrollable ...
                // and this is the FIRST NODE to get added..
                // This is Comctl quirk where it just doesn't draw
                // the first node after a Clear( ) if Scrollable == false.
                PInvokeCore.SendMessage(tv, PInvokeCore.WM_SETREDRAW, (WPARAM)(BOOL)true);
                _nodesCleared = false;
            }
        }

        for (int i = _childCount - 1; i >= 0; i--)
        {
            _children[i].Realize(true);
        }

        // If node expansion was requested before the handle was created,
        // we can expand it now.
        if (_expandOnRealization)
        {
            Expand();
        }

        // If node collapse was requested before the handle was created,
        // we can expand it now.
        if (_collapseOnRealization)
        {
            Collapse();
        }
    }

    /// <summary>
    ///  Remove this node from the TreeView control. Child nodes are also removed from the
    ///  TreeView, but are still attached to this node.
    /// </summary>
    public void Remove()
    {
        Remove(true);
    }

    internal void Remove(bool notify)
    {
        bool expanded = IsExpanded;

        // unlink our children
        for (int i = 0; i < _childCount; i++)
        {
            _children[i].Remove(false);
        }

        // children = null;
        // unlink ourself
        if (notify && _parent is not null)
        {
            for (int i = _index; i < _parent._childCount - 1; ++i)


// 写入长度
                    try
                    {
                        this.m_stream.Write(length, 0, 8);
                        this.m_stream.Flush();  // 迫使问题早些暴露
                    }
                    catch (Exception ex)
                    {
                        strError = "写入当日日志文件时出错: " + ex.Message;
                        return -1;
                    }

                    // 读入内容，追加到当日文件末尾
                    int nWrited = 0;
                    int nThisLen = 0;
                    for (; ; )
                    {
                        byte[] buffer = new byte[4096];
                        nThisLen = Math.Min((int)lLength - nWrited, 4096);
                        nRet = this.m_streamSpare.Read(buffer, 0, nThisLen);
                        if (nRet != nThisLen)
                        {
                            strError = "读入备用文件时出错";
                            return -1;
                        }
                        try
                        {
                            this.m_stream.Write(buffer, 0, nThisLen);
                            this.m_stream.Flush();  // 迫使问题早些暴露
                        }
                        catch (Exception ex)
                        {
                            strError = "写入当日日志文件时出错: " + ex.Message;
                            return -1;
                        }

                        nWrited += nThisLen;
                        if (nWrited >= lLength)
                            break;
                    }
                }

                bSucceed = true;
            }
            finally
            {
                // 截断文件
                if (bSucceed == false)
                {
                    // 通知系统挂起
                    //this.App.HangupReason = HangupReason.OperLogError;

                    this.App.WriteErrorLog("系统启动时，试图将备用日志文件中的信息写入当日日志文件，以使系统恢复正常，但是这一努力失败了。请试着为数据目录腾出更多富余磁盘空间，然后重新启动系统。");
                    this.App.AddHangup("OperLogError");

                    this.m_stream.SetLength(lSaveLength);
                }
            }

            Debug.Assert(bSucceed == true, "");

            // 将备用文件清为空白内容
            nRet = ResetSpareFileContent(out strError);
            if (nRet == -1)
                return -1;

            // 通知系统解挂
            // this.App.HangupReason = HangupReason.None;
            this.App.ClearHangup("OperLogError");
            this.App.WriteErrorLog("系统启动时，发现备用日志文件中有上次紧急写入的日志信息，现已经成功移入当日日志文件。");
            return 1;   // 恢复成功
        }

        // 日志文件存放的目录
        public string Directory
        {
            get
            {
                return this.m_strDirectory;
            }
        }

        // 初始化对象
        public int Initial(
            LibraryApplication app,
            string strDirectory,
            out string strError)
        {
            strError = "";
            int nRet = 0;

            this.App = app;

            this.Close();

            // 2013/12/1
            ////Debug.WriteLine("begin write lock 4");
            this.m_lock.AcquireWriterLock(m_nLockTimeout);
            try
            {
                m_strDirectory = strDirectory;

                PathUtil.TryCreateDir(m_strDirectory);

                // 2013/6/16
                nRet = this.VerifyLogFiles(true, out st


panic!("Bad secret size")
    };
    while potential_second_bytes.len() > throughput {
        let mut second_bytes_to_test: Vec<u8> = Vec::new();
        for _ in 0..throughput {second_bytes_to_test.push(potential_second_bytes.pop().unwrap());}
        let attack_string = make_second_attack_string(first_short, &second_bytes_to_test, &HashSet::new(), secret_size);
        if prime_and_probe_yacc_lru(victim, &attack_string, buffer_state, stats) {
            potential_second_bytes = second_bytes_to_test;
        }
    }
    if verbose {println!("Determined that the second byte is one of the following: {:X?}", potential_second_bytes.as_slice());}
    let mut maybe_second_byte: Option<u8> = None;
    let excludes: HashSet<u8> = potential_second_bytes.iter().map(|&x|x).collect();
    while !potential_second_bytes.is_empty() {
        let second_byte_to_test = potential_second_bytes.pop().unwrap();
        let attack_string = make_second_attack_string(first_short,&vec![second_byte_to_test], &excludes, secret_size);
        if prime_and_probe_yacc_lru(victim, &attack_string, buffer_state, stats) {
            maybe_second_byte = Some(second_byte_to_test);
            potential_second_bytes.clear();
        }
    }
    return maybe_second_byte;
}

fn crack_last_byte(victim: &mut VictimProgramYACC, secret_size: usize, first_short: u16, second_byte: u8, buffer_state: &mut[u8], stats: &mut AttackStats, verbose: bool) -> Option<u8> {
    let mut potential_last_bytes: Vec<u8> = (0x01..=0xFF).collect();
    if verbose {println!("Cracking the last byte...")}
    let throughput = match secret_size {
        4 => 14,
        8 => 12,
        _ => panic!("Bad secret size")
    };
    while potential_last_bytes.len() > throughput {
        let mut last_bytes_to_test: Vec<u8> = Vec::new();
        for _ in 0..throughput {last_bytes_to_test.push(potential_last_bytes.pop().unwrap());}
        let attack_string = make_third_attack_string(first_short, second_byte, &last_bytes_to_test, &HashSet::new(), secret_size);
        if prime_and_probe_yacc_lru(victim, &attack_string, buffer_state, stats) {
            potential_last_bytes = last_bytes_to_test;
        }
    }
    if verbose {println!("Determined that the last byte is one of the following: {:X?}", potential_last_bytes.as_slice());}
    let mut maybe_last_byte: Option<u8> = None;
    let excludes: HashSet<u8> = potential_last_bytes.iter().map(|&x|x).collect();
    while !potential_last_bytes.is_empty() {
        let last_byte_to_test = potential_last_bytes.pop().unwrap();
        let attack_string = make_third_attack_string(first_short, second_byte,&vec![last_byte_to_test], &excludes, secret_size);
        if prime_and_probe_yacc_lru(victim, &attack_string, buffer_state, stats) {
            maybe_last_byte = Some(last_byte_to_test);
            potential_last_bytes.clear();
        }
    }
    return maybe_last_byte;
}

/// Attacks a victim with the following characteristics:
/// * Secret is 8 bytes and placed at the end of a 256-byte superblock
/// * All other bytes in the superblock can be read/written by the attacker
/// * The compressed cache is YACC w/ C-PACK
/// * The cache associativity is as defined in


	const auto auc = new float[numsColumn.size() * numRepeat];
	std::for_each(seed, seed + numRepeat, [](int& a) { a = rand(); });

#ifdef ParallelizationProvider_IntelTBB
	tbb::parallel_for<int>(0, numsColumn.size(), [&](int i) {
		tbb::parallel_for<int>(0, numRepeat, [&](int j) {
#else // @formatter:off
	#pragma omp parallel for
	for (int i = 0; i < numsColumn.size(); i++) {
		for (int j = 0; j < numRepeat; j++) {
#endif // @formatter:on
			srand(seed[j]);

			char pathScore[260];
			sprintf(pathScore, SOLUTION_DIR"temp/Score%d.txt", i * numRepeat + j);
			const auto fileScore = fopen(pathScore, "w");
			// MIDAS::NormalCore midas(2, numsColumn[i]);
			// MIDAS::RelationalCore midas(2, numsColumn[i]);
			MIDAS::FilteringCore midas(2, numsColumn[i], threshold);
			for (int k = 0; k < n; k++)
				fprintf(fileScore, "%f\n", midas(source[k], destination[k], timestamp[k]));
			fclose(fileScore);

			char command[1024];
			sprintf(command, "python %s %s %s %d", SOLUTION_DIR"util/EvaluateScore.py", pathGroundTruth, pathScore, i * numRepeat + j);
			system(command);

			char pathAUC[260];
			sprintf(pathAUC, SOLUTION_DIR"temp/AUC%d.txt", i * numRepeat + j);
			const auto fileAUC = fopen(pathAUC, "r");
			fscanf(fileAUC, "%f", auc + i * numRepeat + j);
			fclose(fileAUC);
#ifdef ParallelizationProvider_IntelTBB
		});
	});
#else // @formatter:off
		}
	}
#endif // @formatter:on

	const auto fileResult = fopen(SOLUTION_DIR"temp/Experiment.csv", "w");
	fprintf(fileResult, "numColumn,threshold,seed,auc\n");
	for (int i = 0; i < numsColumn.size(); i++)
		for (int j = 0; j < numRepeat; j++)
			fprintf(fileResult, "%d,%g,%d,%f\n", numsColumn[i], threshold, seed[j], auc[i * numRepeat + j]);
	fclose(fileResult);

	delete[] seed;
	delete[] auc;
}

void FactorVsAUC(int n, const char* pathGroundTruth, int numColumn, float threshold, const std::vector<float>& factors, int numRepeat, const int* source, const int* destination, const int* timestamp) {
	const auto seed = new int[numRepeat];
	const auto auc = new float[factors.size() * numRepeat];
	std::for_each(seed, seed + numRepeat, [](int& a) { a = rand(); });

#ifdef ParallelizationProvider_IntelTBB
	tbb::parallel_for<int>(0, factors.size(), [&](int i) {
		tbb::parallel_for<int>(0, numRepeat, [&](int j) {
#else // @formatter:off
	#pragma omp parallel for
	for (int i = 0; i < factors.size(); i++) {
		for (int j = 0; j < numRepeat; j++) {
#endif // @formatter:on
			srand(seed[j]);

			char pathScore[260];
			sprintf(pathScore, SOLUTION_DIR"temp/Score%d.txt", i * numRepeat + j);
			const auto fileScore = fopen(pathScore, "w");
			// MIDAS::NormalCore midas(2, numColumn); // This core does not use factors
			// MIDAS::RelationalCore midas(2, numColumn, factors[i]);
			MIDAS::FilteringCore midas(2, numC


find {|key,value| key > 1}
=> [2, 4]                      # Hash#find当找到满足条件的就停止，以数组的形式返回满足条件的键值对
irb(main):031:0> class Hash
irb(main):032:1>   def find_all
irb(main):033:2>     new_hash = Hash.new
irb(main):034:2>     each {|k,v| new_hash[k] = v if yield(k,v)}
irb(main):035:2>     new_hash
irb(main):036:2>   end
irb(main):037:1> end
=> nil
irb(main):038:0> squares.find_all {|key,value| key > 1}
=> {2=>4, 3=>9}

irb(main):053:0> def invoke_on_each(*args, &block)
irb(main):054:1>   args.each {|arg| yield arg}
irb(main):055:1> end
=> nil
irb(main):056:0> invoke_on_each(1,2,3,4) {|x| puts x ** 2}
1
4
9
16
=> [1, 2, 3, 4]

---
layout: post
title: "Subversion管理后台增加对SVN容灾的支持"
---

群英汇Subversion版本控制系统提供的基本服务，实际上已经包含了简单的容灾实现：

在本机使用 gistore 进行数据备份

在备机上用 git pull 进行每日一次的数据同步

这个方法对于大多数公司，对于非核心数据的容灾备份已经足够，但是对于代码，不同的公司有着不同的敏感度，可能每日一次的备份就不合适了。

最近在给一个客户进行SVN版本控制系统的实施时，就碰到了SVN服务器间建立镜像和实时备份的需要

两个异地的开发团队，每个团队工作在不同的本地版本库，可能会参考（读取）异地不同版本库的内容

异地团队中间通过无线网桥互联，互联网桥的通讯质量易受到环境、气候的影响

如果两个异地的SVN服务器能够互做镜像，可以实现双机热备

一个团队可以在本地的主版本库中读写，一旦有数据写入本地版本库，就会同步到无线网桥另外一端的版本库。反之亦然。

由于本地还提供无线网桥另外一端版本库的镜像，因此访问远程版本库可以改用本地镜像进行访问，实现本地读取速度。
如果需要写入，配置 SVN反向代理，实现透明的远程写入。

Subversion可


任何平台） 上创建 32 个字符的十六进制格式哈希字符串
        /// </summary>
        /// <param name="source"></param>
        /// <returns>32位md5加密字符串</returns>
        public static string Md5For32(string source)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source));
                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                string hash = sBuilder.ToString();
                return hash.ToUpper();
            }
        }
        #endregion

        #region 获取16位md5加密
        /// <summary>
        /// 获取16位md5加密
        /// </summary>
        /// <param name="source"></param>
        /// <returns>16位md5加密字符串</returns>
        public static string Md5For16(string source)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source));
                //转换成字符串，并取9到25位
                string sBuilder = BitConverter.ToString(data, 4, 8);
                //BitConverter转换出来的字符串会在每个字符中间产生一个分隔符，需要去除掉
                sBuilder = sBuilder.Replace("-", "");
                return sBuilder.ToUpper();
            }
        }

        #endregion

        #region 返回当前的毫秒时间戳

        /// <summary>
        /// 返回当前的毫秒时间戳
        /// </summary>
        public static string Msectime()
        {
            long timeTicks = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
            return timeTicks.ToString();
        }

        #endregion

        #region 获取多种数据编号
        /// <summary>
        /// 获取多种数据编号
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetSerialNumberType(int type)
        {
            var str = string.Empty;
            Random rand = new Random();
            switch (type)
            {
                case (int)GlobalEnumVars.SerialNumberType.订单编号:         //订单编号
                    str = type + Msectime() + rand.Next(0, 9);
                    break;
                case (int)GlobalEnumVars.SerialNumberType.支付单编号:         //支付单编号
                    str = type + Msectime() + rand.Next(0, 9);
                    break;
                case (int)GlobalEnumVars.SerialNumberType.商品编号:         //商品编号
                    str = 'G' + Msectime() + rand.Next(0, 5);
                    break;
                case (int)GlobalEnumVars.SerialNumberType.货品编号:         //货品编号
                    str = 'P' + Msectime() + rand.Next(0, 5);
                    break;
                case (int)GlobalEnumVars.SerialNumberType.售后单编号:         //售后单编号
                    str = type + Msectime() + rand.Next(0, 9);
                    break;
                case (int)GlobalEnumVars.SerialNumberType.退款单编号:         //退款单编号
                    str = type + Msectime() + rand.Next(0, 9);
                    break;
                case (int)GlobalEnumVars.SerialNumberT


separate
    // fields which intersect each other and queryCommandValue seems to return
    // false if the command is only applied to part of the field.
    setUpSubSuperTests();
    FIELDMOCK.$replay();

    HELPER.select('12345', 1, '12345', 3); // Selects '23'.
    FORMATTER.execCommandInternal(
        goog.editor.plugins.BasicTextFormatter.COMMAND.SUPERSCRIPT);
    HELPER.assertHtmlMatches('1'+OPEN_SUPER+'23'+CLOSE_SUPER+'45');
    HELPER.select('23', 1, '45', 1); // Selects '34'.
    FORMATTER.execCommandInternal(
        goog.editor.plugins.BasicTextFormatter.COMMAND.SUBSCRIPT);
    HELPER.assertHtmlMatches('1'+OPEN_SUPER+'2'+CLOSE_SUPER
                             +OPEN_SUB+'34'+CLOSE_SUB+'5');

    FIELDMOCK.$verify();
    tearDownSubSuperTests();
  }

  function testSuperscriptRemovesSubscriptIntersecting() {
    // Tests: 12345 , sub(23) , sup(34) ==> 1+sub(2)+sup(34)+5
    setUpSubSuperTests();
    FIELDMOCK.$replay();

    HELPER.select('12345', 1, '12345', 3); // Selects '23'.
    FORMATTER.execCommandInternal(
        goog.editor.plugins.BasicTextFormatter.COMMAND.SUBSCRIPT);
    HELPER.assertHtmlMatches('1'+OPEN_SUB+'23'+CLOSE_SUB+'45');
    HELPER.select('23', 1, '45', 1); // Selects '34'.
    FORMATTER.execCommandInternal(
        goog.editor.plugins.BasicTextFormatter.COMMAND.SUPERSCRIPT);
    HELPER.assertHtmlMatches('1'+OPEN_SUB+'2'+CLOSE_SUB
                             +OPEN_SUPER+'34'+CLOSE_SUPER+'5');

    FIELDMOCK.$verify();
    tearDownSubSuperTests();
  }

  function setUpLinkTests(url) {
    stubs.set(window, 'prompt', function() {
      return url;
    });

    ROOT.innerHTML = '12345';
    HELPER = new goog.testing.editor.TestHelper(ROOT);
    HELPER.setUpEditableElement();

    FIELDMOCK.getElement().$anyTimes().$returns(ROOT);

    FIELDMOCK.execCommand(goog.editor.Command.MODAL_LINK_EDITOR,
        goog.testing.mockmatchers.isObject).$returns(undefined);
    FIELDMOCK.setModalMode(true);

    FIELDMOCK.isSelectionEditable().$anyTimes().$returns(true);

    FORMATTER.focusField_ = function() {
      throw 'Field should not be re-focused';
    }
  }

  function tearDownLinkTests() {
    tearDownHelper();
  }

  function testLink() {
    setUpLinkTests('http://www.x.com/');
    FIELDMOCK.$replay();

    HELPER.select('12345', 3);
    FORMATTER.execCommandInternal(goog.editor.Command.LINK);
    HELPER.assertHtmlMatches(
        goog.editor.BrowserFeature.GETS_STUCK_IN_LINKS ?
            '123http://www.x.com/ 45' :
            '123http://www.x.com/45');

    FIELDMOCK.$verify();
    tearDownLinkTests();
  }

  function testSelectedLink() {
    setUpLinkTests('http://www.x.com/');
    FIELDMOCK.$replay();

    HELPER.select('12345', 1, '12345', 4);
    FORMATTER.execCommandInternal(goog.editor.Command.LINK);
    HELPER.assertHtmlMatches(
        goog.editor.BrowserFeature.GETS_STUCK_IN_LINKS ?
            '1234 5' :
            '12345');

    FIELDMOCK.$verify();
    tearDown


/*********************************************************************
*
* Software License Agreement (BSD License)
*
*  Copyright (c) 2008, Willow Garage, Inc.
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of Willow Garage, Inc. nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*
* Author: Eitan Marder-Eppstein
*********************************************************************/

#include <boost/shared_ptr.hpp>

#ifndef ACTIONLIB_ENCLOSURE_DELETER_H_
#define ACTIONLIB_ENCLOSURE_DELETER_H_

namespace actionlib
{

/*
 * This allows the creation of a shared pointer to a section
 * of an already reference counted structure. For example,
 * if in the following picture Enclosure is reference counted with
 * a boost::shared_ptr and you want to return a boost::shared_ptr
 * to the Member that is referenced counted along with Enclosure objects
 *
 * Enclosure ---------------  <--- Already reference counted
 * -----Member <------- A member of enclosure objects, eg. Enclosure.Member
 */
template <class Enclosure> class EnclosureDeleter {
  public:
    EnclosureDeleter(const boost::shared_ptr<Enclosure>& enc_ptr) : enc_ptr_(enc_ptr){}

    template<class Member> void operator()(Member* member_ptr){
      enc_ptr_.reset();
    }

  private:
    boost::shared_ptr<Enclosure> enc_ptr_;
};

template <class Enclosure, class Member>
boost::shared_ptr<Member> share_member(boost::shared_ptr<Enclosure> enclosure, Member &member)
{
  EnclosureDeleter<Enclosure> d(enclosure);
  boost::shared_ptr<Member> p(&member, d);
  return p;
}

}

#endif


l]];c?(0===t&&(t=Ii()),f[l]=c(r[l])):f[l]=r[l]}var s=n.apply(null,f);return"string"===A&&(s=G(s)),0!==t&&Ci(t),s}function I(e,A,i,r){switch("*"===(i=i||"i8").charAt(i.length-1)&&(i="i32"),i){case"i1":case"i8":N[e>>0]=A;break;case"i16":R[e>>1]=A;break;case"i32":H[e>>2]=A;break;case"i64":tempI64=[A>>>0,(tempDouble=A,+Ee(tempDouble)>=1?tempDouble>0?(0|ye(+Ze(tempDouble/4294967296),4294967295))>>>0:~~+Ie((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],H[e>>2]=tempI64[0],H[e+4>>2]=tempI64[1];break;case"float":x[e>>2]=A;break;case"double":U[e>>3]=A;break;default:zi("invalid type for setValue: "+i)}}var Z=2,m=4;function y(e,A,i,r){var a,n;"number"===typeof e?(a=!0,n=e):(a=!1,n=e.length);var f,t="string"===typeof A?A:null;if(f=i==m?r:["function"===typeof vi?vi:o,Ei,o,b][void 0===i?Z:i](Math.max(n,t?1:A.length)),a){var l;for(r=f,v(0==(3&f)),l=f+(-4&n);r<l;r+=4)H[r>>2]=0;for(l=f+n;r<l;)N[r++>>0]=0;return f}if("i8"===t)return e.subarray||e.slice?X.set(e,f):X.set(new Uint8Array(e),f),f;for(var c,s,u,w=0;w<n;){var h=e[w];0!==(c=t||A[w])?("i64"==c&&(c="i32"),I(f+w,h,c),u!==c&&(s=k(c),u=c),w+=s):w++}return f}function G(e,A){if(0===A||!e)return"";for(var i,r=0,a=0;r|=i=X[e+a>>0],(0!=i||A)&&(a++,!A||a!=A););A||(A=a);var n="";if(r<128){for(var f,t=1024;A>0;)f=String.fromCharCode.apply(String,X.subarray(e,e+Math.min(A,t))),n=n?n+f:f,e+=t,A-=t;return n}return W(e)}var Q="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0;function L(e,A){for(var i=A;e[i];)++i;if(i-A>16&&e.subarray&&Q)return Q.decode(e.subarray(A,i));for(var r,a,n,f,t,l="";;){if(!(r=e[A++]))return l;if(128&r)if(a=63&e[A++],192!=(224&r))if(n=63&e[A++],224==(240&r)?r=(15&r)<<12|a<<6|n:(f=63&e[A++],240==(248&r)?r=(7&r)<<18|a<<12|n<<6|f:(t=63&e[A++],r=248==(252&r)?(3&r)<<24|a<<18|n<<12|f<<6|t:(1&r)<<30|a<<24|n<<18|f<<12|t


"""Clone & cache template repositories for resource categories."""
from __future__ import annotations

import logging
import subprocess
import tempfile
from pathlib import Path

from ..config import get_settings

logger = logging.getLogger(__name__)
settings = get_settings()

# Root directory under the OS tmp dir to cache cloned template repos
_CACHE_ROOT = Path(tempfile.gettempdir()) / "template_repos"
_CACHE_ROOT.mkdir(exist_ok=True)

def get_template_dir(category: str) -> Path:
    """Return local path to template repository for *category*.

    Clones the repo on first request and then reuses the cached clone on
    subsequent calls. Raises ``KeyError`` if the category is not configured.
    """
    try:
        repo_url = settings.template_repo_map[category]
    except KeyError as err:
        raise KeyError(f"No template repo configured for category '{category}'") from err

    repo_name = repo_url.rsplit("/", 1)[-1].removesuffix(".git")
    target = _CACHE_ROOT / repo_name

    if target.exists():
        logger.debug("Using cached template repo for %s at %s", category, target)
        return target

    logger.info("Cloning template repo %s -> %s", repo_url, target)
    try:
        subprocess.check_call(["git", "clone", "--depth", "1", repo_url, str(target)])
    except subprocess.CalledProcessError as exc:
        logger.error("Failed to clone template repo %s: %s", repo_url, exc)
        raise RuntimeError(f"Unable to clone template repo {repo_url}") from exc

    return target