hoice":
        return Sample(
            input=message,
            choices=record["choices"],
            target=get_multi_choice_as_letter(record),
            id=record["pid"],
            metadata={
                "question_type": record["question_type"],
                "answer_type": record["answer_type"],
                **record["metadata"],
            },
        )

    elif record["question_type"] == "free_form":
        return Sample(
            input=message,
            target=record["answer"],
            id=record["pid"],
            metadata={
                "precision": record["precision"],
                "question_type": record["question_type"],
                "answer_type": record["answer_type"],
                **record["metadata"],
            },
        )
    else:
        raise ValueError(f"Unexpected question_type: {record['question_type']}")

def get_multi_choice_as_letter(record: dict[str, Any]) -> str:
    choices = record["choices"]
    labels = [chr(i) for i in range(ord("a"), ord("a") + len(choices))]

    choices = dict(zip(labels, choices))

    answer = record["answer"]
    target = list(choices.values()).index(answer)
    return chr(ord("A") + int(target))

def is_image_png(image_bytes: bytes) -> bool:
    return image_bytes[:8] == b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"

def is_image_webp(image_bytes: bytes) -> bool:
    return image_bytes[:4] == b"RIFF" and image_bytes[8:12] == b"WEBP"


n bù liǎo",
	"黾穴鸲巢":       "měng xué qú cháo",
	"俛拾仰取":       "fǔ shí yǎng qǔ",
	"俛首帖耳":       "mǎ shǒu tiē ěr",
	"勉勉强强":       "miǎn miǎn qiǎng qiáng",
	"俛拾地芥":       "bì shí dì jiè",
	"勉为其难":       "miǎn wéi qí nán",
	"腼颜事仇":       "miǎn yán shì chóu",
	"面包车":        "miàn bāo chē",
	"面北眉南":       "miàn běi méi nán",
	"面壁磨砖":       "miàn bì mó zhuān",
	"面从腹诽":       "miàn cóng fù fěi",
	"面不改色":       "miàn bù gǎi sè",
	"面不改容":       "miàn bù gǎi róng",
	"面红耳热":       "miàn hóng ěr rè",
	"面红耳赤":       "miàn hóng ěr chì",
	"面红颈赤":       "miàn hóng jǐng chì",
	"面红面赤":       "miàn hóng miàn chì",
	"面红面绿":       "miàn hóng miàn lǜ",
	"面面观":        "miàn miàn guān",
	"面面厮觑":       "miàn miàn sī qù",
	"面面相睹":       "miàn miàn xiāng dǔ",
	"面面相看":       "miàn miàn xiāng kàn",
	"面面相窥":       "miàn miàn xiāng kuī",
	"面面相觑":       "miàn miàn xiāng qù",
	"面命耳提":       "miàn mìng ěr tí",
	"面片儿":        "miàn piān er",
	"面目可憎":       "miàn mù kě zēng",
	"面如冠玉":       "miàn rú guān yù",
	"面若死灰":       "miàn ruò sǐ huī",
	"面是背非":       "miàn shì bèi fēi",
	"面似靴皮":       "miàn sì xuē pí",
	"面有菜色":       "miàn yǒu cài sè",
	"面有难色":       "miàn yǒu nán sè",
	"面誉背毁":       "miàn yù bèi huǐ",
	"面谀背毁":       "miàn yú bèi huǐ",
	"面誉背非":       "miàn yù bèi fēi",
	"面折廷争":       "miàn zhé tíng zhēng",
	"面折廷诤":       "miàn shé tíng zhèng",
	"苗而不秀":       "miáo ér bù xiù",
	"面争庭论":       "miàn zhēng tíng lùn",
	"面折庭�


tain658
"
},
{
  "summary": "Madalin Stunt Cars 2 Fixed!",
  "date": "2024-03-19T10:57",
  "details": "Just Fixed Madalin Stunt Cars 2!!! Go play it!",
  "html": "
CircleO
-mountain658
"
},
{
  "summary": "Crossy Road Fixed!",
  "date": "2024-03-19T10:57",
  "details": "Just Fixed Crossy Road! Woo! Go play it.",
  "html": "
CircleO
-mountain658
"
},
{
  "summary": "Volley Random is working!",
  "date": "2024-03-19T11:03",
  "details": "Just Fixed Volley Random! Woo! Go play it.",
  "html": "
Volley Random
-mountain658
"
},
{
  "summary": "Subway Surfers",
  "date": "2024-03-20T10:03",
  "details": "Removed a broken Subway Surfers server.",
  "html": "
Subway Surfers
-mountain658
"
},
{
  "summary": "Fixed Papery Planes",
  "date": "2024-03-20T10:03",
  "details": "Fixed Papery Planes, so now you can play it!",
  "html": "
Papery Planes
-mountain658
"
},
{
  "summary": "Ping Pong Chaos, is Fixed!",
  "date": "2024-03-20T10:20",
  "details": "Fixed Ping Pong Chaos, so now you can play it!",
  "html": "
Ping Pong Chaos
-mountain658
"
},
{
  "summary": "T-rex Game Updated!!!",
  "date": "2024-03-20T10:25",
  "details": "Fixed T-rex Game, so now you can play it, also, now with game modes!",
  "html": "
T-rex Game
-mountain658
"
},
{
  "summary": "Moto X3M Pool, fixed.",
  "date": "2024-03-20T10:30",
  "details": "Fixed Moto X3M Pool.html!",
  "html": "
Moto X3M Pool<h3 style=\"color:gold;font-weight


�源。

以下示例添加 `all` CustomResourceDefinition 中的类别列表，并说明如何使用 `kubectl get all` 输出自定义资源。

将以下 CustomResourceDefinition 保存到 `resourcedefinition.yaml`：

```yaml
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: crontabs.stable.example.com
spec:
  group: stable.example.com
  versions:
    - name: v1
      served: true
      storage: true
  scope: Namespaced
  names:
    plural: crontabs
    singular: crontab
    kind: CronTab
    shortNames:
    - ct
    # categories is a list of grouped resources the custom resource belongs to.
    categories:
    - all
```

并创建它：

```bash
kubectl create -f resourcedefinition.yaml
```

创建 CustomResourceDefinition 对象后，您可以创建自定义对象。

将以下 YAML 保存到 `my-crontab.yaml`：

```yaml
apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  cronSpec: "* * * * */5"
  image: my-awesome-cron-image
```

并创建它：

```bash
kubectl create -f my-crontab.yaml
```

您可以使用`kubectl get`以下方式指定类别：

```bash
kubectl get all
```

它将包括种类的自定义资源`CronTab`：

```bash
NAME                          AGE
crontabs/my-new-cron-object   3s
```

## 参考

- [Extend the Kubernetes API with CustomResourceDefinitions - kubernetes.io](https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/)
- [如何从零开始编写一个 Kubernetes CRD - cloudnative.to](https://cloudnative.to/blog/kubernetes-crd-quick-start/)
---
weight: 9
title: 容器存储接口（CSI）
date: '2022-05-21T00:00:00+08:00'
type: book
---

容器存储接口（Container Storage Interface），简称 CSI，CSI 试图建立一个行业标准接口的规范，借助 CSI 容器编排系统（CO）可以将任意存储系统暴露给自己的容器工作负载。有关详细信息，请查看设计方案。

`csi` 卷类型是一种 out-tree（即跟其它存储插件在同一个代码路径下，随 Kubernetes 的代码同时编译的）的 CSI 卷插件，用于 Pod 与在同一节点上运行的外部 CSI 卷驱动程序交互。部署 CSI 兼容卷驱动后，用户可以使用 `csi` 作为卷类型来挂载驱动提供的存储。

CSI 持久化卷支持是在 Kubernetes v1.9 中引入的，作为一个 alpha 特性，必须由集群管理员明确启用。换句话说，集群管理员需要在 apiserver、controller-manager 和 kubelet 组件的“`--feature-gates


.org/2005/xpath-functions" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema">
               Use both inline and internal CSS styles. Internal styles
use spacing and positional CSS styles. Inline styles use appearance
styles, such as color, font, and background color.

               OnlyInlineStyles:

               Use only inline CSS styles from the custom CSS file. This option
removes all internal styles inside the <head> tag on HTML
pages.

               NoStyles:

               Do not use any CSS inline or internal styling. Only styles
that are passed using an external CSS file are used.

            Twitter™ and Facebook posts are not covered under the terms of Creative Commons.

          Home

        /
        <a href="WS664056d07263ca3a-381


r6, [r0, #0x0002]	/* take advantage of nonaligned
					 * word accesses */
	ldr	r7, [r0]
	mov	r6, r6, lsr #16		/* Put the two shorts together */
	orr	r6, r6, r7, lsl #16

	stmia	r1!, {r3-r6}
	subs	r2, r2, #0x00000008	/* Next */
	bgt	insw16loop

	ldmfd	r13!, {r4-r7}

	mov	pc, lr

/*
 * Writes short ints (16 bits) from a block of memory to an I/O address
 *
 * r0 = address to write to (IO)
 * r1 = address to read from (memory)
 * r2 = length
 */

ENTRY(outsw16)
/* Make sure that we have a positive length */
	cmp	r2, #0x00000000
	movle	pc, lr

/* If the destination address is word aligned and the size suitably aligned, do it fast */

	tst	r2, #0x00000007
	tsteq	r1, #0x00000003

	bne	_outsw

/* Word aligned outsw */

	stmfd	r13!, {r4-r7}

outsw16loop:
	ldmia	r1!, {r4-r7}

	mov	r3, r4, lsl #16
	orr	r3, r3, r3, lsr #16
	str	r3, [r0]

	mov	r3, r4, lsr #16
	orr	r3, r3, r3, lsl #16
	str	r3, [r0]

	mov	r3, r5, lsl #16
	orr	r3, r3, r3, lsr #16
	str	r3, [r0]

	mov	r3, r5, lsr #16
	orr	r3, r3, r3, lsl #16
	str	r3, [r0]

	mov	r3, r6, lsl #16
	orr	r3, r3, r3, lsr #16
	str	r3, [r0]

	mov	r3, r6, lsr #16
	orr	r3, r3, r3, lsl #16
	str	r3, [r0]

	mov	r3, r7, lsl #16
	orr	r3, r3, r3, lsr #16
	str	r3, [r0]

	mov	r3, r7, lsr #16
	orr	r3, r3, r3, lsl #16
	str	r3, [r0]

	subs	r2, r2, #0x00000008
	bgt	outsw16loop

	ldmfd	sp!, {r4-r7}

	mov	pc, lr

/*
 * reads short ints (16 bits) from an I/O address into a block of memory
 * The I/O address is assumed to be mapped multiple times in a block of
 * 8 words.
 * The destination address should be word aligned.
 *
 * r0 = address to read from (IO)
 * r1 = address to write to (memory)
 * r2 = length
 */

ENTRY(inswm8)
/* Make sure that we have a positive length */
	cmp	r2, #0x00000000
	movle	pc, lr

/* If the destination address is word aligned and the size suitably aligned, do it fast */

	tst	r1, #0x00000003

	bne	_insw

/* Word aligned insw *


w/640?wx_fmt=png "")

#  OWASP 2025年十大漏洞
铸盾安全  河南等级保护测评   2025-01-22 16:00

![](https://mmbiz.qpic.cn/sz_mmbiz_png/rTibWNx9ARWnuoSW8vkOrDrWjBnQjSNrgbRjECWcYfzom2C3F55piaNUicf2InhPIHVic0iauIZXIhZUQ86s6X49plQ/640?wx_fmt=other&from=appmsg&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1 "")

开放 Web 应用程序安全项目 (OWASP) 发布了备受期待的 2025 年智能合约十大漏洞，这是一份全面的认识文件，旨在让 Web3 开发人员和安全团队掌握对抗智能合约中最关键
漏洞
的知识。

随着去中心化金融 (DeFi) 和区块链技术的不断发展，强大的智能合约安全性的重要性从未如此明显。最新列表反映了不断发展的攻击媒介，并重点介绍了近年来最常被利用或发现的漏洞。

OWASP 智能合约 Top 10
是
开发人员、审计人员和安全专业人员的重要资源，可提供对常见弱点和缓解策略的见解。

它对其他 OWASP 项目（例如智能合约安全验证标准 (SCSVS) 和智能合约安全测试指南 (SCSTG)）进行了补充，为保护区块链生态系统提供了整体方法。
## 2023 年至 2025 年的主要变化

2025 年版根据现实世界中的事件和新兴趋势引入了更新的排名和新见解。值得注意的变化包括增加了价格预言机操纵和闪电贷攻击作为不同的类别，反映了它们在 DeFi 漏洞利用中的日益普遍。

同时，早期版本中突出的时间戳依赖性和 Gas 限制问题等漏洞已被替换或集成到逻辑错误等更广泛的类别中。

![](https://mmbiz.qpic.cn/sz_mmbiz_png/rTibWNx9ARWnuoSW8vkOrDrWjBnQjSNrgwZEDbfgFNpnC8JC2YG3dY5IwJLZnGmHReS8BjRLLibJlyPRYkYz2qog/640?wx_fmt=other&from=appmsg&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1 "")
## OWASP 2025 年十大漏洞：
1. **访问控制漏洞**

1. **价格预言机操纵**

1. **逻辑错误**

1. **缺乏输入验证**

1. **重入攻击**

1. **未经检查的外部调用**

1. **闪电贷攻击**

1. **整数上溢和下溢**

1. **不安全的随机性**

1. **拒绝服务 (DoS) 攻击**

## 主要漏洞的详细概


ns) do
        descriptor._extensions_by_name[k.name] = k
    end
    rawset(descriptor, "_extensions_by_number", {})
    for _, k in ipairs(descriptor.extensions) do
        descriptor._extensions_by_number[k.number] = k
    end
    message_meta._descriptor = descriptor
    message_meta._extensions_by_name = {}
    message_meta._extensions_by_number = {}

    message_meta._getter = {}
    message_meta._setter = {}
    message_meta._member = {}
--    message_meta._name = descriptor.full_name

    local ns = setmetatable({}, message_meta._member)
    message_meta._member.__call = _InitMethod(message_meta)
    message_meta._member.__index = message_meta._member
    message_meta._member.type = ns

    if rawget(descriptor, "_concrete_class") == nil then
        rawset(descriptor, "_concrete_class", ns)
        for k, field in ipairs(descriptor.fields) do
            _AttachFieldHelpers(message_meta, field)
        end
    end
    _AddEnumValues(descriptor, message_meta)
    _AddClassAttributesForNestedExtensions(descriptor, message_meta)
    _AddPropertiesForFields(descriptor, message_meta)
    _AddPropertiesForExtensions(descriptor, message_meta)
    _AddStaticMethods(message_meta)
    _AddMessageMethods(descriptor, message_meta)
    _AddPrivateHelperMethods(message_meta)

    message_meta.__index = property_getter(message_meta)
    message_meta.__newindex = property_setter(message_meta)

    return ns
end

_M.Message = Message


 call without receiver: %v", Nconv(n, FmtSign))
		}
		if t == nil {
			Fatalf("method call unknown receiver type: %v", Nconv(n, FmtSign))
		}
		as := Nod(OAS, tinlvar(t), n.Left.Left)
		if as != nil {
			as = typecheck(as, Etop)
			ninit.Append(as)
		}
	}

	// check if inlined function is variadic.
	variadic := false

	var varargtype *Type
	varargcount := 0
	for _, t := range fn.Type.Params().Fields().Slice() {
		if t.Isddd {
			variadic = true
			varargtype = t.Type
		}
	}

	// but if argument is dotted too forget about variadicity.
	if variadic && isddd {
		variadic = false
	}

	// check if argument is actually a returned tuple from call.
	multiret := 0

	if n.List.Len() == 1 {
		switch n.List.First().Op {
		case OCALL, OCALLFUNC, OCALLINTER, OCALLMETH:
			if n.List.First().Left.Type.Results().NumFields() > 1 {
				multiret = n.List.First().Left.Type.Results().NumFields() - 1
			}
		}
	}

	if variadic {
		varargcount = n.List.Len() + multiret
		if n.Left.Op != ODOTMETH {
			varargcount -= fn.Type.Recvs().NumFields()
		}
		varargcount -= fn.Type.Params().NumFields() - 1
	}

	// assign arguments to the parameters' temp names
	as := Nod(OAS2, nil, nil)

	as.Rlist.Set(n.List.Slice())
	li := 0

	// TODO: if len(nlist) == 1 but multiple args, check that n->list->n is a call?
	if fn.Type.Recv() != nil && n.Left.Op != ODOTMETH {
		// non-method call to method
		if n.List.Len() == 0 {
			Fatalf("non-method call to method without first arg: %v", Nconv(n, FmtSign))
		}

		// append receiver inlvar to LHS.
		t := fn.Type.Recv()

		if t != nil && t.Nname != nil && !isblank(t.Nname) && t.Nname.Name.Inlvar == nil {
			Fatalf("missing inlvar for %v\n", t.Nname)
		}
		if t == nil {
			Fatalf("method call unknown receiver type: %v", Nconv(n, FmtSign))
		}
		as.List.Append(tinlvar(t))
		li++
	}

	// append ordinary arguments to LHS.
	chkargcount := n.List.Len() > 1

	var vararg *Node    // the slice argument to a variadic call
	var varargs []*Node // the list of LHS names to put in vararg.
	if !chkargcount {
		// 0 or 1 expression on RHS.
		var i int
		for _, t := range fn.Type.Params().Fields().Slice() {
			if variadic && t.Isddd {
				vararg = tinlvar(t)
				for i = 0; i < varargcount && li < n.List.Len(); i++ {
					m = argvar(varargtype, i)
					varargs = append(varargs, m)
					as.List.Append(m)
				}

				break
			}

			as.List.Append(tinlvar(t))
		}
	} else {
		// match arguments except final variadic (unless the call is dotted itself)
		t, it := IterFields(fn.Type.Params())
		for t != nil {
			if li >= n.List.Len() {
				break
			}


,
.popover ul,
.control-label,
.dropdown-menu a,
footer,
header,
nav:not(.navbar-fixed-top) {
    font-family: gotham narrow ssm a, gotham narrow ssm b, Arial, sans-serif
}

.note,
.footer-links-legal,
h2,
.h2-extend,
h3.light,
h4.light {
    font-family: gotham narrow ssm a, gotham narrow ssm b, Arial, sans-serif;
    font-weight: 300
}

.footer-signup p:first-of-type,
.footer-links-primary,
.nav-popover h5 {
    font-family: gotham narrow ssm a, gotham narrow ssm b, Arial, sans-serif;
    font-weight: 500
}

.form-header {
    font-family: gotham narrow ssm a, gotham narrow ssm b, Arial, sans-serif;
    font-weight: 700
}

.form-group-special .form-control,
.form-control {
    font-family: gotham ssm a, gotham ssm b, Arial, sans-serif;
    font-weight: 400
}

.form-label {
    font-weight: 500
}

h1 {
    font-family: Georgia, times new roman, Times, serif
}

h1,
h2,
.h2-extend,
h3.light,
h4.light {
    color: #333
}

h1 a,
h2 a,
.h2-extend a,
h3 a,
h4 a,
h5 a,
h6 a {
    color: inherit
}

h1 a:hover,
h1 a:active,
h1 a:focus,
h2 a:hover,
.h2-extend a:hover,
h2 a:active,
.h2-extend a:active,
h2 a:focus,
.h2-extend a:focus,
h3 a:hover,
h3 a:active,
h3 a:focus,
h4 a:hover,
h4 a:active,
h4 a:focus,
h5 a:hover,
h5 a:active,
h5 a:focus,
h6 a:hover,
h6 a:active,
h6 a:focus {
    color: inherit
}

.header-group {
    vertical-align: middle
}

.header-group a {
    font-size: 16px
}

.footer-signup .input-group {
    font-family: gotham ssm a, gotham ssm b, Arial, sans-serif
}

.text-callout {
    font-size: 75px
}

.text-complimentary {
    color: #e4002b
}

a.link-muted {
    color: #797676
}

a.link-muted:hover,
a.link-muted:active,
a.link-muted:focus {
    color: #797676
}

.text-live {
    color: #e4002b !important
}

.text-conversion {
    color: #24988b !important
}

.text-large {
    font-size: 18px
}

.h1-small {
    font-size: 20px;
    color: #333
}

.trigger>.fa {
    color: #777
}

.trigger>.fa:hover {
    color: #555
}

.btn {
    font-weight: 300;
    text-transform: capitalize;
    font-family: gotham ssm a, gotham ssm b, helvetica, sans-serif
}

.btn:active,
.btn.active {
    outline: 0;
    outline-offset: 0;
    box-shadow: none
}

.btn-transparent {
    background-color: transparent;
    border-color: transparent
}

.btn-primary {
    border-width: 2px;
    border-color: #222;
    background-color: #222
}

.btn-primary:hover:not(:disabled),
.btn-primary:active:not(:disabled),


],hu_HU:"Next years",id_ID:["Tahun mendatang"],it:["Anni prossimi"],ja:["次の年"],ko:["다음 해들"],ms_MY:["Tahun-tahun hadapan"],nl_NL:"Next years",pl:["Następne lata"],pt:["Próximos anos"],ro:"Next years",ru:["Следующие годы"],sv:["Kommande år"],th:["ปีถัดไป"],tr:["Sonraki yıllar"],vi:["Năm sau"],zh:["未来几年"],zh_TW:["未來幾年"]}},39752:e=>{e.exports={ar:["الشهر القادم"],ca_ES:["Pròxim mes"],cs:"Next month",de:["Nächster Monat"],el:"Next month",en:"Next month",es:["Próximo mes"],fa:"Next month",fr:["Mois suivant"],he_IL:["חודש הבא"],hu_HU:"Next month",id_ID:["Bulan depan"],it:["Mese prossimo"],ja:["翌月"],ko:["다음 달"],ms_MY:["Bulan hadapan"],nl_NL:"Next month",pl:["Następny miesiąc"],pt:["Próximo mês"],ro:"Next month",ru:["Следующий месяц"],sv:["Nästa månad"],th:["เดือนถัดไป"],tr:["Sonraki ay"],vi:["Tháng sau"],zh:["下一个月"],zh_TW:["下個月"]}},1144:e=>{e.exports={ar:["السبت"],ca_ES:["Dissabte"],cs:"Saturday",de:["Samstag"],el:"Saturday",en:"Saturday",es:["Sábado"],fa:"Saturday",fr:["Samedi"],he_IL:["יום שבת"],hu_HU:["Szombat"],id_ID:["Sabtu"],it:["Sabato"],ja:["土曜日"],ko:["토요일"],ms_MY:["Sabtu"],nl_NL:"Saturday",pl:["Sobota"],pt:["Sábado"],ro:"Saturday",ru:["Суббота"],sv:["Lördag"],th:["เสาร์"],tr:["Cumartesi"],vi:["Thứ Bảy"],zh:["周六"],zh_TW:["周六"]}},61132:e=>{e.exports={ar:["سبتمبر"],ca_ES:["Setembre"],cs:"September",de:"September",el:"September",en:"September",es:["Septiembre"],fa:"September",fr:["Septembre"],he_IL:["ספטמבר"],
hu_HU:["Szeptember"],id_ID:"September",it:["Settembre"],ja:["9月"],ko:["9월"],ms_MY:"September",nl_NL:"September",pl:["Wrzesień"],pt:["Setembro"],ro:"September",ru:["Сентябрь"],sv:"September",th:["กันยายน"],tr:["Eylül"],vi:["Tháng Chín"],zh:["9月"],zh_TW:["九月"]}},72149:e=>{e.exports={ar:["الأحد"],ca_ES:["Diumenge"],cs:"Sunday",de:["Sonntag"],el:"Sunday",en:"Sunday",es:["Domingo"],fa:"Sunday",fr:["Dimanche"],he_IL:["יום ראשון"],hu_HU:["Vasárnap"],id_ID:["Minggu"],it:["Domenica"],ja:["日曜日"],ko:["일요일"],ms_MY:["Ahad"],nl_NL:"Sunday",pl:["N


-----------------------------------
-- Area: Windurst Waters
--  NPC: Janta-Jonta
-----------------------------------
---@type TNpcEntity
local entity = {}

local pathNodes =
{
    { x = -97.897, y = -2.000, z = 43.691 },
    { x = -98.851, z = 43.300 },
    { x = -103.309, z = 42.171 },
    { x = -105.608, z = 42.139 },
    { x = -109.440, z = 42.243 },
    { x = -110.261, z = 43.213 },
    { x = -110.604, z = 43.858 },
    { x = -112.127, z = 47.675 },
    { x = -111.858, z = 48.171 },
    { x = -111.007, z = 48.939 },
    { x = -106.684, z = 51.447 },
    { x = -105.


.ld.128.usar.ip q1, a1, 16

    beqz s1, dl_esp32p4_s8_min4d_bchw_w1_16_w2_1_simdmin_unaligned_0
    li t0, 8
    beq s1, t0, dl_esp32p4_s8_min4d_bchw_w1_16_w2_1_simdmin_unaligned_1

    add t0, a4, x0
    blez t0, 1f
    0:
        esp.src.q.qup q2, q0, q1

        #esp.ld.128.usar.ip q4, a2, 16
        #esp.src.q.qup q5, q3, q4
        esp.vldbc.8.ip q5, a2, 0

        esp.vmin.s8 q2, q2, q5

        esp.ld.128.usar.ip q1, a1, 16
        esp32p4_s8_32b_unaligned_vector_store q2, a0, s1
        addi t0, t0, -1
        bgtz t0, 0b
    1:
    addi a1, a1, -16
    add a1, a1, t5
    esp.movx.r.sar.bytes t6
    esp.src.q.qup q2, q0, q1

    #esp.ld.128.usar.xp q4, a2, t5
    #esp.movx.r.sar.bytes s0
    #esp.src.q.qup q5, q3, q4
    esp.vldbc.8.ip q5, a2, 0
    addi s0, a2, 0

    esp.vmin.s8 q2, q2, q5
    esp32p4_s8_32b_unaligned_vector_store q2, a0, s1
    j dl_esp32p4_s8_min4d_bchw_w1_16_w2_1_simdmin_unaligned_remainder

    #output sar = 0
    dl_esp32p4_s8_min4d_bchw_w1_16_w2_1_simdmin_unaligned_0:
    add t0, a4, x0
    blez t0, 3f
    2:
        esp.src.q.qup q2, q0, q1

        #esp.ld.128.usar.ip q4, a2, 16
        #esp.src.q.qup q5, q3, q4
        esp.vldbc.8.ip q5, a2, 0

        esp.vmin.s8 q2, q2, q5

        esp.ld.128.usar.ip q1, a1, 16
        esp.vst.128.ip q2, a0, 16
        addi t0, t0, -1
        bgtz t0, 2b
    3:
    addi a1, a1, -16
    add a1, a1, t5
    esp.movx.r.sar.bytes t6
    esp.src.q.qup q2, q0, q1

    #esp.ld.128.usar.xp q4, a2, t5
    #esp.movx.r.sar.bytes s0
    #esp.src.q.qup q5, q3, q4
    esp.vldbc.8.ip q5, a2, 0
    addi s0, a2, 0

    esp.vmin.s8 q2, q2, q5
    esp.vst.128.ip q2, a0, 16
    j dl_esp32p4_s8_min4d_bchw_w1_16_w2_1_simdmin_unaligned_remainder

    # #output sar = 8
    dl_esp32p4_s8_min4d_bchw_w1_16_w2_1_simdmi


  final prefCategory = PrefCategory.gameHistory;

  @override
  @protected
  GameHistoryPrefs get defaults => GameHistoryPrefs.defaults;

  @override
  GameHistoryPrefs fromJson(Map<String, dynamic> json) {
    return GameHistoryPrefs.fromJson(json);
  }

  @override
  GameHistoryPrefs build() {
    return fetch();
  }

  Future<void> setDisplayMode(GameHistoryDisplayMode displayMode) {
    return save(state.copyWith(displayMode: displayMode));
  }
}

enum GameHistoryDisplayMode { compact, detail }

@Freezed(fromJson: true, toJson: true)
sealed class GameHistoryPrefs with _$GameHistoryPrefs implements Serializable {
  const GameHistoryPrefs._();

  const factory GameHistoryPrefs({
    @JsonKey(defaultValue: GameHistoryDisplayMode.detail)
    required GameHistoryDisplayMode displayMode,
  }) = _GameHistoryPrefs;

  static const defaults = GameHistoryPrefs(displayMode: GameHistoryDisplayMode.detail);

  factory GameHistoryPrefs.fromJson(Map<String, dynamic> json) {
    return _$GameHistoryPrefsFromJson(json);
  }
}
import 'dart:convert';

import 'package:deep_pick/deep_pick.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart';
import 'package:lichess_mobile/src/model/common/id.dart';
import 'package:lichess_mobile/src/model/study/study.dart';
import 'package:lichess_mobile/src/model/study/study_filter.dart';
import 'package:lichess_mobile/src/model/study/study_list_paginator.dart';
import 'package:lichess_mobile/src/network/http.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'study_repository.g.dart';

@Riverpod(keepAlive: true)
StudyRepository studyRepository(Ref ref) {
  return StudyRepository(ref, ref.read(lichessClientProvider));
}

class StudyRepository {
  StudyRepository(this.ref, this.client);

  final Client client;
  final Ref ref;

  Future<StudyList> getStudies({
    required StudyCategory category,
    required StudyListOrder order,
    int page = 1,
  }) {
    return _requestStudies(
      path: '${category.name}/${order.name}',
      queryParameters: {'page': page.toString()},
    );
  }

  Future<StudyList> searchStudies({required String query, int page = 1}) {
    return _requestStudies(path: 'search', queryParameters: {'page': page.toString(), 'q': query});
  }

  Future<StudyList> _requestStudies({
    required String path,
    required Map<String, String> queryParameters,
  }) {
    return client.readJson(
      Uri(path: '/study/$path', queryParameters: queryParameters),
      headers: {'Accept': 'application/json'},
      mapper: (Map<String, dynamic> json) {
        final paginator = pick(json, 'paginator').asMapOrThrow<String, dynamic>();

        return (
          studies: pick(
            paginator,
            'currentPageResults',
          ).asListOrThrow((pick) => StudyPageItem.fromJson(pick.asMapOrThrow())).toIList(),
          nextPage: pick(paginator, 'nextPage').asIntOrNull(),
        );
      },
    );
  }

  Future<(Study study, String pgn)> getStudy({
    required StudyId id,
    StudyChapterId? chapterId,
  }) async {
    final study = await client.readJson(
      Uri(
        path: (chapterId != null) ? '/study/$id/$chapterId


},
		objective_3 = {
			5,
			120
		},
		bufficon = {}
	},
	[1090505] = {
		sink_limit = 1,
		ai = 3,
		guide_desc = "",
		type = 98,
		ai_mov = 3,
		add_icon = "",
		bgm = "level03",
		exp_commander = 1,
		time_limit = 120,
		exp_commander_ratio = 30,
		dungeon_id = 1090505,
		exp = 601,
		icon = "sairenzhongxun",
		difficulty = 2,
		level = 79,
		map_id = 50009,
		limit_type = 1,
		icon_type = 2,
		name = "精英艦隊",
		effect_prefab = "",
		plot_type = 0,
		id = 1090505,
		scale = 80,
		award_display = {
			{
				2,
				56500
			},
			{
				2,
				57304
			},
			{
				2,
				54024
			},
			{
				2,
				59001
			},
			{
				2,
				54013
			}
		},
		objective_1 = {
			1
		},
		objective_2 = {
			2
		},
		objective_3 = {
			5,
			120
		},
		bufficon = {}
	},
	[1090506] = {
		sink_limit = 1,
		ai = 3,
		guide_desc = "",
		type = 98,
		ai_mov = 2,
		add_icon = "",
		bgm = "level03",
		exp_commander = 1,
		time_limit = 120,
		exp_commander_ratio = 30,
		dungeon_id = 1090506,
		exp = 601,
		icon = "sairenqingxun",
		difficulty = 2,
		level = 79,
		map_id = 50009,
		limit_type = 1,
		icon_type = 2,
		name = "精英艦隊",
		effect_prefab = "",
		plot_type = 0,
		id = 1090506,
		scale = 80,
		award_display = {
			{
				2,
				56500
			},
			{
				2,
				57304
			},
			{
				2,
				54024
			},
			{
				2,
				59001
			},
			{
				2,
				54013
			}
		},
		objective_1 = {
			1
		},
		objective_2 = {
			2
		},
		objective_3 = {
			5,
			120
		},
		bufficon = {}
	},
	[1090507] = {
		sink_limit = 1,
		ai = 3,
		guide_desc = "",
		type = 98,
		ai_mov = 3,
		add_icon = "",
		bgm = "level03",
		exp_commander = 1,
		time_limit = 120,
		exp_commander_ratio = 30,
		dungeon_id = 1090507,
		exp = 634,
		icon = "sairenqingxun",
		difficulty = 2,
		level = 84,
		map_id = 50009,
		limit_type = 1,
		icon_type = 2,
		name = "精英艦隊",
		effect_prefab = "",
		plot_type = 0,
		id = 1090507,
		scale = 80,
		award_display = {
			{
				2,
				56500
			},
			{
				2,
				57305
			},
			{
				2,
				54024
			},
			{
				2,
				59001
			},
			{
				2,
				54013
			}
		},
		objective_1 =


ecepten","relativeLink":"/nl/recepten/alle-recepten","externalLink":false,"active":false,"extension":"html"},"searchPathType":"recipe","alternateSearchType":"product","hideShowSearchTypeBox":"true","showSearchTermGenericProduct":false,"sticky":false,"searchOrigin":"recipe detail","uuid":"ac6cc430","hidden":false}" id="searchComponent-model6d1646a5">

                                    <input class="btn btn--back" type="button" value="Terug" onclick="history.back()"/>


"baz" {
		t.Fatalf("bad: %#v", resp)
	}

	// Read via API
	v, err := p.Get(ctx, storage)
	if err != nil {
		t.Fatalf("bad: %#v", err)
	}
	if v["value"] != "baz" {
		t.Fatalf("bad: %#v", v)
	}

	// Delete via HTTP
	resp, err = b.HandleRequest(ctx, &logical.Request{
		Operation: logical.DeleteOperation,
		Path:      "bar",
		Data:      nil,
		Storage:   storage,
	})
	if err != nil {
		t.Fatalf("bad: %#v", err)
	}
	if resp != nil {
		t.Fatalf("bad: %#v", resp)
	}

	// Re-read via HTTP
	resp, err = b.HandleRequest(ctx, &logical.Request{
		Operation: logical.ReadOperation,
		Path:      "bar",
		Storage:   storage,
	})
	if err != nil {
		t.Fatalf("bad: %#v", err)
	}
	if _, ok := resp.Data["value"]; ok {
		t.Fatalf("bad: %#v", resp)
	}

	// Re-read via API
	v, err = p.Get(ctx, storage)
	if err != nil {
		t.Fatalf("bad: %#v", err)
	}
	if v != nil {
		t.Fatalf("bad: %#v", v)
	}
}
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package framework

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"regexp"
	"strings"
	"time"

	"github.com/go-viper/mapstructure/v2"
	"github.com/hashicorp/go-secure-stdlib/parseutil"
	"github.com/hashicorp/go-secure-stdlib/strutil"
	"github.com/openbao/openbao/sdk/v2/helper/jsonutil"
)

// FieldData is the structure passed to the callback to handle a path
// containing the populated parameters for fields. This should be used
// instead of the raw (*vault.Request).Data to access data in a type-safe
// way.
type FieldData struct {
	Raw    map[string]interface{}
	Schema map[string]*FieldSchema
}

// Validate cycles through raw data and validates conversions in
// the schema, so we don't get an error/panic later when
// trying to get data out.  Data not in the schema is not
// an error at this point, so we don't worry about it.
func (d *FieldData) Validate() error {
	for field := range d.Raw {

		schema, ok := d.Schema[field]
		if !ok {
			continue
		}

		switch schema.Type {
		case TypeBool, TypeInt, TypeInt64, TypeMap, TypeDurationSecond, TypeSignedDurationSecond, TypeString,
			TypeLowerCaseString, TypeNameString, TypeSlice, TypeStringSlice, TypeCommaStringSlice,
			TypeKVPairs, TypeCommaIntSlice, TypeHeader, TypeFloat, TypeTime:
			_, _, err := d.getPrimitive(field, schema)
			if err != nil {
				return fmt.Errorf("error converting input for field %q: %w", field, err)
			}
		default:
			return fmt.Errorf("unknown field type %q for field %q", schema.Type, field)
		}
	}

	return nil
}

// ValidateStrict cycles through raw data and validates conversions in the
// schema. In addition to the checks done by Validate, this function ensures
// that the raw data has all of the schema's required fields and does not
// have any fields outside of the schema. It will return a non-nil error if:


IIx, IIcx, IIci.
		 * $5000 6000 - $5000 7FFF: pseudo-DMA with /DRQ
		 * $5001 0000 - $5001 1FFF: normal mode
		 * $5001 2000 - $5001 3FFF: pseudo-DMA without /DRQ
		 * GMFH says that $5000 0000 - $50FF FFFF "wraps
		 * $5000 0000 - $5001 FFFF eight times" (!)
		 * mess.org says IIci and Color Classic do not alias
		 * I/O address space.
		 */
		platform_device_register_simple("mac_scsi", 0,
			mac_scsi_old_rsrc, ARRAY_SIZE(mac_scsi_old_rsrc));
		break;
	case MAC_SCSI_LC:
		/* Addresses from Mac LC data in Designing Cards & Drivers 3ed.
		 * Also from the Developer Notes for Classic II, LC III,
		 * Color Classic and IIvx.
		 * $50F0 6000 - $50F0 7FFF: SCSI handshake
		 * $50F1 0000 - $50F1 1FFF: SCSI
		 * $50F1 2000 - $50F1 3FFF: SCSI DMA
		 */
		platform_device_register_simple("mac_scsi", 0,
			mac_scsi_ccl_rsrc, ARRAY_SIZE(mac_scsi_ccl_rsrc));
		break;
	}

	/*
	 * IDE device
	 */

	switch (macintosh_config->ide_type) {
	case MAC_IDE_QUADRA:
		platform_device_register_resndata(NULL, "pata_platform", -1,
			mac_pata_quadra_rsrc, ARRAY_SIZE(mac_pata_quadra_rsrc),
			&mac_pata_data, sizeof(mac_pata_data));
		break;
	case MAC_IDE_PB:
		platform_device_register_resndata(NULL, "pata_platform", -1,
			mac_pata_pb_rsrc, ARRAY_SIZE(mac_pata_pb_rsrc),
			&mac_pata_data, sizeof(mac_pata_data));
		break;
	case MAC_IDE_BABOON:
		platform_device_register_resndata(NULL, "pata_platform", -1,
			mac_pata_baboon_rsrc, ARRAY_SIZE(mac_pata_baboon_rsrc),
			&mac_pata_data, sizeof(mac_pata_data));
		break;
	}

	/*
	 * Ethernet device
	 */

	if (macintosh_config->ether_type == MAC_ETHER_SONIC ||
	    macintosh_config->expansion_type == MAC_EXP_PDS_COMM)
		platform_device_register_simple("macsonic", -1, NULL, 0);

	if (macintosh_config->expansion_type == MAC_EXP_PDS ||
	    macintosh_config->expansion_type == MAC_EXP_PDS_COMM)
		platform_device_register_simple("mac89x0", -1, NULL, 0);

	if (macintosh_config->ether_type == MAC_ETHER_MACE)
		platform_device_register_simple("macmace", -1, NULL, 0);

	return 0;
}

arch_initcall(mac_platform_init);


 != nil {
		t.Fatalf("gdb exited with error: %v", err)
	}

	firstLine := bytes.SplitN(got, []byte("\n"), 2)[0]
	if string(firstLine) != "Loading Go Runtime support." {
		// This can happen when using all.bash with
		// GOROOT_FINAL set, because the tests are run before
		// the final installation of the files.
		cmd := exec.Command(testenv.GoToolPath(t), "env", "GOROOT")
		cmd.Env = []string{}
		out, err := cmd.CombinedOutput()
		if err != nil && bytes.Contains(out, []byte("cannot find GOROOT")) {
			t.Skipf("skipping because GOROOT=%s does not exist", runtime.GOROOT())
		}

		_, file, _, _ := runtime.Caller(1)

		t.Logf("package testing source file: %s", file)
		t.Fatalf("failed to load Go runtime support: %s\n%s", firstLine, got)
	}

	// Extract named BEGIN...END blocks from output
	partRe := regexp.MustCompile(`(?ms)^BEGIN ([^\n]*)\n(.*?)\nEND`)
	blocks := map[string]string{}
	for _, subs := range partRe.FindAllSubmatch(got, -1) {
		blocks[string(subs[1])] = string(subs[2])
	}

	infoGoroutinesRe := regexp.MustCompile(`\*\s+\d+\s+running\s+`)
	if bl := blocks["info goroutines"]; !infoGoroutinesRe.MatchString(bl) {
		t.Fatalf("info goroutines failed: %s", bl)
	}

	printMapvarRe1 := regexp.MustCompile(`^\$[0-9]+ = map\[string\]string = {\[(0x[0-9a-f]+\s+)?"abc"\] = (0x[0-9a-f]+\s+)?"def", \[(0x[0-9a-f]+\s+)?"ghi"\] = (0x[0-9a-f]+\s+)?"jkl"}$`)
	printMapvarRe2 := regexp.MustCompile(`^\$[0-9]+ = map\[string\]string = {\[(0x[0-9a-f]+\s+)?"ghi"\] = (0x[0-9a-f]+\s+)?"jkl", \[(0x[0-9a-f]+\s+)?"abc"\] = (0x[0-9a-f]+\s+)?"def"}$`)
	if bl := blocks["print mapvar"]; !printMapvarRe1.MatchString(bl) &&
		!printMapvarRe2.MatchString(bl) {
		t.Fatalf("print mapvar failed: %s", bl)
	}

	// 2 orders, and possible differences in spacing.
	sliceMapSfx1 := `map[string][]string = {["e"] = []string = {"f", "g", "h"}, ["a"] = []string = {"b", "c", "d"}}`
	sliceMapSfx2 := `map[string][]string = {["a"] = []string = {"b", "c", "d"}, ["e"] = []string = {"f", "g", "h"}}`
	if bl := strings.ReplaceAll(blocks["print slicemap"], "  ", " "); !strings.HasSuffix(bl, sliceMapSfx1) && !strings.HasSuffix(bl, sliceMapSfx2) {
		t.Fatalf("print slicemap failed: %s", bl)
	}

	chanIntSfx := `chan int = {99, 11}`
	if bl := strings.ReplaceAll(blocks["print chanint"], "  ", " "); !strings.HasSuffix(bl, chanIntSfx) {
		t.Fatalf("print chanint failed: %s", bl)
	}

	chanStrSfx := `chan string = {"spongepants", "squarebob"}`
	if bl := strings.ReplaceAll(blocks["print chanstr"], "  ", " "); !strings.HasSuffix(bl, chanStrSfx) {
		t.Fatalf("print chanstr failed: %s", bl)
	}

	strVarRe := regexp.MustCompile(`


ror %q", err)
	}

	if !cmp.Equal(got, exp) {
		t.Fatalf("unexpected values: -got/+exp\n%s", cmp.Diff(got, exp))
	}
}

func TestIntegerArrayDecodeAll_Descending(t *testing.T) {
	enc := NewIntegerEncoder(16)
	exp := []int64{
		7094, 4472, 1850,
	}

	for _, v := range exp {
		enc.Write(v)
	}

	b, err := enc.Bytes()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	if b[0]>>4 != intCompressedRLE {
		t.Fatalf("unexpected encoding format: expected simple, got %v", b[0]>>4)
	}

	// Should use 1 header byte, 8 byte first value, 1 var-byte for delta and 1 var-byte for
	// count of deltas in this particular RLE.
	if exp := 12; len(b) != exp {
		t.Fatalf("encoded length mismatch: got %v, exp %v", len(b), exp)
	}

	got, err := IntegerArrayDecodeAll(b, nil)
	if err != nil {
		t.Fatalf("unexpected decode error %q", err)
	}

	if !cmp.Equal(got, exp) {
		t.Fatalf("unexpected values: -got/+exp\n%s", cmp.Diff(got, exp))
	}
}

func TestIntegerArrayDecodeAll_Flat(t *testing.T) {
	enc := NewIntegerEncoder(16)
	exp := []int64{
		1, 1, 1, 1,
	}

	for _, v := range exp {
		enc.Write(v)
	}

	b, err := enc.Bytes()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	if b[0]>>4 != intCompressedRLE {
		t.Fatalf("unexpected encoding format: expected simple, got %v", b[0]>>4)
	}

	// Should use 1 header byte, 8 byte first value, 1 var-byte for delta and 1 var-byte for
	// count of deltas in this particular RLE.
	if exp := 11; len(b) != exp {
		t.Fatalf("encoded length mismatch: got %v, exp %v", len(b), exp)
	}

	got, err := IntegerArrayDecodeAll(b, nil)
	if err != nil {
		t.Fatalf("unexpected decode error %q", err)
	}

	if !cmp.Equal(got, exp) {
		t.Fatalf("unexpected values: -got/+exp\n%s", cmp.Diff(got, exp))
	}
}

func TestIntegerArrayDecodeAll_MinMax(t *testing.T) {
	enc := NewIntegerEncoder(2)
	exp := []int64{
		math.MinInt64, math.MaxInt64,
	}

	for _, v := range exp {
		enc.Write(v)
	}

	b, err := enc.Bytes()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	if b[0]>>4 != intUncompressed {
		t.Fatalf("unexpected encoding format: expected simple, got %v", b[0]>>4)
	}

	if exp := 17; len(b) != exp {
		t.Fatalf("encoded length mismatch: got %v, exp %v", len(b), exp)
	}

	got, err := IntegerArrayDecodeAll(b, nil)
	if err != nil {
		t.Fatalf("unexpected decode error %q", err)
	}

	if !cmp.Equal(got, exp) {
		t.Fatalf("unexpected values: -got/+exp\n%s", cmp.Diff(got, exp))
	}
}

func TestIntegerArrayDecodeAll_Quick(t *testing.T) {
	quick.Check


/ 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])\n  reduce: function reduce(callbackfn /* , initialValue */) {\n    return $reduce(this, callbackfn, arguments.length, arguments[1], false);\n  }\n});\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/core-js/modules/es6.array.reduce.js\n// module id = 569\n// module chunks = 0","'use strict';\nvar $export = require('./_export');\nvar $reduce = require('./_array-reduce');\n\n$export($export.P + $export.F * !require('./_strict-method')([].reduceRight, true), 'Array', {\n  // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])\n  reduceRight: function reduceRight(callbackfn /* , initialValue */) {\n    return $reduce(this, callbackfn, arguments.length, arguments[1], true);\n  }\n});\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/core-js/modules/es6.array.reduce-right.js\n// module id = 570\n// module chunks = 0","'use strict';\nvar $export = require('./_export');\nvar $indexOf = require('./_array-includes')(false);\nvar $native = [].indexOf;\nvar NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;\n\n$export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($native)), 'Array', {\n  // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])\n  indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {\n    return NEGATIVE_ZERO\n      // convert -0 to +0\n      ? $native.apply(this, arguments) || 0\n      : $indexOf(this, searchElement, arguments[1]);\n  }\n});\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/core-js/modules/es6.array.index-of.js\n// module id = 571\n// module chunks = 0","'use strict';\nvar $export = require('./_export');\nvar toIObject = require('./_to-iobject');\nvar toInteger = require('./_to-integer');\nvar toLength = require('./_to-length');\nvar $native = [].lastIndexOf;\nvar NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;\n\n$export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($native)), 'Array', {\n  // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])\n  lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {\n    // convert -0 to +0\n    if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0;\n    var O = toIObject(this);\n    var length = toLength(O.length);\n    var index = length - 1;\n    if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1]));\n    if (index < 0) index = length + index;\n    for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0;\n    return -1;\n  }\n});\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/core-js/modules/es6.array.last-index-of.js\n


import json
import os.path as osp
import re

from datasets import Dataset

from opencompass.openicl.icl_evaluator import BaseEvaluator
from opencompass.registry import (ICL_EVALUATORS, LOAD_DATASET,
                                  TEXT_POSTPROCESSORS)

from .base import BaseDataset

@LOAD_DATASET.register_module()
class BBHDataset(BaseDataset):

    @staticmethod
    def load(path: str, name: str):
        with open(osp.join(path, f'{name}.json'), 'r') as f:
            data = json.load(f)['examples']
        dataset = Dataset.from_list(data)
        return dataset

@TEXT_POSTPROCESSORS.register_module('bbh-mcq')
def bbh_mcq_postprocess(text: str) -> str:
    ans = text
    ans_line = ans.split('answer is ')
    if len(ans_line) != 1:
        ans = ans_line[1].strip()
    match = re.search(r'\(([A-Z])\)*', ans)
    if match:
        return match.group(1)
    match = re.search(r'([A-Z])', ans)
    if match:
        return match.group(1)
    return ans

@TEXT_POSTPROCESSORS.register_module('bbh-freeform')
def bbh_freeform_postprocess(text: str) -> str:
    ans = text
    ans_line = ans.split('answer is ')
    if len(ans_line) != 1:
        ans = ans_line[1].strip()
    ans = ans.split('\n')[0]
    if ans.endswith('.'):
        ans = ans[:-1]
    return ans

@ICL_EVALUATORS.register_module()
class BBHEvaluator(BaseEvaluator):

    def score(self, predictions, references):
        if len(predictions) != len(references):
            return {
                'error': 'predictions and references have different '
                'length'
            }

        predictions = [bbh_freeform_postprocess(pred) for pred in predictions]

        details = []
        cnt = 0
        for pred, ref in zip(predictions, references):
            detail = {'pred': pred, 'answer': ref, 'correct': False}
            if pred == ref:
                cnt += 1
                detail['correct'] = True
            details.append(detail)

        score = cnt / len(predictions) * 100

        return {'score': score, 'details': details}

@ICL_EVALUATORS.register_module()
class BBHEvaluator_mcq(BaseEvaluator):

    def score(self, predictions, references):
        if len(predictions) != len(references):
            return {
                'error': 'predictions and references have different '
                'length'
            }
        details = []
        cnt = 0
        for pred, ref in zip(predictions, references):
            detail = {'pred': pred, 'answer': ref, 'correct': False}
            if pred == ref:
                cnt += 1
                detail['correct'] = True
            details.append(detail)

        score = cnt / len(predictions) * 100

        return {'score': score, 'details': details}


test1:
	;         0123456789012345678901234567890123456789
	.byte 0,10,"PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS!",0
test2:
	.byte 0,30,"pack my box with five dozen liquor jugs?",0
test3:
	.byte 9,50,"This is a HGR font test.",0
test4:
	.byte 0,100,"0123456789)(*&^%$#@!`~<>,./';:[]{}\|_+=",0
test5:
	.byte 0,120,"@/\/\/\/\______ |",0

	.include "font_vmw_1x8.s"
	.include "fonts/a2_lowercase_font.inc"

hposn_low	= $1713	; 0xC0 bytes (lifetime, used by DrawLargeCharacter)
hposn_high	= $1800	; 0xC0 bytes (lifetime, used by DrawLargeCharacter)

	.include "hgr_table.s"


ne"><semantics id="p9.16.m16.1a"><mrow id="p9.16.m16.1.1" xref="p9.16.m16.1.1.cmml"><mi mathvariant="normal" id="p9.16.m16.1.1.3" xref="p9.16.m16.1.1.3.cmml">Γ</mi><mo lspace="0em" rspace="0em" id="p9.16.m16.1.1.2" xref="p9.16.m16.1.1.2.cmml"></mo><mrow id="p9.16.m16.1.1.1.1" xref="p9.16.m16.1.1.1.1.1.cmml"><mo stretchy="false" id="p9.16.m16.1.1.1.1.2" xref="p9.16.m16.1.1.1.1.1.cmml">(</mo><mrow id="p9.16.m16.1.1.1.1.1" xref="p9.16.m16.1.1.1.1.1.cmml"><msub id="p9.16.m16.1.1.1.1.1.2" xref="p9.16.m16.1.1.1.1.1.2.cmml"><mi id="p9.16.m16.1.1.1.1.1.2.2" xref="p9.16.m16.1.1.1.1.1.2.2.cmml">𝐪</mi><mn id="p9.16.m16.1.1.1.1.1.2.3" xref="p9.16.m16.1.1.1.1.1.2.3.cmml">0</mn></msub><mo id="p9.16.m16.1.1.1.1.1.1" xref="p9.16.m16.1.1.1.1.1.1.cmml">+</mo><mi id="p9.16.m16.1.1.1.1.1.3" xref="p9.16.m16.1.1.1.1.1.3.cmml">𝐐</mi></mrow><mo stretchy="false" id="p9.16.m16.1.1.1.1.3" xref="p9.16.m16.1.1.1.1.1.cmml">)</mo></mrow></mrow><annotation-xml encoding="MathML-Content" id="p9.16.m16.1b"><apply id="p9.16.m16.1.1.cmml" xref="p9.16.m16.1.1"><times id="p9.16.m16.1.1.2.cmml" xref="p9.16.m16.1.1.2"></times><ci id="p9.16.m16.1.1.3.cmml" xref="p9.16.m16.1.1.3">Γ</ci><apply id="p9.16.m16.1.1.1.1.1.cmml" xref="p9.16.m16.1.1.1.1"><plus id="p9.16.m16.1.1.1.1.1.1.cmml" xref="p9.16.m16.1.1.1.1.1.1"></plus><apply id="p9.16.m16.1.1.1.1.1.2.cmml" xref="p9.16.m16.1.1.1.1.1.2"><csymbol cd="ambiguous" id="p9.16.m16.1.1.1.1.1.2.1.cmml" xref="p9.16.m16.1.1.1.1.1.2">subscript</csymbol><ci id="p9.16.m16.1.1.1.1.1.2.2.cmml" xref="p9.16.m16.1.1.1.1.1.2.2">𝐪</ci><cn type="integer" id="p9.16


v[0].copy(v[0]);
		U.v[0].invmod2m();

		for (i=1;i<n;i<<=1)
		{
			b.copy(this); b.mod2m(i);
			t=mul(U,b);

			t.shrw(i); b.copy(t);
			c.copy(this); c.shrw(i); c.mod2m(i);
			c.lmul(U); c.mod2m(i);

			b.add(c); b.norm();
			b.lmul(U); b.mod2m(i);

			c.one(); c.shlw(i); b.revsub(c); b.norm();
			b.shlw(i);
			U.add(b);
		}
		U.norm();
		return U;
	}

	public void random(RAND rng)
	{
		int n=length;
		for (int i=0;i<n;i++)
		{
			v[i].copy(BIG.random(rng));
		}
	/* make sure top bit is 1 */
		while (v[n-1].nbits()<CONFIG_BIG.MODBYTES*8) v[n-1].copy(BIG.random(rng));
	}

	/* generate random x */
	public void randomnum(FF p,RAND rng)
	{
		int n=length;
		FF d=new FF(2*n);

		for (int i=0;i<2*n;i++)
		{
			d.v[i].copy(BIG.random(rng));
		}
		copy(d.dmod(p));
	}

	/* this*=y mod p */
	public void modmul(FF y,FF p,FF nd)
	{
		if (pexceed(v[length-1],y.v[y.length-1])) mod(p);
		int n=p.length;
		if (n==1)
		{
			DBIG d=BIG.mul(this.v[0],y.v[0]);
			this.v[0].copy(BIG.monty(p.v[0],(BIG.cast_to_chunk(1)<<CONFIG_BIG.BASEBITS)-nd.v[0].w[0],d));
		}
		else
		{
			FF d=mul(this,y);
			copy(d.reduce(p,nd));
		}
	}

	/* this*=y mod p */
	public void modsqr(FF p,FF nd)
	{
		if (sexceed(v[length-1])) mod(p);
		int n=p.length;
		if (n==1)
		{
			DBIG d=BIG.sqr(this.v[0]);
			this.v[0].copy(BIG.monty(p.v[0],(BIG.cast_to_chunk(1)<<CONFIG_BIG.BASEBITS)-nd.v[0].w[0],d));

		}
		else
		{
			FF d=sqr(this);
			copy(d.reduce(p,nd));
		}
	}

	/* this=this^e mod p using side-channel resistant Montgomery Ladder, for large e */
	public void skpow(FF e,FF p)
	{
		int i,b,n=p.length;
		FF R0=new FF(n);
		FF R1=new FF(n);
		FF ND=p.invmod2m();

		mod(p);
		R0.one();
		R1.copy(this);
		R0.nres(p);
		R1.nres(p);

		for (i=8*CONFIG_BIG.MODBYTES*n-1;i>=0;i--)
		{
			b=e.v[i/BIG.BIGBITS].bit(i%BIG.BIGBITS);
			copy(R0);
			modmul(R1,p,ND);

			cswap


170, 60, 180, 30));

        jLabel4.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(51, 51, 51));
        jLabel4.setText("APELLIDOS");
        jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 40, 70, 20));
        jPanel1.add(txtApellido, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 60, 180, 30));
        jPanel1.add(txtTratamiento, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 160, 180, 30));

        jLabel5.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(51, 51, 51));
        jLabel5.setText("TRATAMIENTO");
        jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 140, 180, 20));

        jLabel6.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(51, 51, 51));
        jLabel6.setText("DESCRIPCION");
        jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 140, 180, 20));
        jPanel1.add(txtOdontologo, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 220, 180, 30));

        jLabel7.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(51, 51, 51));
        jLabel7.setText("FECHA DE CREACION");
        jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 260, 180, 20));

        jtxaDesc.setColumns(20);
        jtxaDesc.setRows(5);
        jScrollPane1.setViewportView(jtxaDesc);

        jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 160, 220, -1));
        jPanel1.add(jdateCreacion, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 280, 180, 40));

        jLabel8.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jLabel8.setForeground(new java.awt.Color(51, 51, 51));
        jLabel8.setText("ODONTÓLOGO");
        jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 200, 180, 20));
        jPanel1.add(txtId, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 160, 60, 30));

        jLabel2.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(51, 51, 51));
        jLabel2.setText("DNI");
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 40, 70, 20));
        jPanel1.add(txtDeuda, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 280, 80, 30));

        jLabel9.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jLabel9.setForeground(new java.awt.Color(51, 51, 51));
        jLabel9.setText("DEUDA");
        jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 260, 80, 20));

        jLabel10.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jLabel10.setForeground(new java.awt.Color(51, 51, 51));
        jLabel10.setText("


.61-8.98 6.96-13.62 10.19-22.24 15.03-40.6 35.96-52.04 60.28-9.36 19.74-14.55 41.97-11.81 63.84 1.95 13.73 8.74 27.67 20.96 35.01 12.94 7.99 29.14 8.09 43.61 5.11 32.9-7.47 61.61-28.97 81.28-56 20.5-27.6 30.61-62.38 29.25-96.64-.52-7.52-1.58-15-1.67-22.55 8.02 19.54 14.87 39.83 16.7 61.01 2.01 14.32.75 28.84-1.62 43.02-1.92 11.02-5.69 21.58-7.81 32.53 20.36-22.73 34.17-51.24 39.46-81.31 5.72-35.37.58-72.36-14.25-104.95 20.84 32.12 32.43 69.79 35.81 107.8.5 12.77.5 25.58 0 38.34-2.91 34.26-12.97 67.95-29.76 98-26.2 47.48-68.2 85.89-117.54 108.32-78.52 36.34-175.2 31.41-248.72-14.72-38.84-23.78-71.06-58.32-91.68-98.96C10.72 337.43 2.04 305.5 0 273.13V241.7c3.94-69.97 40.99-136.32 96.24-178.89m222.65 80.57c5.51-.8 10.82-2.57 16.02-4.5 4.99-1.77 9.27-5.95 10.35-11.25-8.91 5-17.95 9.95-26.37 15.75z"],php:[640,512,[],"f457","M320 104.5c171.4 0 303.2 72.2 303.2 151.5S491.3 407.5 320 407.5c-171.4 0-303.2-72.2-303.2-151.5S148.7 104.5 320 104.5m0-16.8C143.3 87.7 0 163 0 256s143.3 168.3 320 168.3S640 349 640 256 496.7 87.7 320 87.7zM218.2 242.5c-7.9 40.5-35.8 36.3-70.1 36.3l13.7-70.6c38 0 63.8-4.1 56.4 34.3zM97.4 350.3h36.7l8.7-44.8c41.1 0 66.6 3 90.2-19.1 26.1-24 32.9-66.7 14.3-88.1-9.7-11.2-25.3-16.7-46.5-16.7h-70.7L97.4 350.3zm185.7-213.6h36.5l-8.7 44.8c31.5 0 60.7-2.3 74.8 10.7 14.8 13.6 7.7 31-8.3 113.1h-37c15.4-79.4 18.3-86 12.7-92-5.4-5.8-17.7-4.6-47.4-4.6l-18.8 96.6h-36.5l32.7-168.6zM505 242.5c-8 41.1-36.7 36.3-70.1 36.3l13.7-70.6c38.2 0 63.8-4.1 56.4 34.3zM384.2 350.3H421l8.7-44.8c43.2


    {
                    format_header = 10000;
                    break;
                  }
                }
                buf_puts(rx, i);
                format_header += i;
                rx_len        -= i;
              }
              break;
            case FORMAT_WMA:
              if(format_header < 4000) //WMA header is around 5 kByte
              {
                buf_puts(rx, rx_len);
                format_header += rx_len;
                rx_len         = 0;
              }
              else if(format_header < 10000)
              {
                for(i=0; i<rx_len; i++)
                {
                  if(((rx_len-i) >= 3) &&
                      (rx[i+0] == 0x82) &&
                      (rx[i+1] == 0x00) &&
                      (rx[i+2] == 0x00)) ///WMA sync: 0x82 0x00 0x00
                  {
                    format_header = 10000;
                    break;
                  }
                }
                buf_puts(rx, i);
                format_header += i;
                rx_len        -= i;
              }
              break;
          }
        }
      }
      break;

    case SHOUTCAST_OPEN:
      shoutcast_status = SHOUTCAST_HEADER;
      parse_header     = 0;
      format           = FORMAT_UNKNOWN;
      format_header    = 0;
      if(fm_size() == 0) //no F-RAM
      {
        skip = 32; //default skip
      }
      else
      {
        skip = 0;
      }
      station_setbitrate(0); //set default bitrate / buffer limits
      menu_setformat(FORMAT_UNKNOWN);
      tx_len = sprintf((char*)tx, "GET %s HTTP/1.0\r\n"
                                  "Host: %s\r\n"
                                  "User-Agent: "APPNAME"\r\n"
                                  "Icy-MetaData: 0\r\n"
                                  "Connection: Keep-Alive\r\n"
                                  "\r\n",
                                  gbuf.station.file, gbuf.station.host);
      tcp_send(idx, tx_len, 0);
      break;

    case SHOUTCAST_CLOSE:
      shoutcast_status = SHOUTCAST_CLOSED;
      tcp_abort(idx);
      tcp_send(idx, 0, 0);
      break;

    case SHOUTCAST_CLOSED:
      break;
  }

  return;
}


ool_stargate_shield_imm = When this is enabled, the owner of the shield can always go or shoot through\nno matter if he was inside the shield when it was turned on or not
stool_stargate_shield_db = Draw Bubble
stool_stargate_shield_db_desc = Draw a bubble when hit?
stool_stargate_shield_se = Show Effect when Passing Shield
stool_stargate_shield_se_desc = Draws the shield effect, when something passes it
stool_stargate_shield_co = Containment
stool_stargate_shield_co_desc = Enable this to keep things inside a shield instead of keeping it away
stool_stargate_shield_an = Anti Noclip
stool_stargate_shield_an_desc = People can't noclip in the shield?

// Shield identifier
stool_stargate_shield_ident_spawner = Shield Identifier Spawner
stool_stargate_shield_ident_create = Creates a Shield Identifier
stool_stargate_shield_ident_desc = Left click, to spawn a Shield Identifier
stool_stargate_shield_ident_undone = Shield Identifier removed
stool_stargate_shield_ident_cleanup = Shield Identifiers
stool_stargate_shield_ident_cleaned = Removed all Shield Identifiers
stool_stargate_shield_ident_limit = Hit the Shield Identifier limit
stool_stargate_shield_ident_text =[[If device active and his frequency is the same of the shield, then this allow constrained entities to device (for example welded) pass through the shield.

Also when we shoot and the shield fire frequency equal to the fire frequency of the weapon, then:
Shield take 25%% of damage, but if the fire frequency wasn't the same, the shield take in 5 times more damage.
There possible difference in fire frequency of 50 more or less.

By default shield has both frequencies equal to 0.
Weapon frequencies:
850 - ag3, asgard/ori beam weapons
575 - asuran gate weapon, ring beam
325 - all other cap energy weapons (player weapons, destiny turrets etc)
]]

//Atlantis Light
stool_atlantis_light_colour = Light Colour
stool_atlantis_light_spawner = Atlantis Light Spawner
stool_atlantis_light_create = Spawns an Atlantis Light
stool_atlantis_light_desc = Left click to spawn the light
stool_atlantis_light_undone = Atlantis Light removed
stool_atlantis_light_cleanup = Atlantis Lights
stool_atlantis_light_cleaned = Removed all Atlantis Lights

// Supergate DHD
stool_supergate_dhd_spawner = Supergate DHD Spawner
stool_supergate_dhd_create = Creates a Supergate DHD
stool_supergate_dhd_desc = Left click, to spawn a Supergate DHD
stool_supergate_dhd_undone = Supergate DHD removed
stool_supergate_dhd_cleanup = Supergate DHDs
stool_supergate_dhd_cleaned = Removed all Supergate DHDs
stool_supergate_dhd_limit = Hit the Supergate DHD limit
stool_supergate_dhd_err = You are not pointing at a Supergate!
stool_supergate_dhd_exs = Supergate DHD is already exist on this Supergate!

// Tampered ZPM
stool_tampered_zpm_spawner = Tampered ZPM Spawner
stool_tampered_zpm_create = Creates a Tampered ZPM
stool_tampered_zpm_desc = Left click, to spawn a Tampered ZPM
stool_tampered_zpm_undone = Tampered ZPM removed
stool_tampered_zpm_cleanup = Tampered ZPM
stool_tampered_zpm_cleaned = Removed


    let mut connected: Vec<usize> = vec![];
    for y in 0..area.height() {
        connected.clear();
        for x in 0..area.width() {
            let sym = area.symbol_at(x, y);
            if sym == Symbol::Corner {
                for prev in connected.iter() {
                    conns.lines.insert(Line{x1: prev.clone(), y1: y, x2: x, y2: y});
                }
                if let Some(last) = connected.last() {
                    let cf = conns.points.get_mut(&Point{x: last.clone(), y: y}).unwrap();
                    *cf = *cf | CONN_RIGHT;
                }
                let cf = conns.points.entry(Point{x: x, y: y}).or_insert(0);
                if connected.len() > 0 {
                    *cf = *cf | CONN_LEFT;
                }
                connected.push(x);
            } else if sym != Symbol::Connect {
                connected.clear(); // End of connected bit.
            }
        }
    }
    conns
}
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::blob_json_generator::BlobJsonGenerator;
use crate::util::read_config;
use crate::util::write_json_file;
use anyhow::anyhow;
use anyhow::Context;
use anyhow::Result;
use assembly_tool::SdkToolProvider;
use assembly_tool::ToolProvider;
use ffx_assembly_args::SizeCheckArgs;
use fuchsia_hash::Hash;
use fuchsia_pkg::PackageManifest;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::Path;
use std::path::PathBuf;
use url::Url;

/// Blob information. Entry of the "blobs.json" file.
#[derive(Debug, Deserialize, PartialEq)]
pub struct BlobJsonEntry {
    /// Hash of the head for the blob tree.
    pub merkle: Hash,
    /// Size of the content in bytes, once compressed and aligned.
    pub size: u64,
}

/// Root of size checker JSON configuration.
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct BudgetConfig {
    /// Apply a size budget to packages.
    #[serde(default)]
    pub package_set_budgets: Vec<PackageSetBudget>,
    /// Apply a size budget to blobs identified by file name.
    /// Matched blobs are excluded from the package accounting.
    /// This takes apart the widely shared resource in their own budget.
    #[serde(default)]
    pub resource_budgets: Vec<ResourceBudget>,
    /// The total amount of bytes equal to the sum of all individual budgets.
    #[serde(default)]
    pub total_budget_bytes: Option<u64>,
}

/// Size budget for a set of packages.
/// Part of JSON configuration.
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct PackageSetBudget {
    /// Human readable name of the package set.
    pub name: String,
    /// Number of bytes allotted for the packages of this group.
    pub budget_bytes: u64,
    /// Allowed usage increase allowed for a given commit.
    pub creep_budget_bytes: u64,
    /// List of paths to `package_manifest.json` files for each package of the set of the group.
    pub packages: Vec<PathBuf>,
    /// Blobs are de-duplicated by hash across the packages of this set.
    /// This is intended to approximate the process of merging packages.
    pub merge: bool,
}

/// Size budget for a set of files matched by path.
/// Part of JSON configuration.
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct Resourc


_table,R_INIT_DOXREQ)

#if CFG_MULTI_CPUS
		SPIN_UNLOCK(cfe_spinlock,t0)
#endif

		#
		# Restore the saved registers.
		#

		LR	k1,CAE_K1SAVE(sp)
		LR	k0,CAE_K0SAVE(sp)
		LR	s7,CAE_S7SAVE(sp)
		LR	s6,CAE_S6SAVE(sp)
		LR	s5,CAE_S5SAVE(sp)
		LR	s4,CAE_S4SAVE(sp)
		LR	s3,CAE_S3SAVE(sp)
		LR	s2,CAE_S2SAVE(sp)
		LR	s1,CAE_S1SAVE(sp)
		LR	s0,CAE_S0SAVE(sp)

		LR	ra,CAE_RASAVE(sp)	# unwind the stack
		LR	gp,CAE_GPSAVE(sp)

		LR	t0,CAE_SRSAVE(sp)	# old interrupt mask

		add	sp,CAE_STKSIZE		# restore old stack pointer

		mtc0	t0,C0_SR		# restore interrupts
		HAZARD
		j	ra
		nop

END(cpu_apientry)

/*  *********************************************************************
    *  CPU_KSEG0_SWITCH
    *
    *  Hack the return address so we will come back in KSEG0
    *
    *  Input parameters:
    *  	   nothing
    *
    *  Return value:
    *  	   nothing
    ********************************************************************* */

LEAF(cpu_kseg0_switch)

		and	ra,(K0SIZE-1)
		or	ra,K0BASE
		jr	ra

END(cpu_kseg0_switch)

/*  *********************************************************************
    *  _GETSTATUS()
    *
    *  Read the STATUS register into v0
    *
    *  Input parameters:
    *  	   nothing
    *
    *  Return value:
    *  	   v0 - Status register
    ********************************************************************* */

LEAF(_getstatus)

		mfc0	v0,C0_SR
		j	ra
END(_getstatus)

/*  *********************************************************************
    *  _SETSTATUS()
    *
    *  Set the STATUS register to the value in a0
    *
    *  Input parameters:
    *  	   nothing
    *
    *  Return value:
    *  	   v0 - Status register
    ********************************************************************* */

LEAF(_setstatus)

		mtc0	a0,C0_SR
		j	ra
END(_setstatus)

/*  *********************************************************************
    *  _GETCAUSE()
    *
    *  Read the CAUSE register into v0
    *
    *  Input parameters:
    *  	   nothing
    *
    *  Return value:
    *  	   v0 - Cause register
    ********************************************************************* */

LEAF(_getcause)

		mfc0	v0,C0_CAUSE
		j	ra
END(_getcause)

/*  *********************************************************************
    *  _GETTICKS()
    *
    *  Read the COUNT regi


-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Returns the specified NodeGroup. Get a list of available NodeGroups by making a list() request.
   * Note: the "nodes" field should not be used. Use nodeGroups.listNodes instead.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (NodeGroupsClient nodeGroupsClient = NodeGroupsClient.create()) {
   *   String project = "project-309310695";
   *   String zone = "zone3744684";
   *   String nodeGroup = "nodeGroup443599261";
   *   NodeGroup response = nodeGroupsClient.get(project, zone, nodeGroup);
   * }
   * }

   *
   * @param project Project ID for this request.
   * @param zone The name of the zone for this request.
   * @param nodeGroup Name of the node group to return.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final NodeGroup get(String project, String zone, String nodeGroup) {
    GetNodeGroupRequest request =
        GetNodeGroupRequest.newBuilder()
            .setProject(project)
            .setZone(zone)
            .setNodeGroup(nodeGroup)
            .build();
    return get(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Returns the specified NodeGroup. Get a list of available NodeGroups by making a list() request.
   * Note: the "nodes" field should not be used. Use nodeGroups.listNodes instead.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (NodeGroupsClient nodeGroupsClient = NodeGroupsClient.create()) {
   *   GetNodeGroupRequest request =
   *       GetNodeGroupRequest.newBuilder()
   *           .setNodeGroup("nodeGroup443599261")
   *           .setProject("project-309310695")
   *           .setZone("zone3744684")
   *           .build();
   *   NodeGroup response = nodeGroupsClient.get(request);
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final NodeGroup get(GetNodeGroupRequest request) {
    return getCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * Returns the specified NodeGroup. Get a list of available NodeGroups by making a list() request.
   * Note: the "nodes" field should not be used. Use nodeGroups.listNodes instead.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_cl


t") );
      if (dict && size!=dict->get_shape_count())
        G_THROW( ERR_MSG("JB2Image.bad_dict") );
    }
}

void
JB2Dict::JB2Codec::Decode::code_image_size(JB2Dict &jim)
{
  int w=CodeNum(0, BIGPOSITIVE, image_size_dist);
  int h=CodeNum(0, BIGPOSITIVE, image_size_dist);
  if (w || h)
    G_THROW( ERR_MSG("JB2Image.bad_dict2") );
  JB2Codec::code_image_size(jim);
}

void
JB2Dict::JB2Codec::code_image_size(JB2Dict &)
{
  last_left = 1;
  last_row_left = 0;
  last_row_bottom = 0;
  last_right = 0;
  fill_short_list(last_row_bottom);
  gotstartrecordp = 1;
}

void
JB2Dict::JB2Codec::Decode::code_image_size(JB2Image &jim)
{
  image_columns=CodeNum(0, BIGPOSITIVE, image_size_dist);
  image_rows=CodeNum(0, BIGPOSITIVE, image_size_dist);
  if (!image_columns || !image_rows)
    G_THROW( ERR_MSG("JB2Image.zero_dim") );
  jim.set_dimension(image_columns, image_rows);
  JB2Codec::code_image_size(jim);
}

void
JB2Dict::JB2Codec::code_image_size(JB2Image &)
{
  last_left = 1 + image_columns;
  last_row_left = 0;
  last_row_bottom = image_rows;
  last_right = 0;
  fill_short_list(last_row_bottom);
  gotstartrecordp = 1;
}

inline int
JB2Dict::JB2Codec::Decode::get_diff(int,NumContext &rel_loc)
{
   return CodeNum(BIGNEGATIVE, BIGPOSITIVE, rel_loc);
}

void
JB2Dict::JB2Codec::code_relative_location(JB2Blit *jblt, int rows, int columns)
{
  // Check start record
  if (!gotstartrecordp)
    G_THROW( ERR_MSG("JB2Image.no_start") );
  // Find location
  int bottom=0, left=0, top=0, right=0;
  int x_diff, y_diff;
  if (encoding)
    {
      left = jblt->left + 1;
      bottom = jblt->bottom + 1;
      right = left + columns - 1;
      top = bottom + rows - 1;
    }
  // Code offset type
  int new_row=CodeBit((left<last_left), offset_type_dist);
  if (new_row)
    {
      // Begin a new row
      x_diff=get_diff(left-last_row_left,rel_loc_x_last);
      y_diff=get_diff(top-last_row_bottom,rel_loc_y_last);
      if (!encoding)
        {
          left = last_row_left + x_diff;
          top = last_row_bottom + y_diff;
          right = left + columns - 1;
          bottom = top - rows + 1;
        }
      last_left = last_row_left = left;
      last_right = right;
      last_bottom = last_row_bottom = bottom;
      fill_short_list(bottom);
    }
  else
    {
      // Same row
      x_diff=get_diff(left-last_right,rel_loc_x_current);
      y_diff=get_diff(bottom-last_bottom,rel_loc_y_current);
      if (!encoding)
        {
          left = last_right + x_diff;
          bottom = last_bottom + y_diff;


> m.y.y && m.x.x > m.z.z -> {
                val s = 2.0f * sqrt(1.0f + m.x.x - m.y.y - m.z.z)
                Quaternion(
                    0.25f * s,
                    (m.y.x + m.x.y) / s,
                    (m.z.x + m.x.z) / s,
                    (m.y.z - m.z.y) / s
                )
            }
            m.y.y > m.z.z -> {
                val s = 2.0f * sqrt(1.0f + m.y.y - m.x.x - m.z.z)
                Quaternion(
                    (m.y.x + m.x.y) / s,
                    0.25f * s,
                    (m.z.y + m.y.z) / s,
                    (m.z.x - m.x.z) / s
                )
            }
            else -> {
                val s = 2.0f * sqrt(1.0f + m.z.z - m.x.x - m.y.y)
                Quaternion(
                    (m.z.x + m.x.z) / s,
                    (m.z.y + m.y.z) / s,
                    0.25f * s,
                    (m.x.y - m.y.x) / s
                )
            }
        }
    )
}

fun normal(m: Mat4) = scale(1.0f / Float3(length2(m.right), length2(m.up), length2(m.forward))) * m

fun lookAt(eye: Float3, target: Float3, up: Float3 = Float3(z = 1.0f)): Mat4 {
    return lookTowards(eye, target - eye, up)
}

fun lookTowards(eye: Float3, forward: Float3, up: Float3 = Float3(z = 1.0f)): Mat4 {
    val f = normalize(forward)
    val r = normalize(f x up)
    val u = normalize(r x f)
    return Mat4(Float4(r), Float4(u), Float4(-f), Float4(eye, 1.0f))
}

fun perspective(fov: Float, ratio: Float, near: Float, far: Float): Mat4 {
    val t = 1.0f / tan(radians(fov) * 0.5f)
    val a = (far + near) / (far - near)
    val b = (2.0f * far * near) / (far - near)
    val c = t / ratio
    return Mat4(Float4(x = c), Float4(y = t), Float4(z = a, w = 1.0f), Float4(z = -b))
}

fun ortho(l: Float, r: Float, b: Float, t: Float, n: Float, f: Float) = Mat4(
    Float4(x = 2.0f / (r - l)),
    Float4(y = 2.0f / (t - b)),
    Float4(z = -2.0f / (f - n)),
    Float4(
        -(r + l) / (r - l),
        -(t + b) / (t - b),
        -(f + n) / (f - n),
        1.0f
    )
)
/*
 * MIT License
 *
 * Copyright (c) 2021 Romain Guy
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE


c="./scalable/gtk-unindent-rtl.svg" alt="gtk-unindent-rtl.svg">

gtk-unindent-rtl.svg

(format-indent-more.svg)

gtk-yes.png

gtk-yes.png

gtk-yes.png

(dialog-apply.png)

gtk-yes.png

(dialog-ok-apply.png)

gtk-yes-symbolic.png

(gtk-yes.png)

gtk-yes-symbolic.png

(gtk-yes.png)

gtk-zoom-100.png

(zoom-original.png)

gtk-zoom-100.png

(zoom-original.png)

gtk-zoom-100.png

(zoom-original.png)

gtk-zoom-100.png

(zoom-original.png)

gtk-zoom-100.png

(zoom-original.png)

gtk-zoom-100.svg

(zoom-original.svg)

gtk-zoom-fit.png

(zoom-fit-best.png)

			<img src="./22/gtk


tities(
        infile,
        outfn,
        ["id", "name"],
        "place.bounding_box",
        ["coordinates"],
        gzip_compress=False,
    )

    assert files_are_identical(outfn, ref_fn)

def test_retweet_original_tweet(tmp_path, infile):
    ref_fn = subdir / "tweets.20150430-223406.retweet.csv.ref"
    outfn = tmp_path / "tweets.20150430-223406.retweet.csv"
    json2csv_entities(
        infile,
        outfn,
        ["id"],
        "retweeted_status",
        [
            "created_at",
            "favorite_count",
            "id",
            "in_reply_to_status_id",
            "in_reply_to_user_id",
            "retweet_count",
            "text",
            "truncated",
            "user.id",
        ],
        gzip_compress=False,
    )

    assert files_are_identical(outfn, ref_fn)

def test_file_is_wrong(tmp_path, infile):
    """
    Sanity check that file comparison is not giving false positives.
    """
    ref_fn = subdir / "tweets.20150430-223406.retweet.csv.ref"
    outfn = tmp_path / "tweets.20150430-223406.text.csv"
    json2csv(infile, outfn, ["text"], gzip_compress=False)
    assert not files_are_identical(outfn, ref_fn)


     * @param taxRegion Region where tax applies.
     */
    void setTaxRegion(String taxRegion);

    /**
     * Region where tax applies.
     *
     *
     *
     *

     *

     *
     *
     *  tax_region
     *

     *
     *

     *
     *  Details
     *
     *  Geographical region a tax rate
     *  applies to.
     *
     *

     *

     *
     *
     *  Example
     *   <g:tax_region>California</g:tax_region>
     *
     *

     *

     *
     *  Attribute of
     *
     *
     *  Product,
     *  Events,
     *

     *
     *

     *
     *  Content type
     *  string
     *
     *

     *

     * @return Region where tax applies.
     */
    String getTaxRegion();

    /**
     * Product UPC code (Isn't that redundant?).
     *
     *
     *
     *

     *
     *

     *
     *
     *  upc
     *

     *

     *
     *  Details
     *
     *
     *  Product UPC code.
     *
     *

     *

     *
     *  Example
     *   <g:upc>834721479305</g:upc>
     *
     *

     *
     *

     *
     *  Attribute of
     *
     *  Products
     *

     *
     *

     *
     *
     *  Content type
     *
     *  string
     *

     *

     * @param upc Product UPC code (Isn't that redundant?).
     */
    void setUpc(String upc);

    /**
     * Product UPC code (Isn't that redundant?).
     *
     *
     *
     * <table border="1" cellpadding="


 holds function pointers to every optix function. Then
// the Optix driver dll is loaded at runtime and the function table is loaded from that.
// OptiX provides this logic inside optix_stubs.h in the include dir, so we need to compile that
// to a lib and link it in so that we have the initialization and C function logic.
fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let mut header = find_optix_root().expect(
        "Unable to find the OptiX SDK, make sure you installed it and
    that OPTIX_ROOT or OPTIX_ROOT_DIR are set",
    );
    header = header.join("include");
    let cuda_dir = find_cuda_root()
        .expect(
            "Unable to find the CUDA SDK, make sure you
    installed it and that CUDA_ROOT is set",
        )
        .join("include");

    cc::Build::new()
        .file("./optix_stubs.c")
        .include(cuda_dir)
        .include(header)
        .cpp(false)
        .compile("optix_stubs");

    println!("cargo:rustc-link-search=native={}", out_dir);
    println!("cargo:rustc-link-lib=static=optix_stubs");
}
// Copyright (c) SimpleStaking and Tezedge Contributors
// SPDX-License-Identifier: MIT

//! Sends blocks to the `protocol_runner`.
//! This actor is responsible for correct applying of blocks with Tezos protocol in context
//! This actor is aslo responsible for correct initialization of genesis in storage.

use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::thread::JoinHandle;
use std::time::Duration;

use failure::{Error, Fail};
use riker::actors::*;
use slog::{debug, info, Logger, trace, warn};

use crypto::hash::{BlockHash, HashType};
use storage::{BlockMetaStorage, BlockStorage, BlockStorageReader, ChainMetaStorage, initialize_storage_with_genesis_block, OperationsMetaStorage, OperationsStorage, OperationsStorageReader, StorageError, StorageInitInfo, store_applied_block_result, store_commit_genesis_result};
use storage::chain_meta_storage::ChainMetaStorageReader;
use storage::persistent::PersistentStorage;
use tezos_api::environment::TezosEnvironmentConfiguration;
use tezos_api::ffi::ApplyBlockRequest;
use tezos_wrapper::service::{IpcCmdServer, ProtocolController, ProtocolServiceError};

use crate::shell_channel::{BlockApplied, ShellChannelMsg, ShellChannelRef, ShellChannelTopic};
use crate::subscription::subscribe_to_shell_events;

/// This command triggers feeding of completed blocks to the tezos protocol
#[derive(Clone, Debug)]
pub struct FeedChainToProtocol;

type SharedJoinHandle = Arc<Mutex<Option<JoinHandle<Result<(), Error>>>>>;

/// Feeds blocks and operations to the tezos protocol (ocaml code).
#[actor(FeedChainToProtocol, ShellChannelMsg)]
pub struct ChainFeeder {
    /// All events from shell will be published to this channel
    shell_channel: ShellChannelRef,
    /// Thread where blocks are applied will run until this is set to `false`
    block_applier_run: Arc<AtomicBool>,
    /// Block applier thread
    block_applier_thread: SharedJoinHandle,
}

/// Reference to [chain feeder](ChainFeeder) actor
pub type ChainFeederRef = ActorRef<ChainFeederMsg>;

impl ChainFeeder {
    /// Create new actor instance.
    ///
    /// If the actor is successfully created then reference to the actor is returned.
    /// Commands to the tezos protocol


_MAFg3__16ybpnyrQ1Ri)
CALL(b__MAFg3__18vbf_onfr5pyrneRw)
CALL(b__MAFg3__113onfvp_bfgernzVpAF_11pune_genvgfVpRRR6fragelQ1Ri)
CALL(b__MAFg3__112__arkg_cevzrRz)
CALL(b__MA7naqebvq8uneqjner7frafbef4I1_08VFrafbef24ertvfgreSbeAbgvsvpngvbafREXAFg3__112onfvp_fgevatVpAF4_11pune_genvgfVpRRAF4_9nyybpngbeVpRRRREXAF_2fcVAF_4uvqy7znantre4I1_020VFreivprAbgvsvpngvbaRRR)
CALL(b__MAFg3__118pbaqvgvba_inevnoyr10abgvsl_nyyRi)
CALL(b__MAFg3__16puebab12fgrnql_pybpx3abjRi)
CALL(b__MAFg3__16puebab12flfgrz_pybpx3abjRi)
CALL(b__MAFg3__118pbaqvgvba_inevnoyr15__qb_gvzrq_jnvgREAF_11havdhr_ybpxVAF_5zhgrkRRRAF_6puebab10gvzr_cbvagVAF5_12flfgrz_pybpxRAF5_8qhengvbaVkAF_5engvbVYy1RYy1000000000RRRRRRR)
CALL(b__MAFg3__118pbaqvgvba_inevnoyrQ1Ri)
CALL(b__MA7naqebvq22VFrafbeRiragPbaarpgvbaP2Ri)
CALL(b__MA7naqebvq7OOvaqreP2Ri)
CALL(b__MA7naqebvq8Fgevat16P1REXF0_)
CALL(b__MA7naqebvq7OOvaqreQ2Ri)
CALL(b__MA7naqebvq22VFrafbeRiragPbaarpgvbaQ2Ri)
CALL(b__MA7naqebvq7Fgevat8P1REXAF_8Fgevat16R)
CALL(b__MAX7naqebvq6Frafbe31trgUvturfgQverpgErcbegEngrYriryRi)
CALL(b__MAX7naqebvq6Frafbe28vfQverpgPunaaryGlcrFhccbegrqRv)
CALL(b__MAX7naqebvq22VFrafbeRiragPbaarpgvba22trgVagresnprQrfpevcgbeRi)
CALL(b__MAX7naqebvq8Fgevat164fvmrRi)
CALL(b_fgempzc16)
CALL(b__MA7naqebvq7Fgevat8P1REXF0_)
CALL(b__MA7naqebvq7OvgGhorP1Rz)
CALL(b__MA7naqebvq14YbbcrePnyyonpxQ2Ri)
CALL(b__MA7naqebvq7ErsOnfr10baSvefgErsRi)
CALL(b__MAX7naqebvq6Frafbe16trgErcbegvatZbqrRi)
CALL(b__MAX7naqebvq6Frafbe14vfJnxrHcFrafbeRi)
CALL(b__MAX7naqebvq7OvgGhor9trgFraqSqRi)
CALL(b__MA7naqebvq6Ybbcre5nqqSqRvvvEXAF_2fcVAF_14YbbcrePnyyonpxRRRCi)
CALL(b__MA7naqebvq6Ybbcre8erzbirSqRv)
CALL(b__


ig = RepositoryConfigBuilder::new(invalid_static1_url).build();

        let invalid_static2_url = RepoUrl::parse("fuchsia-pkg://a.invalid-static2").unwrap();
        let invalid_static2_config = RepositoryConfigBuilder::new(invalid_static2_url).build();

        let invalid_static3_url =
            RepoUrl::parse("fuchsia-pkg://a.invalid-static3.example.com").unwrap();
        let invalid_static3_config = RepositoryConfigBuilder::new(invalid_static3_url).build();

        let valid_dynamic_url = RepoUrl::parse("fuchsia-pkg://a.valid3.fuchsia.com").unwrap();
        let valid_dynamic_config = RepositoryConfigBuilder::new(valid_dynamic_url).build();

        let invalid_dynamic_url =
            RepoUrl::parse("fuchsia-pkg://a.invalid-dynamic.fuchsia.com").unwrap();
        let invalid_dynamic_config = RepositoryConfigBuilder::new(invalid_dynamic_url).build();

        let env = TestEnv::builder()
            .add_static_configs(
                "config",
                RepositoryConfigs::Version1(vec![
                    valid_static1_config.clone(),
                    valid_static2_config.clone(),
                    valid_static3_config.clone(),
                    invalid_static1_config,
                    invalid_static2_config,
                    invalid_static3_config,
                ]),
            )
            .add_dynamic_configs(RepositoryConfigs::Version1(vec![
                valid_dynamic_config.clone(),
                invalid_dynamic_config,
            ]))
            .build();

        let repomgr = env.repo_manager().unwrap();

        assert_eq!(
            repomgr.get_repo_for_channel("valid1").map(|r| &**r),
            Some(&valid_static1_config)
        );
        assert_eq!(
            repomgr.get_repo_for_channel("valid2").map(|r| &**r),
            Some(&valid_static2_config)
        );

        // Dynamic repos for a valid config overload the static config.
        assert_eq!(
            repomgr.get_repo_for_channel("valid3").map(|r| &**r),
            Some(&valid_dynamic_config)
        );

        // Ignore repos that have a url that aren't `abc.${channel}.fuchsia.com`.
        assert_eq!(repomgr.get_repo_for_channel("invalid-static1"), None);
        assert_eq!(repomgr.get_repo_for_channel("invalid-static2"), None);
        assert_eq!(repomgr.get_repo_for_channel("invalid-static3"), None);

        // Ignore non-overloading dynamic repos.
        assert_eq!(repomgr.get_repo_for_channel("invalid-dynamic"), None);
    }

    #[test]
    fn test_no_dynamic_repos_if_no_dynamic_repo_path() {
        let repomgr = RepositoryManagerBuilder::new_test(Option::<&Path>::None).unwrap().build();

        assert_eq!(repomgr.static_configs, HashMap::new());
        assert_eq!(repomgr.dynamic_configs_path, None);
        assert_eq!(repomgr.dynamic_configs, HashMap::new());
        assert_eq!(repomgr.list().collect::<Vec<_>>(), Vec::<&RepositoryConfig>::new());
    }

    #[test]
    fn test_insert_fails_with_no_change_if_no_dynamic_config_path() {
        let mut repomgr =
            RepositoryManagerBuilder::new_test(Option::<&Path>::None).unwrap().build();
        let fuchsia_url = RepoUrl::parse("fuchsia-pkg://fuchsia.com").unwrap();
        let config = Arc::new(
            RepositoryConfigBuilder::new(fuchsia_url.


_RaidHunter_A_01_TrM.mdx'
    ModelA[93817] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_BeF.mdx'
    ModelA[93816] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_BeM.mdx'
    ModelA[93815] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_DrF.mdx'
    ModelA[93814] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_DrM.mdx'
    ModelA[93813] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_DwF.mdx'
    ModelA[93812] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_DwM.mdx'
    ModelA[93811] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_GnF.mdx'
    ModelA[93810] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_GnM.mdx'
    ModelA[93809] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_GoF.mdx'
    ModelA[93808] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_GoM.mdx'
    ModelA[93807] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_HuF.mdx'
    ModelA[93806] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_HuM.mdx'
    ModelA[93805] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_NiF.mdx'
    ModelA[93804] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_NiM.mdx'
    ModelA[93803] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_OrF.mdx'
    ModelA[93802] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_OrM.mdx'
    ModelA[93801] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_ScF.mdx'
    ModelA[93800] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_ScM.mdx'
    ModelA[93799] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_TaF.mdx'
    ModelA[93798] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_TaM.mdx'
    ModelA[93797] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_TrF.mdx'
    ModelA[93796] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_B_01_TrM.mdx'
    ModelA[93795] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_C_01_BeF.mdx'
    ModelA[93794] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_C_01_BeM.mdx'
    ModelA[93793] = 'ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Mail_RaidHunter_C_01_DrF.mdx'
    Mode


    std::string in_path = "test-data/sequence-parser/test5.sam";
    bool expected = true;

    auto parser = mindex::createSequenceFileParserSam(in_path);
    bool result = parser->IsOpen();

    ASSERT_EQ(result, expected);
}

// TEST(SequenceFileParserSam, GetFileOffset1) {
//     // This functionality is integratively tested in FileSeek1.
// }

TEST(SequenceFileParserSam, FileSeek1) {
    auto parser = mindex::createSequenceFileParserSam("test-data/sequence-parser/test5.sam");

    ASSERT_NE(parser, nullptr);
    ASSERT_EQ(parser->IsOpen(), true);

    std::vector<int64_t> offsets;
    std::vector<mindex::SequencePtr> seqs;

    mindex::SequencePtr seq;
    int64_t prev_offset = parser->GetFileOffset();

    // Create a mini index of the sequences.
    while ((seq = parser->YieldSequence()) != nullptr) {
        seqs.emplace_back(std::move(seq));
        offsets.emplace_back(prev_offset);
        prev_offset = parser->GetFileOffset();
    }

    // Create a reversed permutation of sequence IDs for reading.
    std::vector<int64_t> permutation;
    for (int64_t i = 0; i < static_cast<int64_t>(seqs.size()); ++i) {
        permutation.emplace_back(i);
    }
    std::reverse(permutation.begin(), permutation.end());

    // Lookup all the same sequences, in a random order.
    for (const auto& seq_id: permutation) {
        parser->FileSeek(offsets[seq_id]);
        seq = parser->YieldSequence();
        ASSERT_NE(seq, nullptr);
        ASSERT_EQ(seq->header(), seqs[seq_id]->header());
        ASSERT_EQ(seq->GetSequenceAsString(), seqs[seq_id]->GetSequenceAsString());
        ASSERT_EQ(seq->GetQualityAsString(), seqs[seq_id]->GetQualityAsString());
    }
}

//    int64_t GetFileOffset() const;
//    bool FileSeek(int64_t pos);
// Copyright 2020-2023 Intel Corporation
// SPDX-License-Identifier: BSD-3-Clause

#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#else
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#endif

#include "ispcrt.h"
// std
#include <exception>
#include <iostream>
#include <string>
// ispcrt
#include "detail/Exception.h"
#include "detail/Module.h"
#include "detail/ModuleOptions.h"
#include "detail/TaskQueue.h"

#ifdef ISPCRT_BUILD_CPU
#include "detail/cpu/CPUContext.h"
#include "detail/cpu/CPUDevice.h"
#endif

#ifdef ISPCRT_BUILD_GPU
#include "detail/gpu/GPUContext.h"
#include "detail/gpu/GPUDevice.h"
#endif

static void defaultErrorFcn(ISPCRTError e, const char *msg) {
    std::cerr << "ISPCRT Error (" << e << "): " << msg << std::endl;
    exit(-1);
}

static ISPCRTErrorFunc g_errorFcn = &defaultErrorFcn;

// Helper functions ///////////////////////////////////////////////////////////

static void handleError(ISPCRTError e, const char *msg) {
    if (g_errorFcn)
        g_errorFcn(e, msg);
}

template <typename OBJECT_T = ispcrt::RefCounted, typename HANDLE_T = ISPCRTGenericHandle>
static OBJECT_T &referenceFromHandle(HANDLE_T handle) {
    return *((OBJECT_T *)handle);
}

#define ISPCRT_CATCH


Type::QUANTIZEDMAXPOOL_8,
                &op_map);
  EmplaceOpType("QuantizedAvgPool", {}, SupportedOpType::QUANTIZEDAVGPOOL_8,
                &op_map);
  EmplaceOpType("QuantizedConcat", {}, SupportedOpType::QUANTIZEDCONCAT_8,
                &op_map);
  EmplaceOpType("QuantizedBiasAdd", {},
                SupportedOpType::QUANTIZEDBIASADD_8P8TO32, &op_map);
  EmplaceOpType("Min", {}, SupportedOpType::MIN_F, &op_map);
  EmplaceOpType("Max", {}, SupportedOpType::MAX_F, &op_map);
  EmplaceOpType("QuantizeV2", {}, SupportedOpType::QUANTIZE, &op_map);
  EmplaceOpType("Dequantize", {}, SupportedOpType::DEQUANTIZE, &op_map);
  EmplaceOpType("Softmax", {}, SupportedOpType::SOFTMAX_F, &op_map);
  EmplaceOpType("Reshape", {}, SupportedOpType::RESHAPE, &op_map);
  EmplaceOpType("QuantizedReshape", {}, SupportedOpType::QUANTIZED_RESHAPE,
                &op_map);
  EmplaceOpType("Sigmoid", {}, SupportedOpType::SIGMOID_F, &op_map);
  EmplaceOpType("Slice", {}, SupportedOpType::SLICE_F, &op_map);
  EmplaceOpType("Add", {}, SupportedOpType::ADD_F, &op_map);
  EmplaceOpType("Mul", {}, SupportedOpType::MUL_F, &op_map);
  EmplaceOpType("Requantize", {}, SupportedOpType::REQUANTIZE_32_TO_8, &op_map);
  EmplaceOpType("RequantizationRange", {},
                SupportedOpType::REQUANTIZATION_RANGE_32, &op_map);
  EmplaceOpType("Sub", {}, SupportedOpType::SUB_F, &op_map);
  EmplaceOpType("Pack", {}, SupportedOpType::PACK_INT32, &op_map);
  EmplaceOpType("StridedSlice", {}, SupportedOpType::STRIDED_SLICE_F, &op_map);
  EmplaceOpType("ExpandDims", {}, SupportedOpType::EXPAND_DIMS_F, &op_map);
#ifdef ENABLE_EXPERIMENTAL_HEXNN_OPS
  EmplaceOpType("QuantizedMul", {}, SupportedOpType::QUANTIZED_MUL_8x8to32,
                &op_map);
  EmplaceOpType("QuantizedAdd", {}, SupportedOpType::QUANTIZED_ADD_8p8to32,
                &op_map);
  EmplaceOpType("Pad", {}, SupportedOpType::PAD_F, &op_map);
  EmplaceOpType("SpaceToBatchND", {}, SupportedOpType::SPACE_TO_BATCH_ND_F,
                &op_map),
      EmplaceOpType("BatchToSpaceND", {}, SupportedOpType::BATCH_TO_SPACE_ND_F,
                    &op_map);
  EmplaceOpType("ResizeBilinear", {}, SupportedOpType::RESIZE_BILINEAR_F,
                &op_map);
  EmplaceOpType("ConcatV2", {}, SupportedOpType::CONCAT_V2_F, &op_map);
  EmplaceOpType("Conv2DBackpropInput", {}, SupportedOpType::DECONV_F, &op_map);

  EmplaceOpType("Tanh", {}, SupportedOpType::TANH_F, &op_map);
  EmplaceOpType("Split", {}, SupportedOpType::SPLIT_F, &op_map);
  EmplaceOpType("Transpose", {}, Supp


G_WINR.shadow) {
            exception()
        } else {
            reloadWatchdog()
        }
    }

    private fun startWatchdog() {
        log.info { "Watchdog started!" }
        reloadWatchdog()
    }

    private fun reloadWatchdog() {
        IWDG_RLR.updateShadow()
        count = IWDG_RLR.shadow

        IWDG_WINR.updateShadow()
        count = IWDG_WINR.shadow

        counter.connect(core.clock, watchdogPeriod)   // (40kHz)/divider
    }

    private fun counterTriggerEvent() {
        if (count == 0uL) {
            exception()
        } else {
            count--
        }
    }

    private fun exception() {
        throw GeneralException("[IWDG refresh timeout]")
    }

    private val IWDG_KR = object : RegisterBase(Companion.RegisterType.IWDG_KR) {
        override fun read(ea: ULong, ss: Int, size: Int) = 0x0000uL
        override fun write(ea: ULong, ss: Int, size: Int, value: ULong) {
            when (value) {
                0x0000uL -> state = State.LOCKED
                0x5555uL -> state = State.UNLOCKED
                0xAAAAuL -> if (counter.enabled) refreshWatchdog() // reset counter and apply IWDG_PLR register
                0xCCCCuL -> startWatchdog()
            }
        }
    }
    private val IWDG_PR     = object : RegisterBase(RegisterType.IWDG_PR) {
        var PLR by field(2..0)

        var divider: Long = 4

        override fun write(ea: ULong, ss: Int, size: Int, value: ULong) {
            super.write(ea, ss, size, value)

            if (state == State.UNLOCKED) when (PLR) {
                0b000uL -> divider = 4
                0b001uL -> divider = 8
                0b010uL -> divider = 16
                0b011uL -> divider = 32
                0b100uL -> divider = 64
                0b101uL -> divider = 128
                0b110uL -> divider = 256
                0b111uL -> divider = 256
            }
        }
    }
    private val IWDG_RLR    = object : RegisterBase(RegisterType.IWDG_RLR, default = 0x0000_0FFFu) {
        var RL by field(11..0)  // counter reload value
        var shadow = default

        override fun write(ea: ULong, ss: Int, size: Int, value: ULong) {
            if (state == State.UNLOCKED) super.write(ea, ss, size, value)
        }

        fun updateShadow() {
            shadow = RL
        }
    }
    private val IWDG_SR     = object : RegisterBase(RegisterType.IWDG_SR) {}
    private val IWDG_WINR   = object : RegisterBase(RegisterType.IWDG_WINR, default = 0x0000_0FFFu) {
        var WIN by field(11..0)
        var shadow = default

        override fun write(ea: ULong, ss: Int, size: Int, value: ULong) {
            if (state == State.UNLOCKED) super.write(ea, ss, size, value)
        }

        fun updateShadow() {
            shadow = WIN
        }
    }
}

/*
 *
 * This file is part of Kopycat emulator software.
 *
 * Copyright (C) 2023 INFORION, LLC
 *
 * This program 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 2 of the License, or
 * (at your option) any later v


          if (matchedAnimeByTitleAndId == null && animesList.isNotEmpty) {
            // animesList.first 可能不是 Map<String, dynamic>，所以需要 as Map<String, dynamic>?
            // 并且 matchedAnimeByTitleAndId 在此赋值后可能为 null，所以后续访问需要 '?'
            matchedAnimeByTitleAndId = animesList.first as Map<String, dynamic>?;
            debugPrint('警告: 在标题搜索结果中未通过 animeId ($animeId) 精确匹配。使用第一个结果: ${matchedAnimeByTitleAndId?['animeTitle']} (ID: ${matchedAnimeByTitleAndId?['animeId']})');
          }

          if (matchedAnimeByTitleAndId != null &&
              matchedAnimeByTitleAndId['episodes'] != null &&
              matchedAnimeByTitleAndId['episodes'] is List) {
            final episodes = List<Map<String, dynamic>>.from(matchedAnimeByTitleAndId['episodes']);
            debugPrint('成功获取 ${episodes.length} 个剧集，动画标题: ${matchedAnimeByTitleAndId['animeTitle']} (原始请求ID: $animeId)');

            if (episodes.isNotEmpty) {
              int validEpisodes = 0;
              for (var ep in episodes) {
                if (ep['episodeId'] != null) {
                  validEpisodes++;
                }
              }
              if (validEpisodes < episodes.length) {
                debugPrint('警告: 只有 $validEpisodes/${episodes.length} 个剧集有有效的episodeId');
              } else {
                debugPrint('所有剧集都有有效的episodeId');
              }

              final firstEp = episodes.first;
              debugPrint('第一个剧集: ID=${firstEp['episodeId']}, 标题=${firstEp['episodeTitle']}');

              for (var i = 0; i < episodes.length; i++) {
                var ep = episodes[i];
                final episodeTitle = ep['episodeTitle'] as String? ?? '';
                // 更新正则表达式以更好地匹配集数，例如 " 01 ", "EP01", "(01)"
                final indexMatch = RegExp(r'第\s*(\d+)\s*[集话期]|\s(\d+)(?:\s|$)|EP\s*(\d+)|\((\d+)\)|\【(\d+)\】|\s(\d+)$').firstMatch(episodeTitle);

                if (indexMatch != null) {
                  // 尝试所有可能的捕获组
                  String? numStr;
                  for (int j = 1; j <= indexMatch.groupCount; j++) {
                    if (indexMatch.group(j) != null) {
                      numStr = indexMatch.group(j);
                      break;
                    }
                  }
                  if (numStr != null) {
                    ep['episodeIndex'] = int.parse(numStr);
                  } else {
                     ep['episodeIndex'] = i + 1; // Fallback
                  }
                } else {
                  ep['episodeIndex'] = i + 1;
                }
              }
            }
            return episodes;
          } else {
            debugPrint('警告: 匹配的动画 (${matchedAnimeByTitleAndId?['animeTitle']}) 中没有episodes字段或不是列表格式。');
          }
        } else {
          debugPrint('警


let integer_r = ecc_chip.new_unassigned_scalar(self.sig_data.map(|s| s.r));
				let integer_s = ecc_chip.new_unassigned_scalar(self.sig_data.map(|s| s.s));
				let msg_hash = ecc_chip.new_unassigned_scalar(self.m_hash);

				let r_assigned = scalar_chip.assign_integer(ctx, integer_r, Range::Remainder)?;
				let s_assigned = scalar_chip.assign_integer(ctx, integer_s, Range::Remainder)?;
				let sig = AssignedEcdsaSig {
					r: r_assigned,
					s: s_assigned,
				};

				let pk_in_circuit = ecc_chip.assign_point(ctx, self.pk.map(|p| p.into()))?;
				let pk_assigned = AssignedPublicKey {
					point: pk_in_circuit,
				};
				let msg_hash = scalar_chip.assign_integer(ctx, msg_hash, Range::Remainder)?;
				ecdsa_chip.verify(ctx, &sig, &pk_assigned, &msg_hash)
			},
		)?;

		config.config_range(&mut layouter)?;

		Ok(())
	}
}

#[cfg(test)]
mod test {
	use crate::ecdsa::native::Keypair;

	use super::{native::generate_signature, *};
	use halo2wrong::{
		curves::{
			bn256::Fr,
			group::{Curve, Group},
			secp256k1::Secp256k1Affine as Secp256,
		},
		halo2::arithmetic::CurveAffine,
	};
	use maingate::halo2::dev::MockProver;
	use rand::thread_rng;

	#[test]
	fn test_ecdsa_verify() {
		let k = 20;
		let mut rng = thread_rng();

		let pair = Keypair::<Secp256>::new(&mut rng);
		let pk = pair.public().clone();
		let m_hash = <Secp256 as CurveAffine>::ScalarExt::from(4);
		let sig_data = generate_signature::<Secp256, _>(pair, m_hash, &mut rng).unwrap();

		let aux_generator = <Secp256 as CurveAffine>::CurveExt::random(&mut rng).to_affine();
		let sig_verifyer = EcdsaVerifier {
			sig_data: Some(sig_data),
			pk: Some(pk),
			m_hash: Some(m_hash),
			aux_generator: Some(aux_generator),
			window_size: 2,
			_marker: PhantomData,
		};
		let public_inputs = vec![vec![]];
		let prover = match MockProver::<Fr>::run(k, &sig_verifyer, public_inputs) {
			Ok(prover) => prover,
			Err(e) => panic!("{}", e),
		};
		assert_eq!(prover.verify(), Ok(()));
	}
}
use std::cell::RefCell;
use std::collections::HashSet;

use preprocessor::PreprocessorOptions;

use purkka::core::get_file_cb;
use resolve::*;

fn parse(content: &str) -> ResolveResult {
    let input = "main.prk";
    let get_file_content = |req: &FileQuery| {
        if req.requested_file == input {
            (content.to_string(), req.requested_file.clone())
        } else {
            panic!("Unexpected include: {}", req.requested_file)
        }
    };

    let options = PreprocessorOptions {
        include_path: vec![],
        include_files: vec![],
        definitions: vec![],
    };

    let ctx = RefCell::new(None);
    let res = get_file_cb(&options, &get_file_content, ctx)(FileQuery::new(
        ".",
        input,
        true,
        false,
        HashSet::new(),