repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/ludwig-austermann/typst-din-5008-letter | https://raw.githubusercontent.com/ludwig-austermann/typst-din-5008-letter/main/Changelog.md | markdown | MIT License | # Changelog
## Version 0.1.1
- Fixed type checking according to typst 0.8
## Version 0.1.0
- Added local package presets
- Changed date to automatically take todays date conform to the DIN (`YYYY-MM-DD`)
- Changed variable names / options from `....` and `.._..` to `..-..`
- Changed styling initialization via a function with default arguments
- Added debugging posibilities
- Added background, foreground styling options
- Changed blocks to hooks
- Changed Faltmarke to Falzmarke according to DIN
- Changed Briefkopf to full width according to DIN
- Changed Anschriftzone to full width according to DIN
- Added a reference / label system
- includes default `@date` and `@name` labels
- others can be defined in the labels argument of letter function
- Added `wordings.toml`, where formal / informal variations of various languages are added, which can then be loaded via `wordings` argument and special `load-wordings` function
- Some phrases were moved from `options` to
- Added `block-hooks` to change the behavious of various parts
- Removed `page-number-on-first-page` field, as this should now be done with the `pagenumber` hook
- Added text-params to specify font options
Everything should be cleaner, more flexible and configurable and there are many more changes. Take a look at the new readme file! |
https://github.com/maucejo/presentation_polylux | https://raw.githubusercontent.com/maucejo/presentation_polylux/main/docs/manual-template.typ | typst | MIT License | #import "@preview/showybox:2.0.1": *
#import "@preview/hydra:0.4.0": hydra
#import "@preview/mantys:0.1.3": *
#import "@preview/cheq:0.1.0": *
#let vskip = 1em
#let typst-color = rgb(35,157,173)
#let typst = text("Typst", fill: typst-color)
#let TeX = {
set text(font: "New Computer Modern", weight: "regular")
box(width: 1.7em, {
[T]
place(top, dx: 0.56em, dy: 0.22em)[E]
place(top, dx: 1.1em)[X]
})
}
#let LaTeX = {
set text(font: "New Computer Modern", weight: "regular")
box(width: 2.55em, {
[L]
place(top, dx: 0.3em, text(size: 0.7em)[A])
place(top, dx: 0.7em)[#TeX]
})
}
#let subfigure = figure.with(
kind: "subfigure",
supplement: [],
numbering: "(a)",
)
#let example-box(body) = {
showybox(
title: [*Exemple*],
title-style: (
color: typst-color,
sep-thickness: 2pt,
boxed-style: (
anchor: (x: center, y: horizon),
radius: 5pt
)
),
frame: (
title-color: white,
border-color: typst-color,
thickness: 1pt,
body-inset: 1em
),
align: center,
breakable: true
)[
#body
]
}
#let manual-template(
title: "Title",
subtitle: "subtitle",
version: "Template 0.1.0",
typst-version: "Typst 0.11.1",
date: datetime.today().display("[day]-[month]-[year]"),
abstract : none,
body
) = {
let header = context hydra(1, display: (_, it) => {
set align(center)
emph([#counter(heading).display(it.numbering) #it.body])
})
set page(paper: "a4", numbering: "1/1", header: header)
set par(justify: true)
set text(lang: "fr", font: "Lato", size: 11pt)
show math.equation: set text(font: "Lete Sans Math")
set heading(numbering: "1.1.")
set list(indent: 2em)
show raw: set text(font: "Liberation Mono", size: 11pt)
// Figures
show figure.where(kind: image): set figure(numbering: "1", supplement: "Figure", gap: 1.5em)
show figure.where(kind: image): set figure.caption(separator: [ -- ])
// Subfigures
// Updates subfigure counter properly
show figure.where(kind:image): it => {
counter(figure.where(kind:"subfigure")).update(0)
it
}
show figure.where(kind: "subfigure"): set figure.caption(separator: [ ])
show heading.where(level: 1): it => {
if it.numbering != none {
[#counter(heading).display(it.numbering) #it.body]
} else {
it.body
}
v(vskip/2)
}
show heading.where(level: 2): it => {
[#counter(heading).display(it.numbering) #it.body]
v(vskip/2)
}
show heading.where(level: 3): it => {
[#counter(heading).display(it.numbering) #it.body]
v(vskip/2)
}
show: checklist.with(fill: typst-color.lighten(95%), stroke: typst-color, radius: .2em)
align(center)[
#text(title, fill: typst-color, size: 2em) \
#text(subtitle)
#v(vskip/2)
#block(width: 80%)[
#date #h(1fr) #version #h(1fr) #typst-version
]
#v(vskip/2)
<NAME>
#v(vskip)
#block(width: 80%)[
#set align(left)
#abstract
]
]
v(vskip)
align(center)[
#block(width: 50%)[
#outline(indent: 1em)
#v(vskip)
]
]
body
} |
https://github.com/huyufeifei/grad | https://raw.githubusercontent.com/huyufeifei/grad/master/info/redleaf_zh.typ | typst | #import "@preview/charged-ieee:0.1.0": ieee
#show: ieee.with(
title: [红叶:安全操作系统中的隔离与通信],
abstract: [
红叶(RedLeaf)是一个从零开始用 Rust 开发的新操作系统,旨在探索语言安全对操作系统组成的影响。与商业系统相比,红叶不依赖硬件地址空间进行隔离,而只依靠 Rust 语言的类型和内存安全。脱离昂贵的硬件隔离机制让我们得以探索轻量级细粒度隔离系统的设计空间。我们开发了一个新的基于语言的轻量级隔离域的抽象,它提供了一个信息隐藏和故障隔离的单元。 域能够被动态地加载并干净地终止,即一个域中的错误不会影响其他域的运行。在红叶隔离机制的基础上,我们展示了实现设备驱动程序的端到端零拷贝、故障隔离和透明恢复的可能性。为了评估红叶抽象的实用性。我们把 Rv6,一个 POSIX 子集操作系统实现成了若干个红叶域的集合。最后,为了证明 Rust 和细粒度隔离的实用性,我们开发了 10Gbps 英特尔 ixgbe 网卡和 NVMe 固态硬盘设备驱动程序的高效版本,其性能可与最快的 DPDK 和 SPDK 相媲美。
],
authors: (
(
name: "<NAME>",
organization: [University of California, Irvine],
),
(
name: "<NAME>",
organization: [University of California, Irvine],
),
(
name: "<NAME>",
organization: [University of California, Irvine],
),
(
name: "<NAME>",
organization: [University of California, Irvine],
),
(
name: "<NAME>",
organization: [University of California, Irvine],
),
(
name: "<NAME>",
organization: [VMware Research],
),
(
name: "<NAME>",
organization: [University of California, Irvine],
),
),
// index-terms: ("Scientific writing", "Typesetting", "Document creation", "Syntax"),
bibliography: bibliography("refs.bib"),
)
= 引入
四十年前,早期的操作系统设计认为隔离内核子系统的能力是提高整个系统可靠性和安全性的关键机制@a12@a32。 遗憾的是,尽管多次尝试在内核中引入细粒度隔离,但现代系统仍然是庞大且单一(monolithic)的。一直以来,软件和硬件机制对于高性能要求的子系统隔离来说过于昂贵。多个硬件项目探索了在硬件中实现细粒度、低开销隔离机制的能力 @a84@a89@a90。然而,着眼于性能,现代商品 CPU 只为用户程序的粗粒度隔离提供了基本支持。同样,几十年来,能在软件层面提供细粒度隔离的安全语言对于低级的操作系统代码来说开销仍然过高。传统上,安全语言需要一个可管理的运行时,特别是垃圾回收机制来实现安全。尽管垃圾回收技术取得了许多进步,但对于每个核心每秒处理数百万个请求的系统来说,垃圾回收的开销仍然很高(在典型的设备驱动程序工作情形中,最快的垃圾回收语言比 C 语言慢 20-50%@a28)。
几十年来,打破单一内核的设计选择仍然不切实际。因此,现代内核缺乏隔离性及其优势:简洁的模块化、信息隐藏、故障隔离、透明的子系统恢复和细粒度访问控制。
随着 Rust 的发展,隔离和性能之间的历史平衡正在发生变化。Rust 可以说是第一种在没有垃圾回收的情况下实现安全性的实用语言 @a45。Rust 将旧的线性类型 @a86 思想与实用的语言设计相结合,通过一个受限的所有权模型来实现类型和内存安全,允许内存中的每个生存对象只有唯一一个引用。这样就可以静态跟踪对象的生命周期,并在不使用垃圾回收器的情况下将其删除。该语言的运行时开销仅限于边界检查,且在许多情况下,现代超标量无序 CPU 可以隐藏边界检查,并预测和执行不进行检查时的正确路径 @a28。为了实现实用的非线性数据结构,Rust 提供了一小套精心挑选的基本类型,可以摆脱线性类型系统的严格限制。
Rust 作为一种开发底层系统的工具,迅速受到人们的欢迎,而传统上这些系统都是用 C 语言开发的@a4@a24@a40@a47@a50@a65。低开销安全带来了一系列立竿见影的安全优势——预计三分之二由典型的不安全低级语言编程习语(idiom)引起的漏洞,仅通过使用安全语言就可以消除 @a20@a22@a67@a69@a77。
遗憾的是,最近的项目大多把 Rust 作为 C 语言的一种替换。然而,我们认为,语言安全的真正好处在于可以实现实用、轻量级、细粒度的隔离,以及一系列几十年来一直是操作系统研究重点但却无法实用的机制:故障隔离@a79、透明设备驱动恢复@a78、安全内核扩展@a13@a75、基于能力的细粒度访问控制@a76 等等。
红叶#footnote[在叶片组织中生成的锈(Rust)菌会使叶片变红] 是一个新的操作系统,旨在探索语言安全对操作系统组成的影响,特别是在内核中利用细粒度隔离的能力及其优势。红叶是用 Rust 从零开始实现的。它不依赖硬件机制进行隔离,而只使用 Rust 语言的类型和内存安全。
尽管有多个项目在探索基于语言的系统中的隔离问题 @a6@a35@a39@a85 ,但在 Rust 中阐明隔离原则并提供实用的实现仍然具有挑战性。一般来说,安全语言会提供一些机制来控制对单个对象字段的访问(例如 Rust 中的 `pub` 访问修饰符),并保护指针,即限制对通过可见全局变量和显式传递参数可获取的程序状态的访问。通过对引用和通信渠道的控制,可以在函数和模块边界上隔离程序的状态,以确保保密性和完整性,更广泛地说,可以通过对象能力语言@a59 所探索的一系列技术来构建全面的最小权限系统。
不幸的是,仅靠内置语言机制不足以对互不信任的系统实现隔离,如依赖语言安全隔离应用程序和内核子系统的操作系统内核。为了保护整个系统的执行,内核需要一种隔离故障的机制,即提供一种终止故障或行为不端计算的方法,使系统处于干净的状态。具体来说,在子系统终止后,隔离机制应提供途径来做到:1)取消分配给子系统使用的所有资源;2)如果一个子系统分配的对象已通过通信通道传递给其他子系统,保留它;以及 3)确保今后对已终止子系统所暴露接口的所有调用都不会违反安全规定或阻塞调用者,而是返回错误信息。面对基于语言的系统所鼓励的语义丰富的接口,故障隔离是一项挑战——频繁的引用交换往往意味着单个组件的崩溃会使整个系统处于损坏状态@a85。
从早期的单用户、单语言、单地址空间设计 @a9@a14@a19@a25@a34@a55@a71@a80 到堆隔离@a6@a35 以及使用线性类型来实现堆隔离 @a39 ,多年来,在基于语言的系统中隔离计算的目标已经走过了漫长的道路。尽管如此,如今人们对基于语言的隔离原理还不甚了解。在 Sing\# 中实现故障隔离的 Singularity @a39 依靠语言和操作系统的紧密协同设计来实现隔离机制。且最近几个提出使用 Rust 实现轻量级隔离的系统,如 Netbricks @a68 和 Splinter@a47,都难以阐明实现隔离的原则,而只是用 Rust 已经提供的信息隐藏来代替故障隔离。类似的,最近推出的 Rust 操作系统 Tock 通过传统的硬件机制和受限的系统调用接口支持用户进程的故障隔离,但却无法为安全 Rust 实现的设备驱动程序(胶囊)提供故障隔离@a50。
我们的工作是开发安全语言的故障隔离原则和机制。我们引入了一种基于语言的隔离域抽象,作为信息隐藏、加载和故障隔离的单元。为了封装域的状态并在域边界实现故障隔离,我们制定了以下原则:
- *堆隔离* 我们将堆隔离作为对所有域的约束(invariant),即各域绝不持有指向其他域私有堆的指针。堆隔离是终止和卸载崩溃域的关键,因为没有其他域持有指向崩溃域私有堆的指针,所以卸载整个私有堆是安全的。为了实现跨域通信,我们引入了一种特殊的共享堆,允许分配可在域之间交换的对象。
- *可交换类型* 为了实现堆隔离,我们引入了可交换类型的概念,即在不泄漏指向私有堆的指针的情况下,可以安全地跨域交换的类型。可交换类型允许我们静态地实现一个约束,即在共享堆上分配的对象不能有指向私有域堆的指针,但可以有指向共享堆上其他对象的引用。
- *所有权追踪* 为了取消崩溃域在共享堆上拥有的资源,我们会跟踪共享堆上所有对象的所有权。当一个对象在域之间传递时,我们会根据它是在域之间移动还是在只读访问中被借用来更新其所有权。我们依靠 Rust 的所有权规范来强制各域在跨域函数调用中传递共享对象引用时失去所有权,也就是说,Rust 会强制要求调用者域中没有被传递对象的别名。
- *接口验证* 为了提供系统的可扩展性,并允许域作者为他们实现的子系统定义自定义接口,同时保留隔离性,我们对所有跨域接口进行了验证,确保接口仅含有可交换类型的约束,从而防止它们破坏堆隔离约束。我们开发了一种接口定义语言(IDL),可静态验证跨域接口的定义并为其生成实现。
- *跨域调用代理* 我们通过代理来调用所有跨域调用——这是在所有域接口上插入的一层可信代码。代理可更新跨域传递对象的所有权,支持从崩溃的域中解绑(unwind)线程的执行,并在域终止后保护未来对域的调用。我们的 IDL 通过接口定义生成代理对象的实现
上述原则使我们能够以实用的方式实现故障隔离:即使面对语义丰富的接口,隔离边界也能将开销降至最低。当域崩溃时,我们会通过解绑当前在域内执行的所有线程的执行来隔离故障,并在不影响系统其他部分的情况下取消分配域的资源。对域接口的后续调用会返回错误类型,但仍然安全,不会引发恐慌。域分配的但在崩溃前返回的所有对象都会保持存活。
为了测试这些原则,我们将红叶实现成了一个微内核操作系统,在这个系统中,一组被隔离的域实现了内核的功能:典型的内核子系统、类 POSIX 接口、设备驱动程序和用户应用程序。红叶提供了现代内核的典型功能:多核支持、内存管理、动态加载内核扩展、类 POSIX 用户进程和快速设备驱动程序。在红叶隔离机制的基础上,我们展示了以透明方式恢复崩溃设备驱动程序的可能性。我们采用了一种与影子驱动程序类似的想法 @a78,即轻量级影子域,它作为访问设备驱动程序的中介,并在崩溃后重新启动它,重新执行其初始化协议。
为了评估红叶抽象的通用性,我们在红叶的基础上实现了 Rv6,这是一个 POSIX 子集操作系统。Rv6 遵循 UNIX V6 规范@a53。尽管 Rv6 是一个相对简单的内核,但它是一个很好的平台,说明了如何将基于语言的细粒度隔离思想应用于以 POSIX 接口为中心的现代内核中。最后,为了证明 Rust 和细粒度隔离带来的开销并不高昂,我们开发了高效版本的 10Gbps 英特尔 Ixgbe 网卡和 PCIe 附加固态硬盘 NVMe 驱动程序。
我们认为,将实用语言安全与所有权规范相结合,可以让我们首次以高效的方式实现操作系统研究中的许多经典理念。红叶速度快,支持内核子系统的细粒度隔离@a57@a61@a62@a79、故障隔离@a78@a79、实现端到端零拷贝通信@a39、支持用户级设备驱动程序和内核旁路@a11@a21@a42@a70 等等。
= 基于语言的系统隔离 <l2>
在基于语言的操作系统中,对隔离的研究由来已久,这些研究通过语言安全、指针的细粒度控制和类型系统,探索执行轻量级隔离边界的取舍方法。早期的操作系统采用安全语言开发@a9@a14@a19@a25@a34@a55@a71@a80。这些系统使用“开放”的架构,即单用户、单语言、单地址空间的操作系统,模糊了操作系统与应用程序本身的界限@a48。这些系统依靠语言安全来防止意外错误,但不提供子系统或用户应用程序的隔离(现代 unikernel 采用类似方法 @a2@a37@a56)。
SPIN 是第一个提出将语言安全作为实现动态内核扩展隔离机制的@a13。SPIN 利用 Modula-3 指针来保证执行保密性和完整性,但由于指针是跨隔离边界交换的,因此无法提供故障隔离——一个崩溃的扩展使系统处于不一致状态。
J-Kernel@a85 和 KaffeOS @a6 是最早指出语言安全本身不足以确保隔离故障和终止不受信任的子系统这一问题的内核。 为了支持 Java 中对孤立域的终止,J-Kernel 提出了对跨域共享的所有对象的访问进行中转(mediate)的想法@a85。J-Kernel 引入了一种特殊的功能对象,它封装了在孤立子系统中共享的原始对象的接口。为了支持域终止,由崩溃域创建的所有功能都会被撤销,从而丢弃对已被垃圾回收的原始对象的引用,并通过返回异常来阻止未来的访问。J-Kernel 依靠自定义类加载器来验证跨域接口(即在运行时生成远程指定代理,而不是使用静态 IDL 编译器)。为了实现隔离,J-Kernel 采用了一种特殊的调用约定,允许通过引用传递功能引用,但要求对常规的未封装对象进行深拷贝。由于没有共享对象的所有权约束,J-Kernel 提供的故障隔离模型有一定的局限性:当创建对象的域崩溃时,对共享对象的所有引用都会被撤销,从而将故障传播到通过跨域调用获得这些对象的域中。此外,由于缺乏 "移动 "语义,(即当对象被传递给被调用者时,调用者失去对该对象的访问权限),这意味着隔离需要对对象进行深拷贝,而这对于隔离现代高吞吐量设备驱动程序来说是非常困难的。
KaffeOS 不通过功能引用来中转对共享对象的访问,而是采用了 "写屏障"@a88 技术,这种技术会验证整个系统中的所有指针赋值,因此可以强制执行特定的指针规范@a6。KaffeOS 引入了私有域和特殊共享堆的分离,用于跨域共享对象——显式分离对于执行写屏障检查至关重要(如检查指针是否属于特定堆)。写入障碍用于执行以下约束:1)允许私有堆上的对象拥有指向共享堆上对象的指针,但是 2)共享堆上的对象被限制在同一个共享堆上。在跨域调用中,当共享对象的引用被传递到另一个域时,写入屏障被用来验证约束,并创建一对特殊的对象,负责共享对象的引用计数和垃圾回收。KaffeOS 有以下故障隔离模型:当对象的创建者终止时,其他域保留对该对象的访问权(引用计数确保最终对象在所有共享者终止时被回收)。遗憾的是,虽然其他域能够在对象创建者崩溃后访问这些对象,但这并不足以实现完全隔离——共享对象有可能处于不一致的状态(例如,如果对象更新到一半时发生崩溃),从而可能导致其他域停止或崩溃。与 J-Kernel 类似,隔离对象也需要在跨域调用时进行深拷贝。最后,中转所有指针更新的性能开销很大。
奇点操作系统引入了一种新的故障隔离模型,该模型是围绕静态执行的所有权规范建立的@a39。与 KaffeOS 类似,在奇点中,应用程序使用了隔离的私有堆和用于共享对象的特殊“交换堆”。一个开创性的设计是对交换堆上分配的对象强制执行单一所有权,即同一时间只能有一个域对共享堆上的对象进行引用。在跨域传递对象引用时,对象的所有权会在域之间 "移动"(将对象传递到另一个域后,试图访问该对象会被编译器拒绝)。奇点开发了一系列新颖的静态分析和验证技术,在有垃回收圾的 Sing\# 语言中静态地确保这一属性。单一所有权是实现简洁实用的故障隔离模型的关键——崩溃的域无法影响系统的其他部分——不仅它们的私有堆被隔离,而且新的所有权规范还允许隔离共享堆,即崩溃的域无法触发其他域中共享引用的撤销,也无法让共享对象处于不一致的状态中。此外,单一所有权允许以零拷贝的方式实现安全隔离,即移动语义保证了对象的发送者将失去对该对象的访问权,因此允许接收者在知道发送者无法访问新状态或改变旧状态的情况下更新对象的状态。
在 J-Kernel、KaffeOS 和奇点的启示基础上,我们的工作制定了在安全语言中执行故障隔离的原则,这些原则可以确保所有权系统。与 J-Kernel 类似,我们采用了用代理封装接口的方法。不过,我们通过静态方式生成代理,以避免运行时开销。我们依赖与 KaffeOS 和奇点类似的堆隔离。我们采用堆隔离的主要原因是,可以在不了解堆内对象语义的情况下,回收域的私有堆。我们为共享堆上的对象借用了移动语义,以提供干净的故障隔离,同时支持来自奇点的零拷贝通信。不过,我们将其扩展为只读借用语义,以支持透明域恢复,同时不放弃零拷贝。 由于红叶使用 Rust 实现,因此得益于其所有权规范,我们可以对共享堆上的对象执行移动语义。Rust 基于对线性类型@a86、仿射类型、别名类型@a18@a87 和基于区域的内存管理@a81 的大量研究,并受到 Sing\# @a29、Vault @a30 和 Cyclone@a43 等语言的影响,在不影响语言可用性的前提下,静态地实现了所有权。与严重依赖于共同设计 Sing\#@a29 及其通信机制的奇点不同,我们在 Rust 语言之外开发了红叶的隔离抽象——可交换类型、接口验证和跨域调用代理。这样,我们就能清楚地阐明提供故障隔离所需的最基本原则,并开发出一套独立于语言之外的机制来实现这些原则,可以说,这样就能使这些原则适应特定的设计取舍。最后,我们针对系统的实用性做出了几项设计取舍。我们针对最常见的“迁移线程”模型@a31 而非消息@a39 设计并实施了隔离机制,以避免在关键的跨域调用路径上出现线程上下文切换,并允许使用更自然的编程习语,例如,在红叶中,域接口只是 Rust trait。
= 红叶架构 <l3>
红叶采用微内核系统结构,依靠基于语言的轻量级域实现隔离(@f1)。微内核实现了启动执行线程、内存管理、域加载、调度和中断转发所需的功能。隔离域集合实现了设备驱动程序、操作系统个性(即 POSIX 接口)和用户应用程序(#link(<l45>)[第 4.5 节])。 由于红叶不依赖硬件隔离原语,因此所有域和微内核都运行在 0 环(ring 0)中。 然而,域被限制使用安全的 Rust(即微内核和可信库是红叶中唯一允许使用不安全 Rust 扩展的部分)。
#figure(
image("f01.png"),
caption: [红叶架构],
) <f1>
我们在域之间强制执行堆隔离约束。为了进行通信,域从全局共享堆中分配可共享对象,并交换指向共享堆上分配的对象的特殊指针、远程引用(`RRef<T>`)(#link(<l31>)[第 3.1 节])。所有权规则使我们能够实现跨隔离域的轻量级零拷贝通信(#link(<l31>)[第 3.1 节])
域通过正常的、类型化的 Rust 函数调用进行通信。跨域调用时,线程会在域之间移动,但会在同一堆栈上继续执行。域开发人员为域的入口点及其接口提供接口定义。红叶 IDL 编译器会自动生成创建和初始化域的代码,并检查跨域边界传递的所有类型的有效性(#link(<l315>)[第 3.1.5 节])。
红叶利用受信任的代理对象对所有跨域通信进行调解。代理由 IDL 编译器根据 IDL 定义自动生成(#link(<l315>)[第 3.1.5 节])。在每个域入口处,代理都会检查域是否存活,如果存活,则会创建一个轻量级的继续(continuation),以便在域崩溃时解绑线程的执行。
在红叶中,对对象和 trait 的引用就是能力。在 Rust 中,trait 声明了一个类型必须实现的一组方法,从而提供了一个接口的抽象。域通过跨域调用来交换对 trait 的引用,从而实现其功能。我们依靠基于功能的访问控制@a76 来执行最小特权原则,并实现灵活的操作系统组织:例如,我们实现了几种应用绕过内核直接与设备驱动程序对话的方案,甚至可以利用 DPDK 式的用户级设备驱动程序访问来链接设备驱动程序库。
*保护模型* 红叶背后的核心假设是,我们相信 (1) Rust 编译器能正确实现语言安全,以及 (2) 信任使用了不安全代码的 Rust 核心库,例如实现内部可变性的类型等。红叶的 TCB 包括微内核、实现硬件接口和底层抽象所需的少量可信红叶包、提供硬件资源安全接口的设备板块(如访问 DMA 缓冲区等)、红叶 IDL 编译器和红叶受信编译环境。目前,我们并不处理不安全 Rust 扩展中的漏洞,但我们再次推测,最终所有不安全代码都将通过功能正确性验证@a5@a8@a82。具体来说,RustBelt 项目提供了一个指南,以确保不安全代码被封装在安全接口中@a44。
我们相信设备是非恶意的。未来可以通过使用 IOMMU 来保护物理内存,从而放宽这一要求。最后,我们没有防范侧信道攻击;虽然这些攻击很重要,但解决它们超出了当前工作的范围。我们推测,未来的 CPU 将采用硬件对策来减少信息泄露@a41。
== 域和错误隔离 <l31>
在红叶中,域是信息隐藏、故障隔离和组合的单元。设备驱动程序、内核子系统(如文件系统、网络栈等)和用户程序都作为域加载。每个域的参数之一是微内核系统调用接口的引用。该接口允许每个域创建执行线程、分配内存、创建同步对象等。默认情况下,微内核系统调用接口是域的唯一权限,即域可以影响系统其他部分的唯一接口。不过,域可以为入口函数定义自定义类型,要求在创建时传递对象和接口的附加引用。默认情况下,我们不会为域创建新的执行线程。
不过,每个域都可以在加载域时通过微内核调用的 `init` 函数创建线程。在内部,微内核会跟踪代表每个域创建的所有资源:分配的内存、注册的中断线程等。线程的寿命可能超过创建它们的域,因为它们会进入其他域,并在那里无限期运行。这些线程会继续运行,直到它们返回到崩溃的域,并且该域是它们延续链中的最后一个域。
*错误隔离* 红叶域支持故障隔离。我们按以下方式定义故障隔离。我们说,当进入域的线程之一出现恐慌时,域就会崩溃并需要终止。恐慌可能会使域内可访问的对象处于不一致状态,从而使域内任何线程的进一步运行变得不切实际(也就是说,即使线程没有发生死锁或恐慌,计算结果也是未定义的)。那么,如果以下条件成立,我们就可以说*故障被隔离*了。首先,我们可以将运行在崩溃域内的所有线程解绑到域入口点,并向调用者返回错误信息。其次,后续调用域的尝试会返回错误,但不会违反安全保证或导致恐慌。第三,崩溃域的所有资源都可以安全地回收,也就是说,其他域不会持有对崩溃域堆的引用(堆隔离约束),我们可以回收该域拥有的所有资源,而不会发生泄漏。第四,其他域中的线程会继续执行,并可继续访问由崩溃的域分配、但在崩溃前已转移到其他域的对象。
实施故障隔离具有挑战性。在红叶中,隔离的子系统输出复杂、语义丰富的接口,也就是说,域可以自由交换对接口和对象层次结构的引用。我们做出了几种设计选择,使我们能够干净利落地封装域的状态,同时支持语义丰富的接口和零拷贝通信。
=== 堆隔离与共享 <l311>
*私有和共享堆:* 为了提供跨域的故障隔离并确保域的安全终止,我们要保证跨域堆隔离,即域的私有堆、堆栈或全局数据部分上分配的对象不能从域外访问。这个约束允许我们在执行的任何时刻安全地终止任何域。由于没有其他域持有指向已终止域的私有堆的指针,因此删除整个堆是安全的。
#figure(
image("f02.png"),
caption: []
) <f2>
为了支持高效的跨域通信,我们为可跨域发送的对象提供了一个特殊的全局共享堆。域在共享堆上分配对象的方式与 Rust `Box<T>` 类型在普通堆上分配 `T` 类型的值类似。我们构建了一种特殊类型,即远程引用或 `RRef<T>` ,它可以在共享堆上分配 `T` 类型的值(@f2)。 `RRef<T>` 由两部分组成:一个小的元数据和值本身。 `RRef<T>` 元数据包含当前拥有引用的域的标识符、借用计数器和值的类型信息。`RRef<T>` 元数据和值在共享堆上分配,允许 `RRef<T>` 在最初分配它的域之后继续存在。
*私有堆中的内存分配:* 为了对域的私有堆进行封装,我们采用了两级内存分配方案。在底部,微内核为域提供了一个接口,用于分配无类型的粗粒度内存区域(大于一个页面)。每次粗粒度分配都会记录在*堆注册表*中。要在域的私有堆上进行精细类型分配,每个域都要与提供 Rust 内存分配接口 `Box<T>` 的可信包进行链接。域堆分配遵循 Rust 的所有权规则,即对象超出作用域时会被重新分配。两级方案有以下优点:只分配大内存区域,微内核记录域分配的所有内存,而不会产生显著的性能开销。如果该域发生恐慌,微内核会遍历分配给该域的分配器所分配的所有未类型化内存区域的注册表,并在不调用任何析构函数的情况下将其注销。这种无类型、粗粒度的回收是安全的,因为我们确保了堆隔离约束:其他域对回收的堆没有引用。
=== 可交换类型 <l312>
在共享堆上分配的对象必须遵守以下规则:它们只能由可交换类型组成。可交换类型确保以下约束:共享堆上的对象不能有指向私有堆或共享堆的指针,但可以有指向共享堆上分配的其他对象的 `RRef` 。红叶的 IDL 编译器在生成域的接口时会验证这一不变式(#link(<l315>)[第 3.1.5 节])。我们将可交换类型定义为以下集合: 1) RRef 本身,2)Rust 原始 `Copy` 类型的子集,如 `u32`、`u64`,但不包括一般情况下的引用,也不包括指针,3)由可交换类型构建的匿名(元组、数组)和命名(枚举、结构体)复合类型,4)对具有接收可交换类型方法的`trait`的引用。此外,所有 trait 方法都必须遵循以下调用约定,要求这些方法返回 `RpcResult<T>` 类型,以支持从崩溃域返回的线程的简洁中止语义(#link(<l31>)[第 3.1 节])。IDL 会检查接口定义,并验证所有类型是否格式正确(#link(<l315>)[第 3.1.5 节])。
=== 所有权追踪 <l313>
在红叶中,`RRef<T>` 可以在域之间自由传递。我们允许 `RRef<T>` 被移动或不可变借用。不过,我们对 `RRef<T>` 实施了所有权约束,在跨域调用时保证。通过所有权跟踪,我们可以安全地删除崩溃域所拥有的共享堆上的对象。`RRef<T>` 的元数据部分会记录所有者域和跨域调用时的借用次数。
最初,`RRef<T>` 由分配引用的域所有。如果在跨域调用中将引用转移到另一个域,我们就会更改 `RRef<T>` 中的所有者标识符,将所有权从一个域转移到另一个域。所有跨域通信都由可信代理进行中转,因此我们可以通过代理安全地更新所有者标识符。Rust 的所有权规范确保域内对象始终只有一个远程引用,因此当引用在跨域调用时在域之间移动时,调用者将失去对传递给被调用者的对象的访问权限。如果引用在跨域调用中被不可变借用,我们不会更改 `RRef<T>` 中的所有者标识符,而是递增跟踪 `RRef<T>` 被借用次数的计数器。
*递归引用* `RRef<T>` 可以形成对象的层次结构。为了避免在跨域调用时递归移动层次结构中的所有 `RRef<T>` ,只有对象层次结构的根节点才有有效的所有者标识符(@f2 中只有对象 `X` 有有效的域标识符 `A`,对象 `Y` 没有)。在跨域调用时,根 `RRef<T>` 会被代理更新,从而更改域标识符,在域之间移动 `RRef<T>` 的所有权。这就需要一个特殊的方案,以便在发生崩溃时取消 `RRef<T>` 的分配:我们扫描整个 `RRef<T>` 注册表,清理崩溃域所拥有的资源。为了防止删除层次结构中的子对象,我们的做法是,这些子对象没有有效的 `RRef<T>` 标识符(我们在扫描过程中跳过它们)。根 `RRef<T>` 对象的 `drop` 方法会遍历整个层次结构,并重新分配所有子对象(`RRef<T>` 不能形成循环)。请注意,我们应该小心处理 `RRef<T>` 从层次结构中移出的情况。为了正确地重新分配 `RRef<T>`,我们需要给它分配一个有效的域标识符,也就是说,当 `Y` 从 `X` 移出时,它就会得到一个正确的域标识符。我们用可信的访问器方法对 `RRef<T>` 字段分配进行中转。我们生成的访问器方法提供了从对象字段中取出 `RRef<T>` 的唯一方法。这样,我们就可以对移动操作进行中转,并更新被移动 `RRef<T>` 的域标识符。请注意,对于未命名的复合类型(如数组和元组),无法强制执行访问器。对于这些类型,我们会在跨越域边界时更新所有复合元素的所有权。
*回收共享堆* 通过所有权跟踪,我们可以回收当前由崩溃域拥有的对象的内存。我们对所有已分配的 `RRef<T>` 进行全局注册(@f2)。当域发生恐慌时,我们会浏览注册表,并删除崩溃域拥有的所有引用。如果 `RRef<T>` 被借用,我们会推迟回收,直到借用次数降为零。要取消每个 `RRef<T>` 的分配,我们必须为每种 `RRef<T>` 类型提供一个 `drop` 方法,并能动态识别引用的类型。每个 `RRef<T>` 都有一个由 IDL 编译器生成的唯一类型标识符(IDL 知道系统中的所有 `RRef<T>` 类型,因为它生成了所有跨域接口)。我们将类型标识符与 `RRef<T>` 一起存储,并调用适当的 `drop` 方法来正确地删除共享堆上任何可能的分层数据结构。
=== 跨域调用代理 <l314>
为了实现故障隔离,红叶依靠调用代理对所有跨域调用进行干预(@f2)。代理对象暴露的接口与其所中转的接口完全相同。因此,代理干预对接口用户来说是透明的。为确保隔离性和安全性,代理在每个封装函数中实现了以下功能: 1)在执行调用之前,代理会检查域是否存活。如果域还存活,代理会通过更新微内核中的线程状态来记录线程在域之间移动的事实。当域崩溃时,我们会利用这一信息来解绑所有恰好在域内执行的线程。2)对于每次调用,代理都会创建一个轻量级的继续,以捕获跨域调用前的线程状态。该继续允许我们解绑线程的执行,并向调用者返回错误信息。3)代理在域之间移动作为参数传递的所有 `RRef<T>` 的所有权,或更新所有借用引用的借用计数,使其保持不变。4)最后,代理会封装所有作为参数传递的 trait 引用:代理会为每个 trait 创建一个新的代理,并传递该代理实现的 trait 的引用。
*线程解绑* 要从崩溃域解绑线程的执行,我们需要捕捉线程进入被调用者域之前的状态。对于代理所介导的每个 trait 函数,我们都会使用一个汇编蹦床(trampolime),将所有通用寄存器保存到一个*继续*中。微内核为每个线程维护一个继续栈。每个继续都包含所有通用寄存器的状态和一个指向错误处理函数的指针,该函数的签名与域接口导出的函数相同。如果必须解绑线程,我们会将堆栈恢复到继续所捕获的状态,并在相同的堆栈上以相同的通用寄存器值调用错误处理函数。错误处理函数会向调用者返回错误信息。
#figure(
image("f03.png"),
caption: []
)<f3>
为了在崩溃时干净地返回错误,我们对所有跨域调用执行了以下调用约定:每个跨域函数都必须返回 `RpcResult<T>`,这是一种枚举类型,其中要么包含返回值,要么包含错误(@f3)。这样,我们就可以实现以下约束:从崩溃域中解绑的函数永远不会返回损坏的数据,而是返回一个 `RpcResult<T>` 错误。
=== 接口验证 <l315>
红叶的 IDL 编译器负责验证域接口,并生成在共享堆上执行所有权规范所需的代理代码。红叶 IDL 是 Rust 的一个子集,扩展了多个属性以控制代码的生成(@f3)。这种设计选择使我们能够为开发人员提供熟悉的 Rust 语法,并重新使用 Rust 的解析基础架构。
要实现接口的抽象,我们需要依赖 Rust 的 _trait_。trait 提供了一种定义方法集合的方法,类型必须实现这些方法才能满足 trait 的要求,从而定义了特定的行为。例如,`BDev` trait 要求任何提供该 trait 的类型实现两个方法:`read()` 和 `write()`(@f3)。通过交换对 trait 对象的引用,域可连接到系统的其他部分,并与其他域建立通信。
每个域都为创建 trait 提供了 IDL 定义,允许任何可访问该 trait 的域创建该类型的域(@f3)。标有 _`#[create]`_ 属性的 create trait 既定义了域入口函数的类型,也定义了可用于创建域的 `trait。具体来说,BDev` 域的入口函数将 `PCI` trait 作为参数,并返回一个指向 `BDev` 接口的指针。请注意,当 `BDev` 域与 `BDev` 接口一起创建时,微内核也会返回域 trait,允许域的创建者以后对其进行控制。IDL 会生成用于创建该类型域的 create trait 和微内核代码的 Rust 实现。
*接口检验* 我们在 IDL 编译器的静态分析过程中进行接口验证。编译器首先会解析所有依赖的 IDL 文件,创建统一的抽象语法树 (AST),然后将其传递到验证和生成阶段。在接口验证过程中,我们使用 AST 来提取每个验证类型的相关信息。从本质上讲,我们创建了一个图,其中编码了所有类型的信息以及它们之间的关系。然后,我们使用该图验证每个类型是否可交换,以及是否满足所有隔离约束:跨域接口的方法是否返回 `RpcResult<T>`,等等。
== 零复制通信 <l32>
结合 Rust 的所有权规范和共享堆上执行的单一所有权,我们可以提供隔离,而不会牺牲整个系统的端到端零拷贝。为了利用零拷贝通信,域使用 `RRef<T>` 类型在共享堆上分配对象。每次跨域调用时,域之间都会移动一个可变引用(可对对象进行可写访问的引用),或者借用一个不可变引用。如果调用成功,即被调用者域没有发生恐慌,那么被调用者可能会返回一组 `RRef<T>`,将所有权转移给调用者。与 Rust 本身不同的是,我们不允许借用可变引用。借用可变引用可能会导致域崩溃时出现不一致的状态,因为受损对象会在线程解绑后返回给调用者。因此,我们要求移动和返回所有可变引用。显式返回。如果域崩溃,返回的不是引用,而是 `RpcResult<T>` 错误。
面对崩溃的域和提供透明恢复的要求,零拷贝具有挑战性。典型的恢复协议会重新启动崩溃的域,并重新发出失败的域调用,试图向调用者隐瞒崩溃情况。这通常要求在重新启动调用时作为参数传递的对象在恢复域内可用。可以在每次调用前为每个对象创建一个副本,但这样会带来很大的开销。为了在不增加副本的情况下恢复域,我们依赖于对跨域调用 `RRef<T>` 不可变借用的支持。例如,`BDev` 接口的 `write()` 方法借用了写入块设备的数据的不可变引用(@f3)。如果域借用了不可变引用,Rust 的类型系统会保证域不能修改借用的对象。因此,即使域崩溃,将未修改的只读对象返回给调用者也是安全的。作为恢复协议的一部分,调用者可以再次将不可变引用作为参数重新调用。这样就可以实现透明恢复,而无需在每次调用时创建可能会崩溃的参数备份。
= 实现 <l4>
在引入一系列新颖抽象的同时,我们以实用性和性能为原则来指导红叶的设计。在某种程度上,红叶被设计为全功能商品内核(如 Linux)的替代品。
== 微内核 <l41>
红叶微内核提供了一个最小接口,用于创建和加载隔离域、执行线程、调度、底层中断调度和内存管理。 红叶实现了与 Linux 类似的内存管理机制——buddy@a46 和 slab@a16 分配器的组合为微内核内部的堆分配提供了一个接口(`Box<T>` 机制)。每个域都在内部运行自己的分配器,并直接向内核 buddy 分配器请求内存区域。
我们用汇编实现底层中断进入和退出代码。虽然 Rust 提供了对 x86 中断函数 ABI 的支持(这是一种将 x86 中断堆栈帧作为参数来编写 Rust 函数的方法),但在实践中并没有什么用处,因为我们需要对中断的进入和退出进行干预,例如保存所有 CPU 寄存器。
在红叶中,设备驱动程序是在用户域中实现的(微内核本身不处理除定时器和 NMI 之外的任何设备中断)。域将线程注册为中断处理程序,以处理设备产生的中断。对于每个外部中断,微内核会维护一个等待中断的线程列表。当收到中断时,这些线程会被放回调度程序运行队列。
== 动态加载域 <l42>
在红叶中,域的编译与内核无关,而是动态加载的。动态加载。Rust 本身并不支持动态扩展(除 Splinter@a47 外,现有的 Rust 系统会静态链接其执行的所有代码@a7@a50@a68)。从概念上讲,动态扩展的安全性依赖于以下约束:跨越域边界的所有数据结构的类型,包括入口函数的类型,以及通过入口函数可到达的任何接口传递的所有类型,在整个系统中都是相同的,即具有相同的含义和实现。这样,即使系统的各个部分是单独编译的,也能确保跨域边界的类型安全保证得以保留。
为了确保类型在系统的所有组件中具有相同的含义,红叶依赖于可信的编译环境。该环境允许微内核检查域是否根据相同版本的 IDL 接口定义、相同的编译器版本和标志进行编译。在编译域时,受信任环境会签署包含所有 IDL 文件的指纹和一串编译器标志。微内核会在加载域时验证域的完整性。此外,我们还强制要求域只能使用安全的 Rust 代码,并与白名单上的 Rust 库进行链接。
#figure(
image("f04.png"),
caption: []
) <f4>
*代码生成* 域的创建和加载依赖于 IDL 编译器生成的代码(@f4)。IDL 可确保域边界的安全性,并支持用户定义的域接口。根据域接口定义(@f4, 1)及其创建函数(2),IDL 生成以下代码:1)所有接口的 Rust 实现 (3) 和创建 (4) 特性,2)可信入口点函数 (5) 被置于域的构建树中,与域的其他部分一起编译,以确保域的入口函数与域的创建代码相匹配,从而维护域边界的安全, 3)微内核域创建函数,用于创建具有入口点函数特定类型签名的域 (6);以及 4)该接口的代理实现 (7)。通过控制入口点的生成,我们确保微内核内部和域内部的入口函数类型相匹配。如果域试图通过改变入口函数的类型来违反安全性,编译就会失败。
== 安全设备驱动 <l43>
在红叶中,设备驱动程序是作为普通域实现的,没有额外的权限。与其他域一样,它们也仅限于 Rust 的安全子集。为了访问硬件,我们为设备驱动程序提供了一系列可信包,这些包实现了设备硬件接口的安全接口,例如访问设备寄存器及其 DMA 引擎。例如,ixgbe 设备板块提供了对设备 BAR 区域的访问,并将其提交队列和接收队列抽象为用于从缓冲区添加和删除请求的方法集合。
设备驱动域由 `init` 域在系统启动时创建。每个 PCI 设备都会引用 `pci` 域内实现的 PCI trait。与其他驱动域类似,PCI 驱动程序依赖于可信包来枚举总线上的所有硬件设备。可信设备包构建的 `BARAddr` 对象包含 PCI BAR 区域的地址。我们使用自定义类型保护每个 `BARAddr` 对象,因此它只能在实现访问特定 BAR 区域的可信设备板块内使用。`pci` 域会探测具有匹配设备标识符的设备驱动程序。驱动程序接收到 `BARAddr` 对象的引用,并开始通过其可信包访问设备。
== 设备驱动恢复 <l44>
轻量级隔离机制和简洁的域接口使我们能够利用影子驱动程序实现透明的设备驱动程序恢复@a78。我们将影子驱动程序开发为普通的无特权红叶域。与代理对象类似,影子驱动程序封装了设备驱动程序的接口,并公开一个相同的接口。相比之下,代理相对简单,可以从 IDL 定义中生成,而影子驱动程序则更需要才智,因为它实现了特定于驱动程序的恢复协议。影子驱动程序会中断与驱动程序的所有通信。在正常运行期间,影子驱动程序会将所有调用传递给真正的设备驱动程序。不过,它会保存恢复驱动程序所需的所有信息(例如,对 PCI 接口的引用,以及设备初始化协议的其他部分)。如果驱动程序崩溃,影子驱动程序会收到来自代理域的错误信息。当线程通过继续机制解绑时,代理本身也会收到错误信息。影子不会向调用者返回错误,而是触发域恢复协议。它会创建一个新的驱动程序域,并通过中断驱动程序的所有外部通信,重新执行其初始化协议。
== Rv6 操作系统特性 <l45>
为了评估红叶抽象的通用性,我们在红叶的基础上实现了 Rv6,一个 POSIX 子集操作系统。在高层次上,Rv6 遵循 xv6 操作系统的实现方法@a73,但它是作为一个孤立的红叶域集合来实现的。具体来说,我们将 Rv6 实现为以下域:核心内核、文件系统、网络栈子系统、网络和磁盘设备驱动程序以及用户域集合。用户域通过 Rv6 系统调用接口与核心内核通信。核心内核会将系统调用分配给文件系统或网络堆栈。文件系统本身会与其中一个红叶块设备驱动程序通信,以获取磁盘访问权限。我们实现了三种块设备驱动程序:内存、AHCI 和 NVMe。文件系统实现了日志、缓冲缓存、inode 和命名层。网络子系统实现了 TCP/IP 协议栈并连接到网络设备驱动程序(我们目前只实现了一个支持 10Gbps 英特尔 Ixgbe 设备的驱动程序)。我们不支持 fork() 系统调用的全部语义,因为我们不依赖地址空间,因此无法虚拟和克隆域的地址空间。 相反,我们提供了创建系统调用的组合,允许用户应用程序加载和启动新域@a10。Rv6 启动后会进入一个支持管道和 I/O 重定向的 shell,并能启动与典型 UNIX 系统类似的其他应用程序。
= 评估 <l5>
我们在公开的 CloudLab 网络测试平台上进行所有实验@a72。#footnote[红叶链接:https://mars-research.github.io/redleaf]对于基于网络的实验,我们使用了两台 CloudLab c220g2 服务器,配置了两个主频为 2.6 GHz 的英特尔 E5-2660 v3 10 核 Haswell CPU、160 GB 内存和一个双端口英特尔 X520 10Gb 网卡。我们在 CloudLab d430 节点上运行 NVMe 性能测试,该节点配置了两个 2.4 GHz 64 位 8 核 E5-2630 Haswell CPU 和一个 PCIe 连接的 400GB 英特尔 P3700 系列固态硬盘。Linux 机器运行 64 位 Ubuntu 18.04,内核配置为 4.8.4,没有任何投机执行攻击(speculative execution attack)缓解措施,因为最近的英特尔 CPU 在硬件上解决了一系列投机执行攻击问题。所有红叶实验均在裸机硬件上进行。在所有实验中,我们禁用了超线程、涡轮增压、CPU 空闲状态和频率缩放,以减少性能测试中的差异。
== 域隔离的开销 <l51>
#figure(
image("t1.png"),
caption: []
)<t1>
*基于语言的隔离对比硬件机制* 为了了解基于语言的隔离与传统硬件机制相比有哪些优势,我们将红叶的跨域调用与 seL4 微内核实现的同步 IPC 机制@a27,以及最近利用基于 VMFUNC 的扩展页表(EPT)切换的内核隔离框架@a62 进行了比较。我们选择 seL4,因为它在多个现代微内核中实现了最快的同步 IPC @a58。我们在配置 seL4 时没有使用熔断缓解措施。在 c220g2 上,服务器 seL4 的跨域调用延迟为 834 个周期(@t1)。
最近,英特尔 CPU 引入了两个新的硬件隔离原语——内存保护密钥(MPK)和 EPT 与虚拟机功能的切换——为内存隔离提供支持,开销与系统调用相当@a83(MPK 为 99-105 个周期@a38@a83,VMFUNC 为 268-396 个周期@a38@a58@a62@a83)。遗憾的是,这两种基元(primitives)都需要复杂的机制来实施隔离,例如二进制重写 @a58@a83、硬件断点保护@a38、在管理程序的控制下执行@a54@a58@a62 等。此外,由于 MPK 和 EPT 交换在设计上都不支持特权 0 环代码的隔离,因此需要额外的技术来确保内核子系统的隔离@a62。
为了比较基于 EPT 的隔离技术与红叶中使用的基于语言的技术的性能,我们配置了 LVDs(一种最新的基于 EPT 的内核隔离框架)@a62,以执行 1000 万次跨域调用,并使用 RDTSC 指令测量以周期为单位的延迟。在 LVD 中,跨域调用依靠 VMFUNC 指令切换 EPT 的根,并在被调用域中选择新的栈。然而,LVD 无需额外切换权限级别或页表。在 c220g2 服务器上,一条 VMFUNC 指令需要 169 个周期,而一次完整的调用/回复调用需要 396 个周期(@t1)。
在红叶中,跨域调用是通过调用代理域提供的 trait 对象来启动的。代理域使用微内核系统调用将线程从被调用者域转移到调用者域,创建继续以在调用失败时将线程解绑到入口点,并调用被调用者域的 trait。在返回路径上,类似的序列会将线程从被调用者域移回调用者域。在红叶中,通过代理对象进行的空跨域调用(@t1)会带来 124 个周期的开销。保存线程状态(即创建继续)需要 86 个周期,因为它需要保存所有普通寄存器。传递一个 `RRef<T>` 会增加 17 个周期的开销,因为 `RRef<T>` 会在域之间移动。为了了解透明恢复的底层开销,我们测量了通过影子域执行相同调用的延迟。在影子域的情况下,调用要跨越两个代理和一个用户自建的影子域,由于代理域和影子域的额外跨越,需要 286 个周期。
大多数最新的英特尔 CPU 都支持内存保护密钥的 0 环执行,即保护密钥监督器(PKS)@a3,最终实现了特权内核代码的低开销隔离机制。不过,即使有了低开销的硬件隔离机制,零拷贝故障隔离方案也需要对共享对象的所有权进行规范,而这需要编程语言的支持,即静态分析@a39 或可强制执行单一所有权的类型系统。
#figure(
image("f05.png"),
caption: []
)<f5>
*Rust 的开销* Rust 的内存安全保证是有代价的。除了需要在运行时进行检查以确保安全外,一些 Rust 抽象还需要付出非零的运行时代价,例如实现内部可变性的类型、选项类型等。为了测量 Rust 语言本身带来的开销,我们开发了一个简单的哈希表,该表使用开放式寻址方案,并依靠带有线性探测功能的 Fowler-Noll-Vo (FNV) 哈希函数来存储 8 个字节的键和值。使用相同的散列逻辑,我们开发了三种实现:1)纯 C 语言;2)规范 Rust 语言(Rust 编程手册鼓励的风格);3)C 风格 Rust 语言,本质上使用 C 语言编程习惯,但使用 Rust 语言。具体来说,在 C 风格 Rust 中,我们避免了:1)使用高阶函数;2)使用 `Option<T>` 类型(我们在规范 Rust 代码中使用该类型来区分表中已占用和未占用的条目)。如果没有 `Option<T>` 类型为键值对增加至少一个额外的字节,我们就可以在内存中对键值对进行紧密的缓存对齐表示,从而避免额外的缓存缺失。我们令哈希表中的条目数从 2^12^ 到 2^26^ 不等,并保持哈希表 75% 满。在大多数哈希表大小的情况下,我们的规范 Rust 实现仍然比纯 C 语言慢 25%,而 C 风格 Rust 的性能与纯 C 语言相当,甚至更好,尽管只是 3-10 个周期(@f5)。我们将此归功于 Rust 编译器生成的代码更加紧凑(C-style Rust 中关键 get/set 路径上有 47 条指令,而 C 中有 50 条指令)。
== 设备驱动 <l52>
红叶背后的一个关键假设是,Rust 的安全性适用于开发现代操作系统内核中速度最快的子系统。如今,每个 I/O 请求的延迟时间低至数百个周期,在所有内核组件中,提供访问高吞吐量 I/O 接口、网络适配器和低延迟非易失性 PCIe 附加存储的设备驱动程序的性能预算最为紧张。为了了解 Rust 零成本抽象的开销是否允许开发此类低开销子系统,我们开发了两个设备驱动程序: 1)英特尔 82599 10Gbps 以太网驱动程序(Ixgbe);2)用于 PCIe 附加固态硬盘的 NVMe 驱动程序。
=== Ixgbe 网卡驱动 <l521>
我们将 RedLeaf Ixgbe 驱动程序的性能与 在 Linux 上高度优化的 DPDK 用户空间数据包处理框架@a21 驱动程序的性能进行了比较。DPDK 和我们的驱动程序都在轮询模式下工作,从而使它们达到最高性能。我们令红叶运行几种不同配置:1)`redleaf-driver`:基准应用程序与驱动程序静态链接(这种配置最接近 DPDK 等用户级数据包框架;同样,我们将 Ixgbe 接口直接传递给红叶);2)`redleaf-domain`:基准应用程序在单独的域中运行,但通过代理直接访问驱动程序域(这种配置代表了多个孤立应用程序共享网络设备驱动程序的情况@a38);3)`rv6-domain`:基准应用程序作为 Rv6 程序运行,它首先通过系统调用进入 Rv6,然后调用驱动程序(这种配置类似于商品操作系统内核的设置,其中用户应用程序通过内核网络堆栈访问 I/O 接口)。此外,我们还运行了有影子驱动程序和无影子驱动程序的后两种配置(`redleaf-shadow` 和 `rv6-shadow`),这两种配置会引入额外的跨域来使用影子域(这两种配置会评估透明驱动程序恢复的开销)。在所有测试中,我们都将应用线程固定在单个 CPU 内核上。
#figure(
image("f06.png"),
caption: []
)<f6>
我们发送 64 字节数据包,并测量两种批量大小的性能: 1 个和 32 个数据包(@f6)。在数据包接收测试中,我们使用 DPDK 框架中的快速数据包生成器以线速(line-rate)生成数据包。在数据包发送和接收测试中,由于 Linux 的网络协议栈和同步套接字接口过于通用,其速度仅为 0.89 Mpps(@f6)。在一个批次上,DPDK 达到了 6.7 Mpps,在 RX 和 TX 路径上都比红叶(6.5 Mpps)快 7%(@f6)。在批量处理 32 个数据包时,两个驱动程序都达到了万兆以太网接口的线速性能(14.2 Mpps)。为了了解跨域调用的影响,我们将基准应用程序作为单独的域 (`redleaf-domain`) 和 Rv6 程序 (`rv6-domain`) 运行。跨域的开销在批量为 1 的情况下非常明显,红叶在进行一次跨域(`redleaf-domain`)时,每个内核收发数据包的速度为 4 Mpps,如果调用涉及影子域(redleaf-shadow),则为 2.9 Mpps。在两次跨域的情况下,性能下降到 2.8 Mpps(`rv6-domain`),如果通过影子(`rv6-shadow`)访问驱动程序,性能下降到 2.4 Mpps。在 32 个数据包的批次中,由于所有配置都会使设备达到饱和,因此跨域的开销就会消失。
#figure(
image("f07.png"),
caption: []
)<f7>
*Nullnet* 为了进一步研究不受设备本身限制的隔离开销,我们开发了一个纯软件 `nullnet` 驱动程序,它只需将数据包返回给调用者,而不是将其队列到设备上(@f7)。在 1 个数据包的测试中,多次跨域的开销限制了 nullnet 驱动程序的理论性能。如果应用程序与驱动程序静态链接(`redleaf-driver`),则 `nullnet` 驱动程序的理论性能将从每核 29.5 Mpps 降至从 Rv6 应用程序访问 `nullnet` 时的 5.3 Mpps(`rv6-domain`)。添加阴影驱动程序后,这一数字将降至 3.6 Mpps(`rv6-shadow`)。同样,如果在与驱动程序相同的域中运行应用程序,在 32 个数据包的情况下,`nullnet` 可达到 94 Mpps。当基准代码作为 Rv6 应用程序 (`rv6-domain`) 运行时,性能下降到 67 Mpps,而当 Rv6 应用程序涉及影子驱动程序 (`rv6-shadow`) 时,性能下降到 55 Mpps。
=== NVMe 驱动 <l522>
为了解红叶 NVMe 驱动程序的性能,我们将其与 Linux 内核中的多队列块驱动程序和 SPDK 存储框架中经过优化的 NVMe 驱动程序进行了比较@a42。SPDK 和红叶驱动程序都在轮询模式下工作。与 Ixgbe 类似,我们评估了几种配置:1)静态链接(`redleaf-driver`);2)需要一次跨域(`redleaf-domain`);和 3)作为 Rv6 用户程序(`rv6-domain`)运行。我们在有影子驱动程序(`redleaf-shadow` 和 `rv6-shadow`)和没有影子驱动程序的情况下运行后两种配置。所有测试都仅限于单 CPU 内核。
#figure(
image("f08.png"),
caption: []
)<f8>
我们在 1 个和 32 个请求的批量大小上执行块大小为 4KB 的连续读写测试(@f8)。在 Linux 上,我们使用快速 I/O 生成器 `fio`;在 SPDK 和红叶上,我们开发了类似的基准应用程序,一次性提交一组请求,然后轮询已完成的请求。为了给我们的评估设定一个最佳基线,我们选择了能让我们以最快速度访问设备的配置参数。具体来说,在 Linux 上,我们将 `fio` 配置为使用异步 `libaio` 库来重叠 I/O 提交,并使用直接 I/O 标志绕过页面缓存。
在顺序读取测试中,Linux 上的 `fio` 在批量大小为 1 和 32 的情况下,每个内核分别达到 13K IOPS 和 141K IOPS(@f8)。在批量为 1 的情况下,红叶驱动程序(每核 457K IOPS)比 SPDK(每核 452K IOPS)快 1%。两种驱动程序都能实现最高的设备读取性能。SDPK 的速度较慢,因为它会执行额外的处理,目的是收集每个请求的性能统计数据。在批量大小为 32 的情况下,红叶驱动程序的速度慢了不到 1%(453K IOPS 对比 454K IOPS SPDK)。在批量大小为 32 的连续写入测试中,Linux 与设备的最大吞吐量(约 256K IOPS)相差不到 3%。红叶的速度慢不到百分之一(255K IOPS)。由于 NVMe 与 Ixgbe 相比是一种速度较慢的设备,因此对于两种批量大小的数据而言,跨域的开销都很小。在跨越一个域时,性能甚至提高了 0.7%(我们将其归因于访问设备门铃寄存器的模式不同,设备和 CPU 之间会发生冲突)。
== 应用性能测试 <l53>
为了解安全和隔离对应用工作负载的性能影响,我们开发了几款传统上依赖于操作系统内核快速数据传输的应用软件:1)Magleb 负载平衡器(`maglev`)@a26;2)带有网络功能的键值存储(`kv-store`);3)最小网络服务器(`httpd`)。
#figure(
image("f09.png"),
caption: []
)<f9>
#figure(
image("f10.png"),
caption: []
)
*Maglev 负载平衡器* Maglev 是谷歌开发的一种负载平衡器,用于在一组后端服务器之间平均分配进入的客户端流量@a26。对于每个新流量,Maglev 会在哈希表中进行查找,从可用的后端服务器中选择一个,哈希表的大小与后端服务器的数量成正比(在我们的实验中为 65537)。一致的散列允许流量在所有服务器上均匀分布。然后,Maglev 将所选的后端服务器记录在哈希表(即流量跟踪表)中,用于将同一流量的数据包重定向到同一后端服务器。流量跟踪表的大小与流量的数量成正比(我们在实验中选择了 1M 流量)。处理数据包时,如果数据包是现有流量,则需要在流量跟踪表中查找,或者查找后端服务器并插入流量跟踪表以记录新流量。为了比较红叶的性能,我们开发了 C 语言和 Rust 语言版本的 Meglev 核心逻辑。此外,我们还评估了两个 C 语言版本:一个是作为使用套接字接口的普通 Linux 程序运行,另一个是作为 DPDK 网络处理框架@a21 的网络功能开发。在所有版本中,我们都使用相同代码逻辑,并尽可能采用相同的优化。同样,在所有设置中,我们都限制在一个 CPU 内核上执行。作为 Linux 程序运行时,由于 Linux 内核的同步套接字接口和通用网络协议栈,`maglev` 的单核速度限制在 1 Mpps(@f9)。`maglev` DPDK 功能在 32 个数据包的批次上运行,由于网络设备驱动程序优化良好,每个内核能够达到 9.7 Mpps 的速度。通过与驱动程序静态链接,红叶应用程序 (`redleaf-driver`) 实现了每内核 7.2 Mpps 的速度。随着跨域次数的增加,性能有所下降。作为 Rv6 应用程序运行时,Maglev 在不使用影子域的情况下,每个内核的转发速度为 5.3 Mpps,使用影子域时为 5.1 Mpps。
*键值储存* 从社交网络@a64 到键值数据库@a23,键值存储是一系列数据中心系统事实上的标准构件。 为了评估红叶支持高效数据中心应用开发的能力,我们开发了网络附加键值存储 `kv-store` 的原型。我们的原型在设计上采用了一系列与 Mica@a52 类似的现代优化技术,例如,像 DPDK 这样的用户级设备驱动程序、旨在避免跨核缓存一致性流量的分区设计、保证请求直接指向存储密钥的特定 CPU 内核的数据包流转向、请求处理路径上的无锁和无分配等。我们的实现依赖于一个哈希表,它使用线性探测的开放寻址方案和 FNV 哈希函数。在实验中,我们比较了两种实现的性能:一种是为 DPDK 开发的 C 语言版本,另一种是与驱动程序(`redleaf-driver`)在同一域中执行的 Rust 版本,即最接近 DPDK 的配置。我们评估了两种哈希表大小: 1M 和 16M 条目,三组键值对(`<8B,8B>`, `<16B,64B>`, `<64B,64B>`)。红叶版本是用 C 风格的 Rust 代码实现的,也就是说,我们避免了有运行时开销的 Rust 抽象(如 `Option<T>` 和 `RefCell<T>` 类型)。这确保我们可以控制键值对的内存布局,避免额外的缓存缺失。尽管我们进行了优化,但红叶的性能仅为 C DPDK 版本的 61-86%。性能下降的主要原因是我们的代码使用安全 Rust 中的变长数组(`Vec<T>`)来表示数据包数据。要创建一个响应,我们需要通过调用 `extend_from_slice()` 函数将响应头、键和值复制到响应数据包中,从而对该变长数组进行三次扩展。该函数会检查变长数组是否需要增长,并执行复制。相比之下,C 语言的实现则得益于对 `memcpy()` 的不安全调用。作为练习,我们使用不安全的 Rust 类型转换实现了数据包序列化逻辑,使我们的性能达到了 C 语言的 85-94%。不过,我们不允许在红叶域内使用不安全的 Rust。
*网络服务器* 网页加载的延迟对用户体验和搜索引擎分配的网页排名都起着至关重要的作用@a15@a66。我们开发了一个可提供静态 HTTP 内容的网络服务器 `httpd` 原型。我们的原型使用一种简单的“运行——完成”执行模式,以轮询方式从所有打开的连接中轮询传入的请求。对于每个请求,它都会执行请求解析,并回复所请求的静态网页。我们 我们将我们的实现与事实上的行业标准网络服务器之一 Nginx@a63 进行了比较。在测试中,我们使用了 `wrk` HTTP 负载生成器@a1,并将其配置为以一个线程和 20 个开放连接运行。在 Linux 上,Nginx 每秒可处理 70.9 K 个请求,而在应用程序与驱动程序(`redleaf-driver`)和网络协议栈运行于同一域的配置下,我们的 `httpd` 实现每秒可处理 212 K 个请求(@f9)。具体来说 我们受益于对网络协议栈和网络设备驱动程序的低延迟访问。作为 Rv6 域运行时,`httpd` 实现了每秒 181.4 K 个数据包的速率(如果使用影子域,则为 178.9 K)。
== 设备驱动恢复 <l54>
#figure(
image("f11.png"),
caption: []
)<f11>
为了评估透明设备驱动程序恢复带来的开销,我们开发了一个测试,其中 Rv6 程序访问由内存块设备支持的 Rv6 文件系统。作为 Rv6 程序运行时,基准应用程序使用 4K 块连续读写 Rv6 文件系统中的文件。Rv6 文件系统通过影子驱动程序访问块设备,该驱动程序可在块设备崩溃时执行恢复。测试期间,我们每秒触发一次块设备驱动程序崩溃(@f11)。自动恢复会导致性能略有下降。对于读取时,重启和不重启的平均吞吐量分别为 2062 MB/s 和 2164 MB/s(性能下降 5%)。写入方面,重启后的总吞吐量平均为 356 MB/s,未重启时为 423 MB/s(性能下降 16%)。
= 相关工作 <l6>
近期有些项目使用 Rust 构建底层高性能系统,包括数据存储@a33@a47@a60、网络功能虚拟化@a68、网络引擎 @a74 以及多个操作系统@a17@a24@a50@a51、unikernel@a49 和 hypervisor@a4@a36@a40。Firecracker @a4、英特尔 Cloud Hypervisor@a40 和谷歌 Chrome OS Virtual Machine Monitor@a36 用基于 Rust 的实现取代了 Qemu 硬件仿真器。Redox@a24 利用 Rust 开发了基于微内核的操作系统(微内核和用户级设备驱动程序都用 Rust 实现,但可自由使用不安全的 Rust)。设备驱动程序在 3 环(ring 3)中运行,使用传统硬件机制进行隔离,并使用系统调用与微内核通信。总的来说,所有这些系统都利用 Rust 作为 C 语言的安全替代品,但并没有探索 Rust 在类型和内存安全之外的功能。
Tock 开发了许多原则,以尽量减少在面向硬件的内核代码中使用不安全的 Rust@a50。Tock 的结构是一个最小的核心内核和一系列设备驱动程序(胶囊)。Tock 依靠 Rust 的语言安全来隔离胶囊(在 Tock 中,用户应用程序与商品硬件机制隔离)。为确保隔离,Tock 禁止在胶囊中进行不安全的扩展,但不限制在胶囊和主内核之间共享指针(这与使用指针作为能力的语言系统类似,如 SPIN@a13)。因此,任何一个模块出现故障,整个系统都会停止运行。我们的工作建立在许多设计原则的基础上,这些原则旨在最大限度地减少 Tock 开发的不安全 Rust 代码量,并通过支持故障隔离和扩展的动态加载对这些原则进行了扩展。与 Tock 类似,Netbricks@a68 和 Splinter @a47 也依赖 Rust 来隔离网络功能和用户定义的数据库扩展。这些系统都不支持去分配崩溃子系统的资源、恢复或接口和对象引用的通用交换。
= 结论 <l7>
“是一段旅程,而不是一个终点”@a39,奇点操作系统为影响 Rust 设计的许多概念奠定了基础。反过来,通过在 Rust 本身中应用故障隔离原则,我们的工作完成了这一旅程的循环。然而,红叶只是向前迈出的一步,而不是最终的设计——在实用性和性能原则的指导下,我们的工作首先是一系列机制和一个实验平台,以便未来的系统架构能够利用语言安全。Rust 为系统开发人员提供了我们期待已久的机制:实用、零成本的安全性,以及可强制执行所有权的类型系统。可以说,我们实现的隔离是最关键的机制,因为它为在有故障和不可信组件的系统中确保一系列抽象提供了基础。通过阐明隔离原则,我们的工作将开启未来对隔离和安全抽象的探索:安全动态扩展、细粒度访问控制、最小特权、计算和数据的搭配、透明恢复、和除此之外的很多。
= 致谢
我们要感谢 USENIX ATC 2020 和 OSDI 2020 的评审人员以及我们的指导老师 <NAME>,他的许多真知灼见帮助我们改进了这项工作。此外,我们还要感谢 Utah CloudLab 团队,特别是 <NAME>,感谢他在我们的硬件需求方面给予的持续支持。我们还要感谢 <NAME> 在红叶设备驱动程序方面提供的帮助,以及 <NAME> 在底层性能分析方面提供的帮助。本研究部分得到了美国国家科学基金会(拨款号:1837051 和 1840197)、英特尔和 VMWare 的支持。
|
|
https://github.com/MDLC01/unichar | https://raw.githubusercontent.com/MDLC01/unichar/main/src/README.md | markdown | MIT License | > [!NOTE]
> This file is used to generate [the Typst Universe page](https://typst.app/universe/package/unichar). It is processed by [`/build.py`](/build.py).
# Unichar
This package ports part of the [Unicode Character Database](https://www.unicode.org/reports/tr44/) to Typst. Notably, it includes information from [UnicodeData.txt](https://unicode.org/reports/tr44/#UnicodeData.txt) and [Blocks.txt](https://unicode.org/reports/tr44/#Blocks.txt).
## Usage
This package defines a single function: `codepoint`. It lets you get the information related to a specific codepoint. The codepoint can be specified as a string containing a single character, or with its value.
```example
#codepoint("√").name \
#codepoint(sym.times).block.name \
#codepoint(0x00C9).general-category \
#codepoint(sym.eq).math-class
```
You can display a codepoint in the style of [Template:Unichar](https://en.wikipedia.org/wiki/Template:Unichar) using the `show` entry:
```example
#codepoint("¤").show \
#codepoint(sym.copyright).show \
#codepoint(0x1249).show \
#codepoint(0x100000).show
```
|
https://github.com/ivaquero/book-control | https://raw.githubusercontent.com/ivaquero/book-control/main/README.md | markdown | # 《控制之美》笔记


本仓库文本是 DR_CAN(王天威)一系列 [哔站课程](https://space.bilibili.com/230105574/channel/series) 的学习笔记。同时,结合其著作 [控制之美:卷 1](https://book.douban.com/subject/35934779/) 及[控制之美:卷 2](https://book.douban.com/subject/36556895/) (未包含 Kalman 滤波部分),统一规范了公式和代码。
共包括
- Typst 笔记
- MATLAB 代码
- Simulink 程序
- 福利:控制工具箱 API 梳理
笔记原采用 Markdown 格式,但因该格式输出的 PDF 不够稳定,且样式单一,后转向现代文本工具 [Typst](https://github.com/typst/typst),其安装及使用方法可参考[知乎帖子](https://zhuanlan.zhihu.com/p/642509853)。相信大家会喜欢上 Typst 这个软件。
希望对控制理论感兴趣的朋友,以及 Dr_CAN 的粉丝们,能在这里一起完善和讨论。
## 构建
### 依赖软件
- [Typst](https://github.com/typst/typst)
### 克隆官方仓库
为保证正常编译,请参考 [typst-packages](https://github.com/typst/packages) 上的说明,在如下路径下克隆 `typst-packages` 仓库
- Linux:
- `$XDG_DATA_HOME/typst`
- `~/.local/share/typst`
- macOS:`~/Library/Application Support/typst`
- Windows:`%APPDATA%/typst`
### 使用模版
在上述路径下克隆 [scibook](https://github.com/ivaquero/scibook) 和 [cetz-control](https://github.com/ivaquero/cetz-control),然后在文档中引用
```typst
#import "@local/scibook:0.1.0": *
#import "@local/cetz-control:0.1.0": *
```
## 约定规范
### 公式
- 矩阵
- `[]` 括号
- 加粗斜体,大写
- 向量
- `[]` 括号
- 加粗斜体,小写
### 图表
目前大部分图表采用 [drawio](https://github.com/jgraph/drawio) 制作,后面会逐步使用 [fletcher](https://github.com/Jollywatt/typst-fletcher) 替换,尤其是控制框图。
## 说明
目前存在的样式问题
- 图表
- 部分标题缺失
|
|
https://github.com/typst-community/setup-typst | https://raw.githubusercontent.com/typst-community/setup-typst/main/README.md | markdown | MIT License | # Setup Typst
This action provides the following functionality for GitHub Actions users:
- Installing a version of Typst and adding it to the PATH
- Optionally caching [packages](https://github.com/typst/packages) dependencies
<table align=center><td>
```yaml
- uses: typst-community/setup-typst@v3
- run: typst compile paper.typ paper.pdf
```
</table>
## Usage


### Basic usage
```yaml
name: Render paper.pdf
on: push
jobs:
render-paper:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: typst-community/setup-typst@v3
with:
cache-dependency-path: requirements.typ
# Now Typst is installed and packages will be cached!
- run: typst compile paper.typ paper.pdf
```
### Inputs
- **`typst-token`:** The GitHub token to use when pulling versions from
[typst/typst]. By default this should cover all cases. You shouldn't have to
touch this setting.
- **`typst-version`:** The version of Typst to install. This can be an exact
version like `0.10.0` or a semver range like `0.10` or `0.x`. You can also
specify `latest` to always use the latest version. The default is `latest`.
- **`cache-dependency-path`:** Used to specify the path to dependency file.
Supports a Typst file with lines of `import` keyword.
### Outputs
- **`typst-version`:** The version of Typst that was installed. This will be
something like `0.10.0` or similar.
- **`cache-hit`:** Whether or not Typst was restored from the runner's cache or
download anew.
### Custom combinations
#### Uploading workflow artifact
```yaml
- uses: typst-community/setup-typst@v3
with:
cache-dependency-path: requirements.typ
- run: typst compile paper.typ paper.pdf
- uses: actions/upload-artifact@v4
with:
name: paper
path: paper.pdf
```
#### Expanding font support with Fontist
If your tasks require extending beyond the set of fonts in GitHub Actions runner,
you can employ the Fontist to facilitate custom font installations. Here's an
example showcasing how to use [fontist/setup-fontist] to add new fonts:
```yaml
- uses: fontist/setup-fontist@v2
- run: fontist install "Fira Code"
- uses: typst-community/setup-typst@v3
with:
cache-dependency-path: requirements.typ
- run: typst compile paper.typ paper.pdf --font-path ~/.fontist/fonts
```
## Development

**How do I test my changes?**
Open a draft Pull Request and some magic GitHub Actions will run to test the
action.
[Typst]: https://typst.app/
[typst/typst]: https://github.com/typst/typst
|
https://github.com/dyc3/senior-design | https://raw.githubusercontent.com/dyc3/senior-design/main/room-states.typ | typst | #import "@preview/in-dexter:0.0.5": *
= Maintaining Room State <Chapter::RoomState>
Room State #index[Room State] refers to the state of a Room, which includes, but is not limited to, the following:
- Room Settings (title, description, visibility, queue mode, etc.)
- The current video
- Video Queue
- A list of users in the room
As required by @Req::single-entity, from any client connecting to OTT, it must always appear that OTT is a single entity, even though it could be a distributed system. This means that from anywhere in the world, if 2 clients join a room called "foo", they should see the same state of the Room.
In this document, when we say something is in a "good" or "healthy" state, we mean that the system is functioning as expected and the state of the system is consistent across all Balancers and Monoliths. When we say something is in a "bad" state, we mean that the system is not functioning as expected and the state of the system is inconsistent across Balancers and Monoliths.
== Lost Balancer-Monolith Connections
When a Balancer-Monolith connection is lost, clients connected to that Monolith need to be handled appropriately. Otherwise, the accuracy of room state is compromised.
All client connections that are in rooms on the lost Monolith are no longer valid, so they need to be disconnected and removed
from their rooms. From there, they can reconnect to a Monolith with a new WebSocket connection to the Balancer.
== Duplicate Rooms Across Monoliths <Section::duplicate-rooms-across-monoliths>
As required by @Req::room-uniqueness, 2 Monoliths must never have the same room loaded, as the load balancer should be directing all connections for a given room to the designated Monolith for that room.
In the case that this does happen, the system is in a bad state and it must be resolved. This can occur as a race condition within the context of any number of Balancers. The planned solution to this issue is to have the load balancer unload rooms that were not the
first instance of that particular room. This means that the duplicate instances would be unloaded and the clients could then rejoin the room in a healthy state.
In order to accomplish this, every room must be associated with a "load epoch". The load epoch #index[load epoch] is a system global atomic counter that is incremented every time a room is loaded, maintained in redis.
When a room is loaded, the load epoch is incremented and the room is associated with the current load epoch. There is no need to ever reset the load epoch to 0. If the value rolls over, then the system will still function correctly. However, it must remain in the range of an unsigned 32 bit integer, because JavaScript does not support 64 bit integers #cite(<mdn-js-int>).
Whenever the Balancer is notified of the room load and the room is already loaded, it checks to see if the load epoch of the new room is less than the load epoch of the existing room. If it is, then the old room is unloaded, clients are kicked, and the new room is treated as the source of truth.
Otherwise, the new room is unloaded and the old room is treated as the source of truth.
#figure(
image("figures/duplicate-rooms.svg"),
caption: "Correcting system state following duplicate room instances."
) <Figure::duplicate-rooms>
== Maintaining Room State Across Service Restarts <Section::state-across-restarts>
When OTT is deployed, the Monolith is restarted. To not disrupt end users, room state is constantly being flushed to redis. When OTT starts up, it gets a list of all the rooms that were loaded and tries to restore their state. The problem is that if a Monolith restarts, then it will load all the rooms that are in redis. In a deployment with more than one Monolith, this results in rooms existing on more than one Monolith.
It's possible to simply allow the system to reach equilibrium using the mechanism described in @Section::duplicate-rooms-across-monoliths. However, this would result in a high memory usage on the Monolith upon startup. It would also result in a lot of unnecessary network traffic and load on redis.
The solution is to have rooms be lazy loaded from redis when they are needed. This means that when a client tries to join a room, if the room state is in redis, then the room state will be restored from redis. If the room state is not in redis, then the room will be loaded from the database. This also makes it easier to handle losing Monoliths. If a Monolith is lost, then the clients can reconnect and they will be routed to a new Monolith, which will load the room from redis.
== Migrating Room State Between Monoliths
The solution outlined in @Section::state-across-restarts also enables the ability to migrate room state between Monoliths. #index-main[migration] When a Monolith shuts down, all the clients will be disconnected. When they reconnect, they will be routed to a new Monolith. The new Monolith will load the room state from redis. This results in the room state having been migrated to the new Monolith.
|
|
https://github.com/typst/typst-assets | https://raw.githubusercontent.com/typst/typst-assets/main/README.md | markdown | Apache License 2.0 | # typst-assets
A crate with bundled assets for the Typst compiler.
|
https://github.com/dashuai009/dashuai009.github.io | https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/047.typ | typst |
#let date = datetime(
year: 2023,
month: 8,
day: 20,
)
#metadata((
title: "使用python和qwen处理doc文件",
subtitle: [qwen,win32com,python-docx,textextract],
author: "dashuai009",
description: "",
pubDate: date.display(),
))<frontmatter>
#import "../__template/style.typ": conf
#show: conf
今天帮同学处理了一些docx文件,主要是一些会议通知的文件,总共有一千多份doc、docx、pdf、wps等文件。
目标是提取这些会议通知中的时间、地点、名称、主办单位。
这些文本的格式相对统一,比如
```
通知
一、会议时间:
xxx年xx月xx日xx点
二、会议地点
xxxx
三、xxx
xxx
【通知单位】
年月日
这种算是比较好的,还有啥
通知
一、请xxx于xxx月xx日到xxx参加xxx
xxx
xx
```
两千份通知,横跨半年,至少四种文件格式(pdf、doc、docx、wps),大体格式至少十几种。
手写regex规则是不可能了,这辈子也不可能了。正好想到最近疯狂开源的大模型,文本直接喂给他们,可以帮我总结这些文本。
首先不考虑chatgpt,死贵死贵,2023年8月19日,`16K context $0.003 / 1K tokens`,两百万文本就要110人民币。其次,数据传到境外,明显不太安全,这里还是有些敏感数据的。
找了一圈,发现qwen和llama2还可以(早一个月遇到这个问题可能还没这好弄,感谢开源人士)。后边这个中文一般般,有#link("https://huggingface.co/LinkSoul/Chinese-Llama-2-7b")[LinkSoul微调的模型],我用下来效果一般,我这个任务可能不太对付的问题。前边qwen是阿里开源的,看他们公布的对比测试,很能打,阿里出品,看起来靠谱。(注:我只是对于我的文件进行测试,不代表两个相对好坏)
这两个试用都很方便,hugginface真是大大滴好。qwen文档:#link("https://github.com/QwenLM/Qwen")[Qwen-7B/README_CN.md at main · QwenLM/Qwen-7B (github.com)]
第一次用huggingface,还以为要手动一个个下载`pytorch_model-0001-0008.bin`文件,原来代码里都处理好这些琐事了。直接跑,自动下载。
qwen还依赖flash-attention,官方推荐`git clone -b v1.0.8` ,就别用flash-attention2了,安装会遇到编译问题。
== 文件处理
找了半天没找到合适的库去读doc文件
- textract #link("https://textract.readthedocs.io/en/stable/")[textract 1.6.1 documentation] 这个说是啥都能读,安装好之后会遇到后边这个报错,调用antiword命令处理时有问题。
- 其他好多库都不太支持doc,只支持docx
- 批量转#link("https://www.bilibili.com/read/cv3416134/")[【真技术】批量将doc转为docx的方法 - 哔哩哔哩 (bilibili.com)] 有vba和ps的代码
- python的win32com库可以实现上一种方法,具体如后边代码
- python-docx可以修改和读取docx
```
Traceback (most recent call last):
File "C:\Users\15258\.conda\envs\llm\Lib\site-packages\textract\parsers\utils.py", line 87, in run
pipe = subprocess.Popen(
^^^^^^^^^^^^^^^^^
File "C:\Users\15258\.conda\envs\llm\Lib\subprocess.py", line 1026, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\15258\.conda\envs\llm\Lib\subprocess.py", line 1538, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [WinError 2] The system cannot find the file specified
```
处理pdf、doc都可以同word打开,然后重新saveas,pdf用word打开时会有个提示,按理来说可以在python加个-y的参数,自动选yes,没找到资料,跑脚本的时候手动点的yes,还好也就二三十个。有些pdf有加密,不让其他程序读取内容,这些处理不了,只能人工。
== 提示QWEN去提取信息
简单,直接加用
```
f"找出以下通知的会议名称、会议时间、会议地点和主办单位,结果用逗号隔开\n{text}"
```
text是docx文本。
也就三个步骤:
- 把pdf、doc转成docx
- 读取docx
- 文本加提示词喂给qwen
代码
```python
import os
from win32com import client as wc #导入模块
import textract
word = wc.Dispatch("Word.Application") # 打开word应用程序
base_dir = './docs'
def find_all_file(base, extension):
for root, ds, fs in os.walk(base):
for f in fs:
fullname = os.path.join(root, f)
if f.endswith(extension):
yield os.path.abspath(fullname)
for file in find_all_file(base_dir, ".pdf"):
print(file)
_file = file.replace("pdf", "docx")
print(_file)
if not os.path.exists(_file):
doc = word.Documents.Open(file) #打开word文件
doc.SaveAs(_file, 12)#另存为后缀为".docx"的文件,其中参数12指docx文件
doc.Close() #关闭原来word文件
for file in find_all_file(base_dir, ".doc"):
print(file)
_file = file.replace("doc", "docx")
print(_file)
if not os.path.exists(_file):
doc = word.Documents.Open(file) #打开word文件
doc.SaveAs(_file, 12)#另存为后缀为".docx"的文件,其中参数12指docx文件
doc.Close() #关闭原来word文件
word.Quit()
import os
from docx import Document
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation import GenerationConfig
# 请注意:分词器默认行为已更改为默认关闭特殊token攻击防护。
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B-Chat", trust_remote_code=True)
# 打开bf16精度,A100、H100、RTX3060、RTX3070等显卡建议启用以节省显存
# model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, bf16=True).eval()
# 打开fp16精度,V100、P100、T4等显卡建议启用以节省显存
# model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, fp16=True).eval()
# 使用CPU进行推理,需要约32GB内存
# model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="cpu", trust_remote_code=True).eval()
# 默认使用自动模式,根据设备自动选择精度
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True).eval()
# 可指定不同的生成长度、top_p等相关超参
model.generation_config = GenerationConfig.from_pretrained("Qwen/Qwen-7B-Chat", trust_remote_code=True)
base_dir = './docs' # 通知文件的文件夹
out_file = open("./doc_out2.txt", "w") #结果输出文件
def find_all_file(base): #和上边代码重复了
for root, ds, fs in os.walk(base):
for f in fs:
fullname = os.path.join(root, f)
if f.endswith('.docx'):
yield fullname
cnt = 0
for i in find_all_file(base_dir):
document = Document(i) #读取docx
text = ""
for p in document.paragraphs:
text += p.text #拼接文本
text_format = f"找出以下通知的会议名称、会议时间、会议地点和主办单位,结果用逗号隔开\n{text}"
# 问模型
response, _ = model.chat(tokenizer, text_format, history = None)
cnt += 1
print(cnt, i)
out_file.write("\n" + "==" * 10 + "\n")
out_file.write(f"file_name = {i}\n") # 输出结果
out_file.write(response)
```
== 总结
有了large language model,这种任务一下子简单很多。
结果上,对于比较规整的文件,提取结果非常好。不太规整的文件,人力不好做,大模型也整不明白。
以我的经验,gpt4能把这个任务做的很好,qwen这些开源的7b模型,还是不如人意,比如
- 输出了多余的提示信息,”您好”、”结果如下“等等
- 分不清楚主办单位和被通知人,源文件确实复杂
- 吃内存,4090 24G显存,也就处理4k左右的中文文本,多了爆显存
|
|
https://github.com/atareao/typst-templates | https://raw.githubusercontent.com/atareao/typst-templates/main/book/example/main.typ | typst | MIT License | #import "../template.typ": template
#show: template.with(
title: "Sample book",
subtitle: "test",
author: "<NAME> <a.k.a. atareao>",
front_page_image: "example/images/jason-hudson-l2scWsGyq_U-unsplash.jpg",
code_theme: "example/assets/halcyon.tmTheme",
)
#include "01-chapter-01.typ"
#include "02-chapter-02.typ"
|
https://github.com/ukihot/igonna | https://raw.githubusercontent.com/ukihot/igonna/main/articles/shell-work/cmd.typ | typst | #import "@preview/colorful-boxes:1.2.0": *
#import "@preview/codly:0.2.0": *
#let icon(codepoint) = {
box(
height: 0.8em,
baseline: 0.05em,
image(codepoint)
)
h(0.1em)
}
#show: codly-init.with()
#codly(languages: (
sh: (name: "Command", icon: none, color: none)
))
== コマンド
ここでは、基本的なコマンドを紹介する。
細かいオプションまでは解説をしない。
なお、ここで使用するコマンドはWindows コマンドプロンプトでは使用できない。
=== ファイルの一覧化:ls
まずはフォルダの内容を確認したい。
そのようなときに打つコマンドである。
何回打っても良い.
```sh
ls
```
=== ディレクトリの移動:cd
今いるフォルダから移動したいときに打つ。
```sh
cd {path} // {移動先のパス}へ移動
cd .. // 1つ上のディレクトリへ移動
cd ~ // ホームへ移動
```
#colorbox(
title: "コマンドライン",
color: none,
width: auto,
radius: 2pt,
)[
本書では、コマンドラインへの入力表記において`{}`を代入記号、`//`をコメントとする。これらは実際に入力せず、可読性を補助する。
]
=== 現在地 : pwd
プロンプトに書いてあるディレクトリ名をわざわざ絶対パスで表示する。
あまり使わないが,重大な作業をしているときに使った記憶がある。
```sh
pwd
```
=== ディレクトリの作成 : mkdir
思ったよりお世話になる。
メイクディレクトリと読んでしまうが正解は知らない。
知っておいて損はない。
```sh
mkdir {ディレクトリの名前}
```
=== ファイルの閲覧 : cat
本来は複数のファイルを結合(concat)して表示するコマンドだが、単一のファイルをのぞき見することで使うことが多い。
```sh
cat {ファイル名}
```
=== ページャ : less
本来のファイル閲覧用コマンドだが、大体は`cat`コマンドで足りてしまう。
`less`を使用した後は、Qキーを押下すると終了する。
```sh
less {ファイル名}
```
=== 容量の確認 : du
「このフォルダは何MBあるのか」といった疑問を解決する。
ちなみに、`-hs`オプションを付与すると内訳を非表示にできるため、ファイル数が異常に多いディレクトリで有効である。
```sh
du {フォルダ名}
```
=== 検索 : grep
ファイルを検索することは多々ある。
よく使うオプションつきで紹介する。
```sh
grep -rn {path} -e ${text}
```
- r : 再帰的にサブディレクトリを含める
- n : マッチした行番号を表示
- e : 検索する文字列を指定
=== 改名もしくは移動 : mv
便利だが、個人的にリスクがあると思っているコマンドの1つである。
2つめの引数が存在するパスならそこへ1つ目の引数に指定されたファイルを移動させる。
存在しないパスなら、1つ目の引数に指定されたファイルを2つ目の文字列に改名する。
```sh
mv {path} {path} // 改名
mv {path} {rename} // 新しい名前に変更
```
移動先を誤字脱字すると、その文字列が新しい名前となるので注意が必要である。
ただし、`-iv`オプションを付与すると警告してくれるので必須である。
=== 削除 : rm
`mv`より危険なコマンドである。
削除をコマンドで実施する場合、取り返しがつかない(=ゴミ箱に移動しない)ため、`-iv`オプションを付与して警告を有りにする習慣をつけよう。
```sh
rm -iv {対象ファイル}
```
== パイプとリダイレクト
|
|
https://github.com/Coekjan/typst-upgrade | https://raw.githubusercontent.com/Coekjan/typst-upgrade/master/tests/normal1/entry.incompat.typ | typst | MIT License | #import "@local/pack:0.1.1"
#import "@preview/pack1:1.1.1"
#import "@preview/pack2:2.0.0"
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.2.0/src/exports.typ | typst | Apache License 2.0 | #import "main.typ": diagram, node, edge
#import "all.typ" as fletcher |
https://github.com/barrel111/readings | https://raw.githubusercontent.com/barrel111/readings/main/notes/random-graphs.typ | typst | #import "@local/preamble:0.1.0": *
#import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge
#import "@preview/commute:0.2.0": node, arr, commutative-diagram
#show: project.with(
course: "Mathematics",
sem: "Summer",
title: "Random Graphs",
subtitle: "a first course",
authors: ("<NAME>",),
)
= Introduction to Asymptotics
#definition(
"Asymptotic Equivalence",
)[We say that $f(n)$ is _asymptotically equivalent_ to $g(n)$ and write $f(n) tilde g(n)$ if $f(n) slash g(n) arrow 1$ as $n arrow infinity$.]
#definition[We write $f(n) in O(g(n))$ when there is a $C > 0$ such that for all
sufficiently large $n$, $ abs(f(n)) <= C abs(g(n)). $]
#definition[We write $f(n) = Omega(g(n))$ when there is a $c > 0$ such that for all
sufficiently large $n$, $ abs(f(n)) >= c abs(g(n)). $]
#lemma[ Equivalently, $f(n) = O(g(n))$ iff $limsup_(n to infinity) abs(f(n)) slash abs(g(n)) < infinity.$ ]
#proof[ For convenionce let $Q(n) = abs(f(n)) slash abs(g(n))$. First, the foward
direction. We note that we have $0 <= Q(n) <= C$. As $Q(n)$ is bounded $limsup Q(n)$ clearly
exists and is finite (the sequence ${sup_(n >= k) Q(n)}_(k in N)$ is decreasing
and as it is bounded by below, must converge).
Conversely, assume $limsup Q(n) < infinity$. Let $C = max(lim sup Q(n) + 1, 1)$.
As $C > limsup Q(n)$, it is an eventual upper bound for $Q(n)$. That is to say,
there exists $N in NN_(>0)$ such that for all $n >= N$ $ abs(f(n)) <= C abs(g(n)). $ ]
#lemma[ Equivalently, $f(n) = Omega(g(n))$ iff $liminf_(n to infinity) abs(f(n)) slash abs(g(n)) < infinity. $ ]
#proof[ Same idea as above. ]
#definition[We write $f(n) = Theta(g(n))$ when there are constants $c, C > 0$ such that $ c abs(g(n)) <= f(n) <= C abs(g(n)). $ Equivalently, $f(n) = Theta(g(n))$ iff $f(n) = Omega(g(n))$ and $f(n) = O(g(n))$.
]
#lemma[If $f_1, f_2 in O(g)$ then $f_1 + f_2 = O(g)$.]
#proof[ There exists $C_1, C_2, N_1, N_2 > 0$ such that for $n > N_1$ and $n > N_2$ $ abs(f_1) &<= C_1 abs(g) \ abs(f_2) &<= C_2 abs(g). $ Then,
for $N = max(N_1, N_2)$, we can say that if $n > N$ then $ |f_1 + f_2| <= (C_1 + C_2) |g|. $ ]
#lemma[ If $f_1, f_2 in Omega(g)$ then $f_1 + f_2 in Omega(g)$ too. ]
#proof[ Same idea as above. ]
#lemma[ If $f_1, f_2 in Theta(g)$ then $f_1 + f_2 in Theta(g)$ too. ]
#proof[ Follows from prior two lemmas and definition of $Theta$. ]
#definition[We write $f(n) = o(g(n))$ (or $f(n) << g(n)$) if $f(n) slash g(n) arrow 0$ as $n arrow infinity$.
]
#definition[We write $f(n) = omega(g(n))$ (or $f(n) >> g(n)$) if $f(n) slash g(n) arrow infinity$ as $n arrow infinity$.
]
|
|
https://github.com/refparo/resume | https://raw.githubusercontent.com/refparo/resume/main/README.md | markdown | MIT License | # Chi CV template, but Typst
Rip-off of [rip-off of skyzh's CV](https://github.com/matchy233/chi-cv-template), using [Typst](https://typst.app/).
Like everyone else I'm new to Typst :) This template mainly serves as a "learning" repo for me to get familiar with `typst` functionalities. PRs and suggestions are welcome.
⚠️ The implementation of `fontawesome.typ` is far from perfect and **may** conflict with existing `typst` built-in commands! Please report any issues you find.
`fonts/FontAwesome6.otf` is generated by merging `Font Awesome 6 Free-Solid-900.otf` and `Font Awesome 6 Brands-Regular-400.otf` using [fontforge](https://fontforge.org/en-US/). Original Font Awesome fonts were downloaded from [here (Desktop version)](https://fontawesome.com/download) (6.0.4 as of 2023/04/01).
## Usage
### Using Typst web app
Upload `chicv.typ`, `fontawesome.typ`, `resume.typ` and `fonts/FontAwesome6.otf` to [Typst](https://typst.app/), and then you can edit the CV.
### Locally
Assume that you have installed `typst` cli already and it's in your `$PATH`.
```bash
git clone https://github.com/matchy233/typst-chi-cv-template.git
cd typst-chi-cv-template
typst compile --font-path ./fonts resume.typ resume.pdf
```
## Sample Output

[PDF file](resume.pdf)
|
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/feebf7-2023_fall_TA/extensions/peano.typ | typst | #import "../utils.typ": *
#text(fill: blue)[
=== $NN$的定义,Peano公理 <peano>
]
在提出$NN$的定义这个问题之前,似乎没人想过去关心自然数怎样「定义」,`1+1=2`的不证自明似乎很显然.出于公理化的考量,我们也需要对自然数进行公理化的定义.
#definintion(name: "Peano公理")[
*Peano公理* 提出了基于下面五条的公理体系:
- $0 in NN$
- $forall a in NN, exists ! a^' in NN$,对于每个确定的$a$,在$NN$中总能找到唯一的$a^'$,称为$a$的后继.
- $forall b, c in NN, b=c <=> b^' = c^'$, 也就是说,如果两个数的后继相等,当且仅当这两个数也相等.
- $forall n in NN, n^' != 0$,也就是说,任意一个数的后继不是$0$.
- $forall {S_n}$,其中$S_n$均为命题,如果$S_0$成立,且$S_n => S_(n^')$,则命题对所有自然数均成立,也就是说$forall n, S_n$都是成立的.
]
#text(fill: blue)[
更深入了解 $=>$
- 数域$FF$上的加法,乘法
- 有序集,有序域
]
#pagebreak() |
|
https://github.com/xkevio/typst-anki | https://raw.githubusercontent.com/xkevio/typst-anki/main/README.md | markdown | Creative Commons Zero v1.0 Universal | # typst-anki
Convert `typst` math code to `MathJax` (via pandoc) or `SVG`s (via the typst compiler) for use in Anki flashcards. Click either the `Typst` button or press <kbd>Ctrl + M, T</kbd>. Add custom functions inside [`preamble.py`](src/typst_anki/preamble.py)!
> [!IMPORTANT]
> Use `MathJax` for consistency. The `SVG`s directly from Typst are very misaligned inside the text field.
## Installation
```sh
git clone <EMAIL>:xkevio/typst-anki.git
cd typst-anki/src/typst_anki
mkdir lib # <- this stores external dependencies for Anki.
pip install typst -t ./lib/
pip install pypandoc -t ./lib/
zip -r typst_anki.zip __init__.py typst_input_dialog.py manifest.json ./lib/
```
Then, open Anki > Tools > Addons > Install from file > `typst_anki.zip`.
(Pandoc needs to be installed on your system and available via `$PATH`.) Or, if you wish, use [`just`](https://github.com/casey/just).
## TODO
- [ ] **Feature:** Use Typst HTML export when it releases.
- [ ] **Inconsistency:** `Typst SVG` option uses display math as otherwise small margins will cut parts off while `MathJax` always uses inline math for now.
- [ ] **Issue (?):** It seems to prepend the output on some Linux systems, perhaps because the web engine behind `QWebEngineView` differs.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/latedef/0.1.0/render-examples.typ | typst | Apache License 2.0 | // compile with [typst c render-examples.typ 'example-images/{p}.png']
#let prefix = ```#import "latedef.typ": latedef-setup
```.text
#set page(width: auto, height: auto, margin: 5pt)
#let first = true
#let fail-next = false
#let isolate-next = false
#for (i, s) in read("README.md").split("```typst").enumerate() {
let (example, ..rest) = s.split("```")
if not first and not fail-next {
if isolate-next {
example = example.replace("latedef-setup(", "latedef-setup(group: \"" + str(i) + "\", ")
}
pagebreak(weak: true)
eval(prefix + example, mode: "markup")
}
fail-next = rest.len() > 0 and rest.last().ends-with("<!-- fail-example -->\n")
isolate-next = rest.len() > 0 and rest.last().ends-with("<!-- isolate-example -->\n")
first = false
} |
https://github.com/denkspuren/typst_programming | https://raw.githubusercontent.com/denkspuren/typst_programming/main/README.md | markdown | # Typst Programming
My programming experiments with [Typst](https://typst.app/). Typst is a new programmable markup-based typesetting system.
By chance, I found Typst on Wikipedia. Typst is mentioned in an article on typesetting, see ["Other text formatters"](https://en.wikipedia.org/wiki/Typesetting#Other_text_formatters).
Typst is invented by <NAME> and presented in his Master's thesis titled "[A Programmable Markup Language for Typesetting](https://www.user.tu-berlin.de/laurmaedje/programmable-markup-language-for-typesetting.pdf)" (2022-09-08, TU Berlin).
There is a [project](https://github.com/Myriad-Dreamin/typst.ts) that targets Typst running directly in the browser.
There is the [Typst Example Book](https://sitandr.github.io/typst-examples-book/book/) to learn a lot from.
**Experimental Package Repository**: https://github.com/typst/packages
**Awesome Typst Links**: https://github.com/qjcg/awesome-typst
## `extractText`
[extractText](extractText/extractText.typ) is my very first Typst programm. It fixes an [issue](https://github.com/typst/templates/issues/12#issuecomment-1793845765) with titles in Typst's default templates.
## `wrapText`
Unfortunately, there is no solution in Typst to wrap text around a textbox, see [wrapText](wrapText/README.md). That's too bad!
## Literate Programming for Typst in Typst
Just an idea: I guess it is possible to write Typst programms as literate programms with an appropriate Typst template.
My first attempts towards this idea can be found in folder [LiterateProgramming](LiterateProgramming/) |
|
https://github.com/piepert/philodidaktik-hro-phf-ifp | https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/grundpositionen/kulturtechnik.typ | typst | Other | #import "/src/template.typ": *
== #ix("Philosophie als Kulturtechnik", "Philosophie als Kulturtechnik", "Kulturtechnik")
#ix("<NAME>", "<NAME>") prägt den Begriff der Philosophie als #ix("Kulturtechnik").#en[@Martens2003_MethodenPU[S. 13-42]] Er unterscheidet #ix("Philosophie als Tätigkeit") -- d.i. der Prozess des Erkennens -- und #ix("Philosophie als Tatbestand") -- d.i. die hervorgebrachten Erkenntnisse, Theorien oder Produkte der Tradition.#en[Vgl. @Martens2003_MethodenPU[S. 15]] Ziel des Philosophieunterrichts ist Kompetenzerwerb, Philosophieren lernen, nicht Philosophie-Wissen aneignen.#en[Vgl. @Martens2003_MethodenPU[S. 15 f]]
#ix("Martens", "<NAME>") zeigt, dass Philosophieren stark mit der (westlichen) Kultur verbunden ist und Aspekte anderer Formen der Technik aufweist:
#table(columns: (50%, 50%), stroke: none)[
#show: strong
Philosophieren als Bestandteil der Kultur#en[Vgl. @Martens2003_MethodenPU[S. 30 f]]
][
#show: strong
Philosophieren als Technik#en[Vgl. @Martens2003_MethodenPU[S. 31 f]]
][
+ *genetisch*: historisch Teil der griechisch-europäischen Kultur
+ *anthropologisch*: Teil der menschlichen Natur
+ *deskriptiv*: als reflexive, demokratische Willensbildung
+ *normativ*: ist hilfreich für wissenschaftliche Ansprüche der modernen Welt, aber auch als Selbstzweck und Ausdruck eines sinnvollen, selbstbestimmten Lebens
+ *didaktisch-methodisch*: muss kultiviert werden, niemand wird als Philosoph geboren
+ *legitimatorisch*: zur Kritikfähigkeit, Persönlichkeitsbildung und demokratischen Erziehung
][
+ als *Handwerkskunst* ist Philosophieren nicht rein mechanisch
+ als *Materialkunde* ist sie nicht rein technisch, ebenfalls hilft eine breite Wissensbasis über die Philosophiegeschichte zur Begriffseinordnung beim Philosophieren
+ ist nicht von ihrem *Träger* (dem Philosophierenden) ablösbar
+ Philosophieren ist in drei Hinsichten *elementar*, (1.) grundlegend als Rechenschaftsabgabe über Grundannahmen des Denkens, (2.) in Hinsicht fachlicher Grundlagen Voraussetzungslos möglich und (3.) für humane Lebensgestaltung und rationale Verständigung unverzichtbar
]
#task[Philosophie als Kulturtechnik][
Erklären Sie warum #ix("Martens", "<NAME>") Philosophieren als "Kulturtechnik" bezeichnet!
][
Martens nennt Philosophie eine "Kulturtechnik" als provozierende Analogie zu ähnlichen Tätigkeiten wie dem Lesen, Schreiben und Rechnen. Dabei erfülle sie zwei Kriterien: Sie sei Teil der Kultur und eine Form von Technik.
Kulturell sei sie genetisch Teil des europäischen kulturellen Erbes, anthropologisch Teil der menschlichen Natur, genetisch Teil der westlichen Moderne, normativ Teil einer humanen Lebensweise, didaktisch-methodisch Teil der kultivierbaren Fähigkeiten und damit insgesamt legitimatorisch Teil der Kritikfähigkeit, Persönlichkeitsbildung und demokratischer Erziehung.
Technisch sei sie in der Hinsicht, dass sie nicht rein mechanisch sondern braucht ein Gewisses "Fingerspitzengefühl", sie ist durch die Nützlichkeit der Kenntnisse aus dem Studium der Philosophiegeschichte ebenfalls eine Materialkunde, nicht von ihrem Träger, dem Philosophierenden, ablösbar und insgesamt elementar, also Grundlegend für andere Fähigkeiten und die Reflexion darüber, voraussetzungslos und als Mittel rationaler Verständigung unverzichtbar.
]
#task[Philosophie als #ix("Kulturtechnik")][
Erklären Sie, inwiefern sich die Begriffe "genetisch" und "anthropologisch" im Sinne von Philosophie als #ix("Kulturtechnik") widersprechen können!
][
Martens beschreibt die Philosophie im Sinne einer Kultur sowohl als "genetisch" sowie auch als "anthropologisch". Genetisch sei sie in der Hinsicht, dass sie Teil der griechisch-europäischen Kultur ist, da diese Region als das bezeichnet wird, was wir "Philosophie" nennen. Anthropologisch heißt hier, dass die Philosophie in der menschlichen Natur liegt, wie man daran erkennen kann, dass die Philosophie in vielen Kulturen unabhängig voneinander erkannt werden kann, wie etwa in der alt-indischen und alt-chinesischen Kultur.
Fraglich ist, inwiefern sich diese beiden Eigenschaften widersprechen: Wenn die Philosophie genuin europäisch-griechisch ist, ist sie nicht anthropologisch. Wenn sie anthropologisch ist, ist sie nicht genuin europäisch-griechisch. Wie streng die Genese der Philosophie gemeint ist, bleibt ungeklärt. Je nach Interpretation von Martens Bestimmung der Philosophie als Kulturtechnik kann somit ein Widerspruch erkannt werden.
]
#task(key: "kritikMartens")[Kritik an Martens Ansatz][
In <NAME> Buch "Methodik des Ethik- und Philosophieunterrichts: Philosophieren als elementare Kulturtechnik." wird der dialogisch-pragmatische Ansatz der Philosophie dargestellt. Ein Amazon-Rezensent kritisiert das Buch und Martens Ansatz scharf.#en(key: "kritikMartens-amazon")[
Amazon: "Methodik des Ethik- und Philosophieunterrichts: Philosophieren als elementare Kulturtechnik." https://www.amazon.de/Methodik-Ethik-Philosophieunterrichts-Philosophieren-Kulturtechnik/dp/3937223002#customerReviews (letzter Zugriff am 12.05.2024)
] Fassen Sie die Kritikpunkte des Rezensenten zusammen, benennen Sie das Selbstverständnis der Philosophie, das durch die Kritik propagiert wird und nehmen Sie beurteilt Stellung in der Debatte!
#image("martens_kritik_amazon.png", width: 100%)
][
Der Beitrag ist ein Musterbeispiel für die Rehfus-Martens-Kontroverse, beide Akteure werden auch direkt genannt: <NAME> und <NAME>. Dabei steht besonders ein philosophisches Selbstvertändnis im Zentrum: das esoterische Selbstverständnis. Ist die Philosophie nun mit dem Alltag und der Lebenswelt verknüpfbar oder nicht? Der hier dargestellte Ansatz ist wahrscheinlich in das letztere einzuordnen, während Martens zum ersteren tendieren würde.
Der Rezensent behauptet im groben und ganzen 4 Dinge: Der dialogisch-pragmatische Ansatz ...
+ ... propagiere "Philosophie für jeden" und entwickele diese (nur) aus der Lebenswelt.
+ ... führe dazu, dass Meinungen selbstbewusst dargestellt werden und man auf diese Meinung stolz sein könne.
+ ... mache den Lehrer zu einem Moderator.
+ ... ende in einer Unendlichkeitsspirale individueller Erzählungen, in der "Laberei" und "Bullshit" entstehen würden.
Ich stimme den ersten drei Punkten umfänglich zu, wenn jedoch auch nicht aus der Perspektive und mit dem radikalen Ausmaß, mit dem es diese Rezension tut. Philosophie ist für jedermann zugänglich und entwickelt sich aus der Lebenswelt -- das ist ganz in der Natur der Philosophie, das ist das "Staunen", von dem die alten Griechen gesprochen haben. Dieses kann sich durchaus von der Lebenswelt entfernen, jedoch heißt dies nicht, dass es komplett davon abzulösen ist.
Dass Meinungen erarbeitet und selbstbewusst dargestellt werden, dass man für Werte steht und vertritt, ist dabei nicht nur Teil des Philosophieunterrichts sondern im Zuge der Selbstkompetenz Teil aller Fächer. Und das ist auch gut so -- was will Schule mit der Ausbildung willenloser Marionetten? Die freiheitliche Demokratie lebt von fundiertem, sachlichem Diskurs. Genau das ist ein Ziel des Philosophieunterrichts. Was man daran schlecht findet, kann ich nicht verstehen. Es geht nicht um die Erarbeitung _irgendeiner_ Meinung, sondern einer begründeten Meinung und der argumentativen Prüfung und Auseinandersetzung damit.
Die Rolle des Lehrers als Moderators entspricht ganz dem konstruktivistischem Weltbild der Pädagogik -- SuS könnten sich die Realität nur selbst aneignen, in der radikalsten Form ist das "Vermitteln" von Erkenntnis hier gar nicht möglich. Wenn ich auch keinen radikalen Konstruktivismus vertrete, sehe ich diese Position jedoch insoweit als hilfreich an, als dass besonders das gut gelernt werden kann, was mann selbst auch _macht_. Ein Maß hoher SuS-Tätigkeit sehe ich als Merkmal guten Unterrichts und damit auch diesen Punkt als Vorteil und nicht als ein Nachteil an Martens Ansatz.
Besonders unangenehm ist es, dass hier die Meinung, die sich die SuS erarbeiten, delegitimiert wird. Was heute für die SuS wichtig sein soll, entscheiden die "berühmten Philosophen" -- da werden sich die SuS aber kräftig bedanken. Wer auch immer nur Kant, Descartes, Platon oer Fichte als Authorität über die aktuellen Probleme und Fragestellungen der SuS hebt, versagt Ihnen jedes vom "traditionellen" Weg abkommende Fragen und somit auch die Möglichkeit, neue Philosophen auszubilden, die einmal zu den "berühmten Philosophen" gehören könnten, die der Rezensent hier hervorhebt. Kant ist nicht berühmt, weil er Kant ist, sondern weil er gute, revolutionäre oder aufschlussreiche Ideen hatte. Das Autoritätsargument der "berühmten Philosophen" ist hier komplett fehl am Platz. Wie sollte Sokrates guter Philosoph werden, wenn er Kant vorher gar nicht lesen konnte?
Das esoterische Selbstverständnis der Philosophie, in Verbindung mit "Philosophie für Kinder" statt "Philosophieren mit Kindern" ist für das Bildungsideal des kompetenten Menschen schädlich und nicht förderlich. Niemand leugnet, dass ein Grundwissen über Debatten und allgemeinen philosophiegeschichtlichen Wissens hilfreich und förderlich ist, sogar grundlegend für viele Erkenntnisse in der Philosophie sein kann, doch ist sie aus psychologischen und didaktischen Gründen nicht als alleiniger Unerrichtsinhalt wünschenswert. Das Wiedergeben von philosophiegeschichtlichen Fakten ist nicht Philosophieren.
// Letzten Endes fällt die Rezension doch unter ihre eigene Kritik -- es handelt sich zwar sicher nicht "Bullshit", aber dennoch ist es bloß "Laberei". Wahrlich schrecklich, dass _alle_ eine Meinung haben können!
] |
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Code/two-way.typ | typst | ```ts
onModuleChange() {
this.moduleChange.emit(this.module);
}
@Input() module!: ModuleDetail;
@Output() moduleChange = new EventEmitter<any>();
``` |
|
https://github.com/janusz-bit/CV--pdf | https://raw.githubusercontent.com/janusz-bit/CV--pdf/main/CV%20Janusz%20Chmaruk.typ | typst | #import "@preview/vercanard:1.0.1": *
#set text(lang: "pl")
#show: resume.with(
name: [<NAME>],
accent-color: rgb("f3bc54"),
margin: 2.2cm,
aside: [
#align(center)[#image("image/2024-06-23-17-52-37.png", width: 80%) ]
= Kontakt
// lists in the aside are right aligned
- #link("mailto:<EMAIL>")
- +48 880 741 788
- Hipokratesa 16,\ 18-400 Łomża
= Języki
- Angielski: B2 \ TOEIC test: #link("https://www.etsglobal.org/fr/en/digital-score-report/09E18694EF20509DD45581EAF697E1DC37C03ADB6F89A4BC046EC076C638BF38d1A2eEh0MVdXbTh3OStkN0JoZFRYYklaM0NBTSs3QVdlT3RRRk9EMlBFNFVMd2JN")[#text(fill: green)[link]]
]
)
= Edukacja
#entry([Technik mechatronik], [Ukończono Zespół Szkół Mechanicznych i Ogólnokształcących nr 5 w Łomży z tytułem: Technik mechatronik, \ Kwalifikacje zawodowe:
- E3 Montaż urządzeń i systemów mechatronicznych
- E18 Eksploatacja urządzeń i systemów mechatronicznych
- E19 Projektowanie i programowanie urządzeń i systemów mechatronicznych], [2015-2019])
#entry([Studia - Automatyka i Robotyka],[Politechnika Białostocka:
- I stopień (ukończony), specjalizacja: automatyzacja i informatyzacja procesów
- II stopień (ostatni semestr), specjalizacja: automatyka przemysłowa],[2019-2024])
#entry([<NAME>],[Aktywny członek koła naukowego na Politechnice Białostockiej (zawody robotów w Kolumbi, Brazyli, Litwie, Rumuni):
- #link("https://wm.pb.edu.pl/studenci/kola-naukowe/projekty-studenckie/sumomasters/")[strona koła naukowego: wm.pb.edu.pl/studenci/kola-naukowe/projekty-studenckie/sumomasters/]
- wykonane przeze mnie roboty: #link("https://janusz-bit.github.io/CV/#sec-1")[#text(fill: green)[janusz-bit.github.io/CV/\#sec-1]]],[2022-2024])
= Umiejętności / Uprawnienia
#entry([Uprawnienia SEP],[
Spełniam wymagania kwalifikacyjne do wykonywania pracy na stanowisku EKSPLOATACJI w zakresie obsługi, konserwacji, remontu lub naprawy, montażu lub demontażu dla następujących urządzeń, instalacji i sieci:
\1. urządzenia prądotwórcze przyłączone do sieci przesyłowej lub dystrybucyjnej energii elektrycznej bez względu na wysokość napięcia znamionowego;
\2. urządzenia, instalacje i sieci elektroenergetyczne o napięciu znamionowym nie wyższym niż 1kV;
\11. elektryczne urządzenia w wykonaniu przeciwwybuchowym;
\13. aparatura kontrolno-pomiarowa oraz urządzenia i instalacje automatycznej regulacji, sterowania i zabezpieczeń urządzeń i instalacji wymienionych w pkt 1,2,11
],[Ważne do 17.04.2029])
#entry([Uprawnienia na wózek widłowy UDT],[
Zakres uprawnienia: Wózki jezdniowe podnośnikowe z mechanicznym napędem podnoszenia z wyłączeniem wózków z wysięgnikiem oraz wózków z osobą obsługującą podnoszoną wraz z ładunkiem
],[Ważne do 21.12.2033])
#entry([Aktualne orzeczenie Sanepid],[Aktualne orzeczenie lekarskie do celów sanitarno-epidemiologicznych],[bezterminowe])
#entry([Umiejętność obsługi frezarki],[KIMLA CNC 3-osiowa (starszy model)],[2022-2024, Koło SumoMasters])
= Doświadczenie
#entry([Praktyki zawodowe we Włoszech (ERASMUS)],[EUROCONIC s.r.l. \
Via Diesel - Nucleo industriale],[02.09.2017 - 28.09.2017])
#entry([Praktyki zawodowe w OSM Piątnica],[
Praca przy "tackarkach"
],[08.08.2022 - 26.08.2022])
#entry([Praca wakacyjna w OSM Piątnica],[
- Praca przy "tackarkach", Bosch i innych jako pomocnik mleczarski\
- Pomoc przy dziale utrzymania ruchu, obsługa systemu MWS
],[07.2023-09.2023])
#entry([
#set text(size: 12pt)
Klauzula poufności],[
#set text(size: 10pt)
Wyrażam zgodę na przetwarzanie moich danych osobowych dla potrzeb niezbędnych do realizacji procesu rekrutacji zgodnie z Rozporządzeniem Parlamentu Europejskiego i Rady (UE) 2016/679 z dnia 27 kwietnia 2016 r. w sprawie ochrony osób fizycznych w związku z przetwarzaniem danych osobowych i w sprawie swobodnego przepływu takich danych oraz uchylenia dyrektywy 95/46/WE (RODO).
],[])
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-A980.typ | typst | Apache License 2.0 | #let data = (
("JAVANESE SIGN PANYANGGA", "Mn", 0),
("JAVANESE SIGN CECAK", "Mn", 0),
("JAVANESE SIGN LAYAR", "Mn", 0),
("JAVANESE SIGN WIGNYAN", "Mc", 0),
("JAVANESE LETTER A", "Lo", 0),
("JAVANESE LETTER I KAWI", "Lo", 0),
("JAVANESE LETTER I", "Lo", 0),
("JAVANESE LETTER II", "Lo", 0),
("JAVANESE LETTER U", "Lo", 0),
("JAVANESE LETTER PA CEREK", "Lo", 0),
("JAVANESE LETTER NGA LELET", "Lo", 0),
("JAVANESE LETTER NGA LELET RASWADI", "Lo", 0),
("JAVANESE LETTER E", "Lo", 0),
("JAVANESE LETTER AI", "Lo", 0),
("JAVANESE LETTER O", "Lo", 0),
("JAVANESE LETTER KA", "Lo", 0),
("JAVANESE LETTER KA SASAK", "Lo", 0),
("JAVANESE LETTER KA MURDA", "Lo", 0),
("JAVANESE LETTER GA", "Lo", 0),
("JAVANESE LETTER GA MURDA", "Lo", 0),
("JAVANESE LETTER NGA", "Lo", 0),
("JAVANESE LETTER CA", "Lo", 0),
("JAVANESE LETTER CA MURDA", "Lo", 0),
("JAVANESE LETTER JA", "Lo", 0),
("JAVANESE LETTER NYA MURDA", "Lo", 0),
("JAVANESE LETTER JA MAHAPRANA", "Lo", 0),
("JAVANESE LETTER NYA", "Lo", 0),
("JAVANESE LETTER TTA", "Lo", 0),
("JAVANESE LETTER TTA MAHAPRANA", "Lo", 0),
("JAVANESE LETTER DDA", "Lo", 0),
("JAVANESE LETTER DDA MAHAPRANA", "Lo", 0),
("JAVANESE LETTER NA MURDA", "Lo", 0),
("JAVANESE LETTER TA", "Lo", 0),
("JAVANESE LETTER TA MURDA", "Lo", 0),
("JAVANESE LETTER DA", "Lo", 0),
("JAVANESE LETTER DA MAHAPRANA", "Lo", 0),
("JAVANESE LETTER NA", "Lo", 0),
("JAVANESE LETTER PA", "Lo", 0),
("JAVANESE LETTER PA MURDA", "Lo", 0),
("JAVANESE LETTER BA", "Lo", 0),
("JAVANESE LETTER BA MURDA", "Lo", 0),
("JAVANESE LETTER MA", "Lo", 0),
("JAVANESE LETTER YA", "Lo", 0),
("JAVANESE LETTER RA", "Lo", 0),
("JAVANESE LETTER RA AGUNG", "Lo", 0),
("JAVANESE LETTER LA", "Lo", 0),
("JAVANESE LETTER WA", "Lo", 0),
("JAVANESE LETTER SA MURDA", "Lo", 0),
("JAVANESE LETTER SA MAHAPRANA", "Lo", 0),
("JAVANESE LETTER SA", "Lo", 0),
("JAVANESE LETTER HA", "Lo", 0),
("JAVANESE SIGN CECAK TELU", "Mn", 7),
("JAVANESE VOWEL SIGN TARUNG", "Mc", 0),
("JAVANESE VOWEL SIGN TOLONG", "Mc", 0),
("JAVANESE VOWEL SIGN WULU", "Mn", 0),
("JAVANESE VOWEL SIGN WULU MELIK", "Mn", 0),
("JAVANESE VOWEL SIGN SUKU", "Mn", 0),
("JAVANESE VOWEL SIGN SUKU MENDUT", "Mn", 0),
("JAVANESE VOWEL SIGN TALING", "Mc", 0),
("JAVANESE VOWEL SIGN <NAME>", "Mc", 0),
("JAVANESE VOWEL SIGN PEPET", "Mn", 0),
("JAVANESE CONSONANT SIGN KERET", "Mn", 0),
("JAVANESE CONSONANT SIGN PENGKAL", "Mc", 0),
("JAVANESE CONSONANT SIGN CAKRA", "Mc", 0),
("<NAME>", "Mc", 9),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
("<NAME>", "Po", 0),
(),
("<NAME>", "Lm", 0),
("JAVANESE DIGIT ZERO", "Nd", 0),
("JAVANESE DIGIT ONE", "Nd", 0),
("JAVANESE DIGIT TWO", "Nd", 0),
("JAVANESE DIGIT THREE", "Nd", 0),
("JAVANESE DIGIT FOUR", "Nd", 0),
("JAVANESE DIGIT FIVE", "Nd", 0),
("JAVANESE DIGIT SIX", "Nd", 0),
("JAVANESE DIGIT SEVEN", "Nd", 0),
("JAVANESE DIGIT EIGHT", "Nd", 0),
("JAVANESE DIGIT NINE", "Nd", 0),
(),
(),
(),
(),
("JAVANESE PADA TIRTA TUMETES", "Po", 0),
("JAVANESE PADA ISEN-ISEN", "Po", 0),
)
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/103.%2013sentences.html.typ | typst | 13sentences.html
Startups in 13 Sentences
Want to start a startup? Get funded by
Y Combinator.
Watch how this essay was
written.
February 2009One of the things I always tell startups is a principle I learned
from <NAME>: it's better to make a few people really happy
than to make a lot of people semi-happy. I was saying recently to
a reporter that if I could only tell startups 10 things, this would
be one of them. Then I thought: what would the other 9 be?When I made the list there turned out to be 13:
1. Pick good cofounders.Cofounders are for a startup what location is for real estate. You
can change anything about a house except where it is. In a startup
you can change your idea easily, but changing your cofounders is
hard.
[1]
And the success of a startup is almost always a function
of its founders.2. Launch fast.The reason to launch fast is not so much that it's critical to get
your product to market early, but that you haven't really started
working on it till you've launched. Launching teaches you what you
should have been building. Till you know that you're wasting your
time. So the main value of whatever you launch with is as a pretext
for engaging users.3. Let your idea evolve.This is the second half of launching fast. Launch fast and iterate.
It's a big mistake to treat a startup as if it were merely a matter
of implementing some brilliant initial idea. As in an essay, most
of the ideas appear in the implementing.4. Understand your users.You can envision the wealth created by a startup as a rectangle,
where one side is the number of users and the other is how much you
improve their lives.
[2]
The second dimension is the one you have
most control over. And indeed, the growth in the first will be
driven by how well you do in the second. As in science, the hard
part is not answering questions but asking them: the hard part is
seeing something new that users lack. The better you understand
them the better the odds of doing that. That's why so many successful
startups make something the founders needed.5. Better to make a few users love you than a lot ambivalent.Ideally you want to make large numbers of users love you, but you
can't expect to hit that right away. Initially you have to choose
between satisfying all the needs of a subset of potential users,
or satisfying a subset of the needs of all potential users. Take
the first. It's easier to expand userwise than satisfactionwise.
And perhaps more importantly, it's harder to lie to yourself. If
you think you're 85% of the way to a great product, how do you know
it's not 70%? Or 10%? Whereas it's easy to know how many users
you have.6. Offer surprisingly good customer service.Customers are used to being maltreated. Most of the companies they
deal with are quasi-monopolies that get away with atrocious customer
service. Your own ideas about what's possible have been unconsciously
lowered by such experiences. Try making your customer service not
merely good, but
surprisingly good. Go out of your way to make
people happy. They'll be overwhelmed; you'll see. In the earliest
stages of a startup, it pays to offer customer service on a level
that wouldn't scale, because it's a way of learning about your
users.7. You make what you measure.I learned this one from <NAME>.
[3]
Merely measuring something
has an uncanny tendency to improve it. If you want to make your
user numbers go up, put a big piece of paper on your wall and every
day plot the number of users. You'll be delighted when it goes up
and disappointed when it goes down. Pretty soon you'll start
noticing what makes the number go up, and you'll start to do more
of that. Corollary: be careful what you measure.8. Spend little.I can't emphasize enough how important it is for a startup to be cheap.
Most startups fail before they make something people want, and the
most common form of failure is running out of money. So being cheap
is (almost) interchangeable with iterating rapidly.
[4]
But it's
more than that. A culture of cheapness keeps companies young in
something like the way exercise keeps people young.9. Get ramen profitable."Ramen profitable" means a startup makes just enough to pay the
founders' living expenses. It's not rapid prototyping for business
models (though it can be), but more a way of hacking the investment
process. Once you cross over into ramen profitable, it completely
changes your relationship with investors. It's also great for
morale.10. Avoid distractions.Nothing kills startups like distractions. The worst type are those
that pay money: day jobs, consulting, profitable side-projects.
The startup may have more long-term potential, but you'll always
interrupt working on it to answer calls from people paying you now.
Paradoxically, fundraising is this type of distraction, so try to
minimize that too.11. Don't get demoralized.Though the immediate cause of death in a startup tends to be running
out of money, the underlying cause is usually lack of focus. Either
the company is run by stupid people (which can't be fixed with
advice) or the people are smart but got demoralized. Starting a
startup is a huge moral weight. Understand this and make a conscious
effort not to be ground down by it, just as you'd be careful to
bend at the knees when picking up a heavy box.12. Don't give up.Even if you get demoralized, don't give up. You can get surprisingly
far by just not giving up. This isn't true in all fields. There
are a lot of people who couldn't become good mathematicians no
matter how long they persisted. But startups aren't like that.
Sheer effort is usually enough, so long as you keep morphing your
idea.13. Deals fall through.One of the most useful skills we learned from Viaweb was not getting
our hopes up. We probably had 20 deals of various types fall
through. After the first 10 or so we learned to treat deals as
background processes that we should ignore till they terminated.
It's very dangerous to morale to start to depend on deals closing,
not just because they so often don't, but because it makes them
less likely to.
Having gotten it down to 13 sentences, I asked myself which I'd
choose if I could only keep one.Understand your users. That's the key. The essential task in a
startup is to create wealth; the dimension of wealth you have most
control over is how much you improve users' lives; and the hardest
part of that is knowing what to make for them. Once you know what
to make, it's mere effort to make it, and most decent hackers are
capable of that.Understanding your users is part of half the principles in this
list. That's the reason to launch early, to understand your users.
Evolving your idea is the embodiment of understanding your users.
Understanding your users well will tend to push you toward making
something that makes a few people deeply happy. The most important
reason for having surprisingly good customer service is that it
helps you understand your users. And understanding your users will
even ensure your morale, because when everything else is collapsing
around you, having just ten users who love you will keep you going.Notes[1]
Strictly speaking it's impossible without a time machine.[2]
In practice it's more like a ragged comb.[3]
Joe thinks one of the founders of <NAME> said it first,
but he doesn't remember which.[4]
They'd be interchangeable if markets stood still. Since they
don't, working twice as fast is better than having twice as much
time.Turkish TranslationSpanish TranslationBulgarian TranslationJapanese TranslationPersian Translation
|
|
https://github.com/EpicEricEE/typst-equate | https://raw.githubusercontent.com/EpicEricEE/typst-equate/master/tests/nested/test.typ | typst | MIT License | #import "/src/lib.typ": equate
#set page(width: 6cm, height: auto, margin: 1em)
#show: equate
// Test handling of nested equations.
$ a + b &= lr(\{#block[$ e \ #block[$ f \ g $] $]) $
#set math.equation(numbering: "(1.1)")
$ a + b &= c \
&= lr(\{#block[$ e \ f $] + #block[$ g \ h $]) $
|
https://github.com/TC-Fairplay/member-listing | https://raw.githubusercontent.com/TC-Fairplay/member-listing/main/aktive.typ | typst | MIT License | #import "members-list.typ": members-list
#show: doc => members-list("aktive.csv", "", doc)
|
https://github.com/CL4R3T/QFT_homework | https://raw.githubusercontent.com/CL4R3T/QFT_homework/main/requirements.typ | typst | #import "@preview/problemst:0.1.0": *
#import "@preview/physica:0.9.3": * |
|
https://github.com/0x1B05/nju_os | https://raw.githubusercontent.com/0x1B05/nju_os/main/book_notes/content/02_virtualization_02_memory_01_segement.typ | typst | #import "../template.typ": *
#pagebreak()
== Segmentation
#image("images/2023-12-14-15-50-09.png", width: 30%)
Although the space between the stack and heap is not being used by the process, it is still taking up physical memory when we relocate the entire address space somewhere in physical memory.
Thus, the simple approach of using a base and bounds register pair to virtualize memory is wasteful.
=== Segmentation: Generalized Base/Bounds
To solve this problem, an idea was born, and it is called *segmentation*.
The idea is simple: instead of having just one base and bounds pair in our MMU, why not have a base and bounds pair per logical segment of the address space?
We have three logically-different segments: code, stack, and heap. With a base and bounds pair per segment, we can place each segment independently in physical memory. Just like the figure below:
#image("images/2023-12-14-20-24-44.png", width:50%)
Only used memory is allocated space in physical memory, and thus large address spaces with large amounts of unused address space (which we sometimes call *sparse address spaces*) can be accommodated.
Figure below shows the register values for the example above; each bounds register holds the size of a segment.
#image("images/2023-12-14-20-27-31.png", width:30%)
==== example
Assume a reference is made to virtual address 100 (which is in the code segment).
- When the reference takes place (say, on an instruction fetch), the hardware will add the base value to the offset into this segment (100 in this case) to arrive at the desired physical address: 100 + 32KB, or 32868.
- It will then check that the address is within bounds (100 is less than 2KB), find that it is, and issue the reference to physical memory address 32868.
Now let’s look at an address in the heap, virtual address 4200.
- If we just add the virtual address 4200 to the base of the heap (34KB), we get a physical address of 39016, which is not the correct physical address.
- What we need to first do is extract the offset into the heap, i.e., which byte(s) in this segment the address refers to. Because the heap starts at virtual address 4KB (4096), the offset of 4200 is actually `4200-4096`, or `104`.
- We then take this offset (104) and add it to the base register physical address (34K) to get the desired result: 34920.
==== The segmentation fault
The term segmentation fault or violation arises from a memory access on a segmented machine to an illegal address.
What if we tried to refer to an illegal address, such as 7KB which is beyond the end of the heap?
You can imagine what will happen: the hardware detects that the address is out of bounds, traps into the OS, likely leading to the termination of the offending process. Then *segmentation fault*!!
#tip("Tip")[
Humorously, the term persists, even on machines with no support for segmentation at all.
]
=== Which Segment Are We Referring To?
How does it know the offset into a segment, and to which segment an address refers?
One common approach, sometimes referred to as an *explicit* approach:
- based on the top few bits of the virtual address
#tip("Tip")[
this technique was used in the VAX/VMS system
]
In our example above, we have three segments; thus we need two bits to accomplish our task.
If we use the top two bits of our 14-bit virtual address to select the segment, our virtual address looks like this:
#image("images/2023-12-14-20-37-08.png", width: 80%)
- The top two bits are 00, the hardware knows the virtual address is in the code segment, and thus uses the code base and bounds pair to relocate the address to the correct physical location.
- physical_addr = virtual_addr + base
- If the top two bits are 01, the hardware knows the address is in the heap, and thus uses the heap base and bounds.
- physical_addr = offset + base
#tip("Tip")[
- offset = virtual_addr - segment_virtual_start_addr
- Note the offset eases the bounds check too: we can simply check if the offset is less than the bounds; if not, the address is illegal.
]
If base and bounds were arrays (with one entry per segment), the hardware would be doing something like this to obtain the desired physical address:
```c
// get top 2 bits of 14-bit VA
Segment = (VirtualAddress & SEG_MASK) >> SEG_SHIFT
// now get offset
Offset = VirtualAddress & OFFSET_MASK
if (Offset >= Bounds[Segment])
RaiseException(PROTECTION_FAULT)
else
PhysAddr = Base[Segment] + Offset
Register = AccessMemory(PhysAddr)
```
In our running example:
- `SEG_MASK` -> `0x3000`,
- `SEG_SHIFT` -> `12`
- `OFFSET_MASK` -> `0xFFF`.
Some systems put *code* in the same segment as the *heap* and thus use only one bit to select which segment to use.
=== Implicit approach
The hardware determines the segment by noticing how the address was formed.
- If, for example, the address was generated from the program counter (i.e., it was an instruction fetch), then the address is within the code segment.
- If the address is based off of the stack or base pointer, it must be in the stack segment.
- Any other address must be in the heap.
=== What About The Stack?
one critical difference: it *grows backwards*, translation must proceed differently.
- In physical memory, it starts at 28KB and grows back to 26KB.
- Corresponding to virtual addresses 16KB to 14KB.
The first thing we need is a little extra hardware support. Instead of just base and bounds values, the hardware also needs to know which way the segment grows.
#image("images/2023-12-14-20-50-41.png", width: 50%)
==== example
In this example, assume we wish to access virtual address 15KB, which should map to physical address 27KB. Our virtual address, in binary form, thus looks like this: 11 1100 0000 0000 (hex 0x3C00). The hardware uses the top two bits (11) to designate the segment, but then we are left with an offset of 3KB(`segment_virtual_start_addr - virtual_addr`->`18-15`).
To obtain the correct negative offset, we must *subtract the maximum segment size* from 3KB:
- In this example, suppose that a segment can be 4KB, and thus the correct *negative_offset = `3KB - 4KB = -1KB`* .
- We simply add the negative offset (-1KB) to the base (28KB) to arrive at the correct physical address: 27KB.
#tip("Tip")[
The bounds check can be calculated by ensuring the absolute value of the negative offset is less than the segment’s size.
]
=== Support for Sharing
Specifically, to save memory, sometimes it is useful to share certain memory segments between address spaces. In particular, *code sharing* is common and still in use in systems today.
To support sharing, we need a little extra support from the hardware, in the form of *protection bits*:
- Add a few bits per segment, indicating whether or not a program can read or write a segment, or perhaps execute code that lies within the segment.
By setting a code segment to read-only, the same code can be shared across multiple processes, without worry of harming isolation.
While each process still thinks that it is accessing its own private memory, the OS is secretly sharing memory which cannot be modified by the process, and thus the illusion is preserved.
An example: the code segment is set to read and execute, and thus *the same physical segment in memory could be mapped into multiple virtual address spaces*
#image("images/2023-12-14-21-05-04.png", width: 80%)
In addition to checking whether a virtual address is within bounds, the hardware also has to check whether a particular access is permissible.
If a user process tries to write to a read-only segment, or execute from a non-executable segment, the hardware should raise an exception, and thus let the OS deal with the offending process.
=== Fine-grained vs. Coarse-grained Segmentation
*coarse-grained*: it chops up the address space into relatively large, coarse chunks.
*fine-grained*: more flexible and allowed for address spaces to consist of a large number of smaller segments
Supporting many segments requires even further hardware support, with a *segment table* of some kind stored in memory. Such segment tables usually support the creation of a very large number of segments, and thus enable a system to use segments in more flexible ways than we have thus far discussed.
The thinking at the time was that by having *fine-grained* segments, the OS could better learn about which segments are in use and which are not and thus utilize main memory more effectively.
=== OS Support
The first is an old one: what should the OS do on a context switch?
- the segment registers must be saved and restored.
The second, and more important, issue is managing free space in physical memory.
- previous fixed size -> easy
- now variable-sized
==== external fragmentation
The general problem that arises is that physical memory quickly becomes full of little holes of free space, making it difficult to allocate new segments, or to grow existing ones. We call this problem *external fragmentation*
#image("images/2023-12-14-21-13-52.png", width: 80%)
In the example, a process comes along and wishes to allocate a 20KB segment. In that example, there is 24KB free, but not in one contiguous segment (rather, in three non-contiguous chunks). Thus, the OS cannot satisfy the 20KB request.
One solution: to compact physical memory by rearranging the existing segments.
However, compaction is expensive, as copying segments is memory-intensive and generally uses a fair amount of processor time.
A simpler approach is to use a free-list management algorithm that tries to keep large extents of memory available for allocation.
There are literally hundreds of approaches that people have taken, including classic algorithms like *best-fit* (which keeps a list of free spaces and returns the one closest in size that satisfies the desired allocation to the requester) *worst-fit*, *first-fit*, and more complex schemes like *buddy algorithm*.
No matter how smart the algorithm, external fragmentation will still exist; thus, a good algorithm simply attempts to minimize it. There is no one “best” way to solve the problem.
The only real solution (as we will see in forthcoming chapters) is to avoid the problem altogether, by never allocating memory in variable-sized chunks.
=== Summary
problems:
- The first, as discussed above, is external fragmentation.
- The second and perhaps more important problem is that segmentation still isn’t flexible enough to support our fully generalized, sparse address space.
#tip("Tip")[
If we have a large but sparsely-used heap all in one logical segment, the entire heap must still reside in memory in order to be accessed.
]
== Free Space Management
- fixed-sized units -> easy
- variable-sized units -> more difficult
=== Assumptions
- a basic interface such as that provided by `malloc()` and `free()`.
#tip("Tip")[
- Note the implication of the interface: the user, when freeing the space, does not inform the library of its size; thus, the library must be able to figure out how big a chunk of memory is when handed just a pointer to it.
- The space that this library manages is known historically as the `heap`, and the generic data structure used to manage free space in the heap is some kind of *free list*.
]
- For the sake of simplicity, we further assume that primarily we are concerned with *external fragmentation*
#tip("Tip")[
Allocators could of course also have the problem of *internal fragmentation*, if an allocator hands out chunks of memory bigger than that requested, any unasked for (and thus unused) space in such a chunk is considered internal fragmentation
]
- We’ll also assume that once memory is handed out to a client, it cannot be relocated to another location in memory. that memory region is essentially “owned” by the program (and cannot be moved by the library) until the program returns it via a corresponding call to `free()`.
#tip("Tip")[
no *compaction* of free space is possible
]
- We’ll assume that the allocator manages a contiguous region of bytes. For simplicity, we’ll just assume that the region is a single fixed size throughout its life.
=== Low-level Mechanisms
some common mechanisms used inmost allocators:
- the basics of splitting and coalescing
- how one can track the size of allocated regions
- how to build a simple list inside the free space to keep track of what is free and what isn’t
==== Splitting and Coalescing
A free list contains a set of elements that describe the free space still remaining in the heap.
Assume the following 30-byte heap:
#image("images/2023-12-18-07-28-17.png", width: 60%)
Then the free list:
#image("images/2023-12-18-07-28-34.png", width:60%)
===== Splitting
If the request is for something smaller than 10 bytes?
It will find a free chunk of memory that can satisfy the request and split it into two. The first chunk it will return to the caller; the second chunk will remain on the list.
If a request for 1 byte were made:
#image("images/2023-12-18-07-29-57.png", width:60%)
===== Coalescing
Take our example from above once more (free 10 bytes, used 10 bytes, and another free 10 bytes).
#image("images/2023-12-18-07-28-17.png", width: 60%)
What happens when an application calls free(10), thus returning the space in the middle of the heap?
If we simply add this free space back into our list without too much thinking:
#image("images/2023-12-18-07-32-22.png", width: 60%)
#tip("Tip")[
If a user requests 20 bytes, a simple list traversal will not find such a free chunk, and return failure.
]
The idea is simple: when returning a free chunk in memory, look carefully at the addresses of the chunk you are returning as well as the nearby chunks of free space; if the newly freed space sits right next to one (or two, as in this example) existing free chunks, merge them into a single larger free chunk.
#image("images/2023-12-18-07-33-25.png", width: 40%)
==== Tracking The Size Of Allocated Regions
The interface to `free(void *ptr)` does not take a size parameter:
It is assumed that given a pointer, the malloc library can quickly determine the size of the region of memory being freed and thus incorporate the space back into the free list.
To accomplish this task, most allocators store a little bit of extra information in a header block which is kept in memory, usually just before the handed-out chunk of memory.
We are examining an allocated block of size 20 bytes, `ptr = malloc(20);`
#image("images/2023-12-18-07-34-09.png", width: 70%)
#tip("Tip")[
When a user requests N bytes of memory, the library searches for *a free chunk of size N plus the size of the header*.
]
===== The header
The header minimally contains
- the size of the allocated region
- additional pointers to speed up deallocation
- a magic number to provide additional integrity checking
- ....
Let’s assume a simple header which contains the size of the region and a magic number:
```c
typedef struct __header_t {
int size;
int magic;
} header_t;
```
When the user calls `free(ptr)`, the library then uses simple pointer arithmetic
to figure out where the header begins:
```c
void free(void *ptr) {
header_t *hptr = (void *)ptr - sizeof(header_t);
...
```
#image("images/2023-12-18-07-39-54.png", width: 70%)
After obtaining such a pointer to the header, the library can easily:
- determine whether the magic number matches the expected value as a sanity check (`assert(hptr->magic == 1234567)`)
- calculate the total size of the newly-freed region via simple math (i.e., adding the size of the header to size of the region).
==== Embedding A Free List
How do we build a linked list inside the free space itself?
Assume we have a 4096-byte chunk of memory to manage. We first have to initialize said list; initially, the list should have one entry, of size 4096 (minus the header size).
```c
typedef struct __node_t {
int size;
struct __node_t *next;
} node_t;
```
Initializes the heap and puts the first element of the free list inside that space.
#tip("Tip")[
We are assuming that the heap is built within some free space acquired via a call to the system call `mmap()`
]
```c
// mmap() returns a pointer to a chunk of free space
node_t *head = mmap(NULL, 4096, PROT_READ|PROT_WRITE,
MAP_ANON|MAP_PRIVATE, -1, 0);
head->size = 4096 - sizeof(node_t);
head->next = NULL;
```
After running this code, the status of the list is that it has a single entry, of size 4088.
The head pointer contains the beginning address of this range; let’s assume it is 16KB (though any virtual address would be fine).
#image("images/2023-12-18-07-49-18.png", width: 70%)
Let’s imagine that a chunk of memory is requested, say of size 100 bytes.
The library will first find a chunk that is large enough to accommodate the request; because there is only one free chunk (size: 4088), this chunk will be chosen.
Then, the chunk will be split into two: one chunk big enough to service the request, and the remaining free chunk. Assuming an 8-byte header (an integer size and an integer magic number). Upon the request for 100 bytes, the library allocated 108 bytes out of the existing one free chunk.
#image("images/2023-12-18-07-50-48.png", width: 70%)
Let’s look at the heap when there are three allocated regions, each of 100 bytes (or 108 including the header).
#image("images/2023-12-18-10-40-49.png", width: 70%)
Calling free(16500) (the value 16500 = 16KB+108B).This value is shown in the previous diagram by the pointer `sptr`.
#image("images/2023-12-18-10-42-36.png", width: 70%)
Let’s assume now that the last two in-use chunks are freed. Without coalescing, you might end up with a free list that is highly fragmented:
#image("images/2023-12-18-10-43-19.png", width: 70%)
The solution is simple: go through the list and *merge* neighboring chunks; when finished, the heap will be whole again.
==== Growing The Heap
Specifically, what should you do if the heap runs out of space?
The simplest approach is just to fail.
Most traditional allocators start with a small-sized heap and then request more memory from theOS when they run out.
- Typically, this means they make some kind of system call (e.g., `sbrk` in most UNIX systems) to grow the heap, and then allocate the new chunks from there. To service the `sbrk` request,
- the OS finds free physical pages
- maps them into the address space of the requesting process
- returns the value of the end of the new heap
=== Basic Strategies
The ideal allocator is both fast and minimizes fragmentation.
The stream of allocation and free requests can be arbitrary (after all, they are determined by the programmer), any particular strategy can do quite badly given the wrong set of inputs.
==== Best Fit
First, search through the free list and find chunks of free memory that are as big or bigger than the requested size.
Then, return the one that is the smallest in that group of candidates; this is the so called best-fit chunk (it could be called *smallest fit* too).
A full search of free space is required
==== Worst Fit
Find the largest chunk and return the requested amount
Keep the remaining (large) chunk on the free list.
A full search of free space is required. Worse, most studies show that it performs badly, leading to excess fragmentation while still having high overheads.
==== First Fit
finds the first block that is big enough and returns the requested amount to the user
the remaining free space is kept free for subsequent requests.
The advantage of First fit is speed.
But Sometimes pollutes the beginning of the free list with small objects.
Thus, how the allocator manages the free list’s order becomes an issue. One approach is to use *address-based ordering*: by keeping the list ordered by the address of the free space, coalescing becomes easier, and fragmentation tends to be reduced.
==== Next Fit
The next fit algorithm keeps an extra pointer to the location within the list where one was looking last.
The idea is to spread the searches for free space throughout the list more uniformly, thus avoiding splintering of the beginning of the list.
=== Other Approaches
==== Segregated Lists
The basic idea is simple:
if a particular application has one (or a few) popular-sized request that it makes, keep a separate list just to manage objects of that size; all other requests are forwarded to a more general memory allocator.
The benefits:
- fragmentation is much less of a concern
- allocation and free requests can be served quite quickly when they are of the right size, as no complicated search of a list is required
This approach introduces new complications into a system:
How much memory should one dedicate to the pool of memory that serves specialized requests of a given size?
The *slab allocator* handles this issue in a rather nice way.
===== slab allocator
Specifically, when the kernel boots up, it allocates a number of object caches for kernel objects that are likely to be requested frequently (such as locks, file-system inodes, etc.); the object caches thus are each segregated free lists of a given size and serve memory allocation and free requests quickly.
- When a given cache is running low on free space, it requests some slabs of memory from a more general memory allocator .
#tip("Tip")[
the total amount requested being a multiple of the page size and the object in question
]
- When the reference counts of the objects within a given slab all go to zero, the general allocator can reclaim them from the specialized allocator, which is often done when the VM system needs more memory.
The slab allocator also goes beyond most segregated list approaches by keeping free objects on the lists in a pre-initialized state.
By keeping freed objects in a particular list in their initialized state, the slab allocator thus avoids frequent initialization and destruction cycles per object and thus lowers overheads noticeably.
==== Buddy Allocation
Some approaches have been designed around making *coalescing* simple. One good example is found in the *binary buddy allocator*.
In such a system, free memory is first conceptually thought of as one big space of size 2^N.
When a request for memory is made, the search for free space recursively divides free space by two until a block that is big enough to accommodate the request is found (and a further split into two would result in a space that is too small). At this point, the requested block is returned to the user.
Here is an example of a 64KB free space getting divided in the search for a 7KB block:
#image("images/2023-12-18-12-17-32.png", width: 60%)
In the example, the leftmost 8KB block is allocated (as indicated by the darker shade of gray) and returned to the user.
#tip("Tip")[
Note that this scheme can suffer from *internal fragmentation*, as you are only allowed to give out power-of-two-sized blocks.
]
The beauty of buddy allocation is found in what happens *when that block is freed*.
When returning the 8KB block to the free list,
- The allocator checks whether the “buddy” 8KB is free; if so, it coalesces the two blocks into a 16KB block.
- The allocator then checks if the buddy of the 16KB block is still free; if so, it coalesces those two blocks.
This recursive coalescing process continues up the tree, either restoring the entire free space or stopping when a buddy is found to be in use.
The reason buddy allocation works so well is that it is simple to determine the buddy of a particular block.
The address of each buddy pair only differs by a single bit; which bit is determined by the level in the buddy tree.
==== Other Ideas
One major problem with many of the approaches described above is their lack of *scaling*.
Specifically, searching lists can be quite slow. More complex data structures to address these costs, trading simplicity for performance.
Examples include balanced binary trees, splay trees, or partially-ordered trees..
Given that modern systems often have multiple processors and run multi-threaded workloads. It is not surprising that a lot of effort has been spent making allocators work well on multiprocessor-based systems.
the glibc allocator
|
|
https://github.com/CHHC-L/ciapo | https://raw.githubusercontent.com/CHHC-L/ciapo/master/README.md | markdown | MIT License | # ciapo
Yet another simplistic Typst template for presentations.
Based on [diapo](https://github.com/lvignoli/diapo). Add some features but keep it a single-file template.
## Features
- Still as simple as diapo
- Slide for transition, long page, and references
- Header with previous headings (if any) for better navigation
## Usage
Copy the [template](./template.typ) to your project folder and start your document with a global show rule using `diapo.with()`.
Then just write as you like.
For headings, use `=` for the first level, `==` for the second, and so on.
To get a transition slide, use `#transition[some text]`.
To get a long page (e.g. for demonstrating long code), use `#longpage(times)[some text]`. For example, `#longpage(3)[some text]` will generate a page with three times the height of the normal page.
For references page, use `#refpage[your reference]`.
To change font, search in the template for `font` and replace it.
## Potential bugs
When setting the header, as the query for the header cannot simply obtain the locale of the header (that is, we cannot directly determine whether a header is located on the current page), the rules are a little inelegant to maintain. And when there is no text under the level-1 heading, the header might be incorrect.
## Minimal example
This will give you [this](./examples/example.pdf). For more examples, see [examples](./examples).
```typ
#import "../template.typ": diapo, transition
#show: diapo.with(
title: "My last vacations",
author: "<NAME>",
date: "2023-04-20",
// display_lastpage: false,
)
= Introduction
It was great!
#lorem(20)
#transition[Day one]
= Travelling
#lorem(30)
#lorem(30)
= Relax
#align(horizon)[
#set text(size: 28pt)
$ e^(i pi) + 1 = 0 $
]
= The journey back home
It was exhausting.
= Conclusion
That was short.
``` |
https://github.com/AliothCancer/AppuntiUniversity | https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/capitoli_dispositivi/01ValvoleCardiache.typ | typst |
= Valvole Cardiache
== Apertura e chiusura delle valvole
L'apertura tra ogni atrio e il suo ventricolo è regolata da
una valvola atrioventricolare (AV). La valvola AV è
formata da lembi sottili di tessuto unito alla base
a un anello di tessuto connettivo. I lembi sono lievemente
ispessiti ai margini e sono connessi al lato ventricolare
attraverso tendini ricchi di collagene, le corde tendinee.
La maggior parte delle corde tendinee si salda ai margini
dei lembi delle valvole. Le estremità opposte delle corde
sono inserite su estensioni di muscolo ventricolare simili a
montagnole, note come *muscoli papillari*.
#underline("Questi muscoli danno stabilità alle corde tendinee, ma non sono in grado di aprire e chiudere attivamente le valvole AV. Le valvole si aprono o chiudono passivamente quando vengono spinte dal sangue che scorre.")
===== Fonte
Silverthorn "Fisiologia umana. Un'approccio integrato" pag. 422-423 (libro del corso di fisiologia)
#align(center, image("/immagini/cuore_valvole.png", width: 60%))
#pagebreak()
== Funzione cardiaca
#let im0 = image("/immagini/immagine_cuore.png", width: 80%)
#let im1 = image("/immagini/grafico_pressioni_ciclo_cardiaco.png", width: 110%)
#grid(
columns: 2,
rows: 1,
grid.cell(im0),
grid.cell(im1),
)
Le valvole vengono azionate semplicemente dalle pressioni su cui agisce il cuore.
La valvola aortica si apre quando la *pressione ventricolare* supera la pressione aortica che arriva fino ad un valore massimo di riferimento pari a 120mmHg (*pressione sistolica*), la *pressione aortica* è quindi normalmente la *pressione diastolica*, ha valore di riferimento di 80mmHg. Questo accade perchè la valvola aortica è una valvola che si apre in una sola direzione, la sua forma a "uncino" fa in modo che il flusso quando scorre nel verso opposto faccia chiudere la valvola, come si vede in figura.
#align(center, image("/immagini/valvola_aortica00.png", width: 60%))
#pagebreak()
== Criticità
Le valvole non devono avere reflusso, cioè devono impedire lo scorrimento del sangue nel verso opposto, se questo non avviene, il ventricolo cercherà comunque di aumentare la pressione per vincere quella aortica ed aprire la valvola, si richiederà al cuore uno sforzo maggiore perchè dovrà aumentare la pressione mentre perde volume, si avrà quindi una perdita di eiezione, la ejection fraction sarà minore.
Fondamentale quindi è il mantenimento delle proprietà meccaniche della valvola, che deve presentare la giusta resistenza alle sollecitazioni che le vengono imposte dal cuore attraverso il sangue.
Le caratteristiche meccaniche possono variare a causa di risposte immunitarie che vanno a modificare la composizione del tessuto a causa dell'azione delle cellule immunitarie. Questo può essere causato da: *febbre reumatica*, *endocardite*. Di seguito un elenco delle cause delle patologie valvolari:
+ *Febbre reumatica*
+ Condizione infiammatoria che spesso inizia con un'infezione batterica streptococcica.
+ Il danno non è causato dai batteri stessi, ma da una risposta autoimmune.
+ *Endocardite*
+ Infezione dell'endocardio e delle valvole causata da batteri, virus, funghi o altri agenti infettivi.
+ *Degenerazione mixomatosa*
- Processo degenerativo del tessuto connettivo, con aumento dei glicosaminoglicani.
- Colpisce prevalentemente la valvola mitralica.
- Il tessuto della valvola perde l’elasticità e diventa meccanicamente debole.
+ *Degenerazione calcifica*
- Causa comune della malattia della valvola cardiaca negli anziani.
- E’ la causa più frequente di stenosi aortica.
+ *Anomalie congenite*
- Il difetto più comune è una valvola aortica deformata, con due foglietti invece di tre (valvola bicuspide).
== TAVI
È l'acronimo di Transcatheter-Aortic-Valve-Implantation, è una tecnica della cardiologia interventistica che permette l'impianto della valvola aortica (meccanica o biologica) con approccio percutaneo in alternativa alla sostituzione con intervento cardiochirurgico.
== Tipologie di valvole cardiache
=== Valvole Meccaniche
Sono costituite da una struttura principale su cui sono vincolati degli organi mobili che permettono la chiusura e la apertura. È costituita da materiali *metallici o polimerici* per quanto riguarda la struttura interna che fa da sostegno.
=== Componenti
==== Alloggiamento
- È solo metallico: Ti6Al4V o lega di a base di cobalto, rivestimento di carbonio pirolitico
==== Occlusore
-
- Esempio materiale metallico: Ti6Al4V
- Esempio materiale polimerico: <NAME>
#{
let img0 = image("/immagini/valvola_meccanica_moderna.png", width: 50%)
let img1 = image("/immagini/valvola_meccanica_moderna01.png", width: 100%)
let fig0 = figure(img0, caption: "bileaflet -- A emidischi")
let fig1 = figure(img1, caption: "altri tipi")
grid(
columns: 2,
grid.cell(fig0),
grid.cell(fig1)
)
}
=== Rivestimento di Carbonio Pirolitico
Permette di avere una superficie biocompatibile, si ha comunque la necessità di trattare il paziente con farmaci anti-coagulanti (vitamina K).
Si ottiene tramite il *CVD* (Chemical Vapor Deposition) oppure il *PVD* (Physical Vapor Deposition).
Questo materiale ha delle caratteristiche miste delle due forme del carbonio cristallino, *la grafite* e *il diamante*, come per i polimeri si può avere una composizione parziale di struttura cristallina e amorfa.
==== Metodo: Forno a letto fluido
Questo processo viene utilizzato per ottenere carbonio pirolitico, anche chiamato Carbonio Low Temperature Isotropic (LTI), a partire da un idrocarburo gassoso.
Il rivestimento viene eseguito all'interno di un forno, detto *forno di letto fluido*, in un atmosfera composta da 2 gas: l'*elio*, gas inerte che permette la *pirolisi* (combustione in assenza di agenti ossidanti), permette inoltre di regolare il risultato del rivestimento regolando la composizione dei 2 gas, e un idrocarburo gassoso da cui poter strappare gli atomi di carbonio.
#align(
center, image("/immagini/pyrolitic_carbon_manifacturing.png", width: 60%
)
)
Per strappare gli atomi di carbonio è necessaria una temperatura tra i 1000°C e i 2400°C. Per ovvie ragioni i polimerici non sono adatti a questo trattamento.
==== Metodo: Sputtering catodico
Trattamento a basse temperature e pressioni(vuoto) adatto sia a materiale *metallico* che *polimerico*. Utilizza il carbonio pirolitico per rivestire una superficie di interesse, es: valvola protesica.
Il processo consiste di 3 elementi:
- *Ambiente controllato*: camera a pressione inferiore a quella atmosferica, in cui l'unico gas presente è l'Argon (contiene l'anodo e il catodo).
- *Anodo*: pezzo da rivestire.
- *Catodo*: pezzo fatto di carbonio pirolitico, fa da sorgente di materiale.
===== Descrizione del processo di sputtering
La differenza di potenziale ionizza l'argon, i cationi di Argon impattano sul catodo(venendo attratti) l'impatto genera una cascata di collisioni, in seguito questo può causare una espulsione di un atomo del catodo. Questo è il processo di *sputtering*. L'atomo che viene emesso si appiccica sulla superficie dell'anodo(come? boh).
(da wikipedia) https://en.wikipedia.org/wiki/Sputtering
=== Valvole Biologiche
Le valvole cardiache biologiche hanno una struttura interna metallica che sostiene il materiale biologico con cui è realizzata la valvola.
Il tessuto con cui viene realizzata può essere *autologo* (del paziente stesso), di *orgine animale* (pericardio bovino, valvola porcina).
Nel caso di valvola di origine animale, il tessuto viene decellularizzato e trattato con gluteraldeide per evitare l'attivazione del sistema immunitario. La valvola biologica viene poi ripopolata dalle cellule dell'organismo ospitante.
=== Biologiche vs Meccaniche
==== Terapia anticoagulante
*Per le meccaniche* è necessaria una terapia anticoagulante, vitamina K antagonista, per tutta la vita del paziente dal momento in cui gli viene impiantata la valvola meccanica. Aumentato rischio di emorraggia per tutta la vita a venire.
*Per le biologiche* secondo le linee guida è necessario solamente per un breve periodo post-operazione (3-6 mesi), in assenza di controindicazioni.
#let coag_terapy_link = "https://www.escardio.org/Journals/E-Journal-of-Cardiology-Practice/Volume-20/prosthetic-heart-valves-part-2-antithrombotic-management"
===== Fonte
#link(coag_terapy_link)[European Society of Cardiology Website: "Prosthetic heart valves: Part 2 - Antithrombotic management"]
==== Rumore
*Le valvole meccaniche* producono un rumore (click) dovuto alla durezza/rigidità superficiale delle palette mobili durante la loro apertura e chiusura.
*Le biologiche* siccome sono composte da materiale biologico non producono rumori udibili dal paziente in condizioni di silenzio.
==== Durata
- Biologiche: 10-15 anni
- Meccaniche: 30+ anni
|
|
https://github.com/Daillusorisch/HYSeminarAssignment | https://raw.githubusercontent.com/Daillusorisch/HYSeminarAssignment/main/hyyt.typ | typst | #import "template/template.typ": thesis, tlt, indent, acknowledgement, appendix
// Magic code for fake bold
// reference: https://github.com/typst/typst/issues/394#issuecomment-1987055478
#show text.where(weight: "bold").or(strong): it => {
show regex("\p{script=Han}"): set text(stroke: 0.025em)
it
}
#let (
doc, cover, front-matter, abstract-zh, abstract-en, outline-page, main-matter
) = thesis(
title: [就“基于分布式光纤的非常规油气藏微震观测与分析”的报告],
author: "*******",
student-id: "*************",
major: "地球物理学",
school: "****",
supervisor: "---",
date: "二 〇 二 四 年 六 月",
)
#show: doc
#cover()
// #declaration(
// author_signature_path: "/assets/whu.png",
// mentor_signature_path: "/assets/whu.png"
// )
#show: front-matter
#show "typst": typst => underline(link("https://typst.app")[#typst]) // mk `typst` a link
#show "latex": latex => box(baseline:22.5%)[#image("assets/LaTeX_logo.svg", height: 13pt)] // mk `latex` svg
#abstract-zh(
keywords: ("弘毅研讨课", "作业")
)[
本文是-----------------。文中就线上学术报告“基于分布式光纤的非常规油气藏微震观测与分析”进行了总结和讨论。在本文写作的同时还对新型排版工具typst进行了测试(所以本文件也是由 typst 生成)。
]
// #pagebreak()
#v(100pt)
#abstract-en(
keywords: ("Hongyi Seminar", "Homework")
)[
This paper is a ---------------------------------. The paper summarizes and discusses the online academic report “Distributed Fiber Optic-based Microseismic Observation and Analysis of Unconventional Reservoirs”. The author test new layout tool typst while writing this paper (so this paper is also generated by typst).
]
#pagebreak()
#outline-page()
#pagebreak()
#show: main-matter
= 线上报告本体
报告以基于分布式光纤的非常规油气藏微震观测与分析为主题,报告者为来自南方科技大学的罗彬。这份报告可以在#underline(link("https://www.bilibili.com/video/BV1jG411M7Jt/")[这里])观看。
== DAS和背景介绍
报告首先介绍了分布式光纤传感(DAS)的基本原理和特性。光纤地震仪和传统的三分量地震仪不同,光纤地震仪只对沿光纤方向的应变敏感。所以P波和S波的入射方向和沿光纤方向之间的夹角的变化会导致DAS的响应也有所不同。由P波和S波以及光纤对于应变的响应关系,可以推导出:
$ "P_wave" ~ cos^2 theta $ $ "S_wave" ~ sin 2 theta $
此外,光纤地震仪不是严格的单点采样。由于其标距效应,其相当于对目标信号在空间上进行了一个滑动平均(和一个方波进行了卷积),所以DAS对于波长小于标距的信号具有明显的方向性相应,而对于远长于标距的信号的方向性响应则较弱。
本报告作者的研究是“非常规油气藏”。所谓的“非常规油气藏”即指页岩油和页岩气,其在开采过程中使用水力压裂技术。压裂技术是通过在井眼中注入高压液体,使岩石发生裂缝,从而增加岩石的渗透率。压裂过程中导致的岩层破裂会产生微震。这些微震信号可以被同井或是专用井中的光纤记录下来。井下光纤覆铠,耐磨损性能好所以可以在作业期间持续进行井下观测。作者主要的研究就以此为背景开展。
== DAS在水力压裂中的应用
DAS在水力压裂中的应用主要是检测压裂的破裂场。这方面有三种手段,一类是观测压裂前后的地震信号作对比,计算破裂,如@fig:base-line 所示。另一类是在压裂过程中持续观测应变场,如@fig:wwing 所示。第三类是观测微震信号并对其作分析。本报告中主要聚焦于第三个方法。
#figure(image("./assets/baseline.png"), caption: [水压裂前后观测人工源地震的对比显示出新的破裂@byerley2018time]) <base-line>
#figure(image("./assets/wwimg.png"), caption: [水压裂作业中的持续观测能发现岩层中应力的持续变化@jin2017hydraulic]) <wwing>
作者使用是数据来自德州的Eagle Ford岩层。此岩层的特点是上下两个高速层夹着中间的低速页岩层。这就会产生全反射和导波,如@fig:microseimdas 所示。
#figure(image("./assets/microseimdas.png"), caption: [光纤对于压裂微震的响应,注意到导波的产生]) <microseimdas>
由于只有震源在低速层内才会产生导波,所以可以通过导波的存在来判断震源的位置。这方面可以通过人工生成的加噪声图像训练CNN来识别。同时,注意到有些导波有奇阶和第一高阶的特质,而有些没有这些mode,这可以用来判断震源在低速层中的位置。
为了获得震源位置和光纤之间的距离,需要一个已知源。在压裂场景中可以使用钻头的信号来校准。井下噪声很少,不能通过互相关来做。
通过微震位置的集合,可以发现其分布具有一定规律。在本例中,其分布呈现一定的倾斜状,可能是由于压裂没有按照最小应力的方向进行。
在多数的较大震级(大于-1级)的事件中,都可以发现如@fig:near-field 所示的近场信号。从Aki and Richards的公式出发模拟,可以得到和观测相同的结果。由历史研究可知,从这些近场结果中,如果介质各向同性,那么我们不能得到更多的信息@vera2020strain。但是在实际工程中,我们有可能可以更好地约束震源参数,这需要进一步研究。
#figure(image("./assets/nf.png"), caption: [可以观测到近场的出现,P-S有大幅度的反相加强@luo2021near]) <near-field>
= 讨论
光纤在井下观测中具有明显的优势。得益于光纤(及其覆铠)的机械强度,DAS可以在地下持续观测。而且光纤相较传统地震仪在观测时更接近震源,测点更密集,这为未来的大规模密集观测成像,乃至于地下云图的实现提供了可能性。在页岩油气藏的开采中,光纤传感可以更灵敏地感知微震,从而对压裂作业的效果进行实时监测,进而指导作业。
但是光纤同样尤其弱点,那就是它是单分量的。这导致本报告中的例子只靠光纤不能准确定震源点(最佳情况也只能限制到左右对称的两个点上),需要多方面的额外信息来确定。
根据报道,在德州Eagle ford地区就有上万口已经打下去的井@wells2022。而已经安装了DAS的则是少数,多数的井都是过去打的,其中没有预埋光纤。如果能够利用那些已经存在的井,或许有可能能以更低的成本实现大规模的密集观测。
#pagebreak()
#bibliography(("./bib/bib.bib"), style: "gb-7714-2005-numeric")
// #acknowledgement()[
// ]
#appendix()[
typst本次测试中表现良好,在#underline(link("https://github.com/Enter-tainer/typst-preview")[typst-preview])项目的帮助下,可以实时预览修改的效果,不需要像latex一样等待编译。typst在语法上相较latex也更加简洁明快,缺点是可定制性暂时还不如latex,各种排版细节还需要进一步完善。但是对于一般项目已经达到了可用水平,且体感强于latex。
本文的源码可以在#underline(link("https://github.com/Daillusorisch/HYSeminarAssignment")[这个github仓库])上查看。
]
|
|
https://github.com/next-generation-cartographers/ngc-flyer | https://raw.githubusercontent.com/next-generation-cartographers/ngc-flyer/main/README.md | markdown | # NGC Flyer
This flyer is created using [typst](https://typst.app/docs/).
## Prequisites
To compile this document you need:
- _typst_. There are [multiple ways to install typst](https://github.com/typst/typst?tab=readme-ov-file#installation) on your machine.
- the font [_Source Sans Pro_](https://github.com/adobe-fonts/source-sans/releases/). The font needs to be installed (and activated) on your system.
To compile the document run:
```sh
typst compile main.typ
```
To watch the file for changes run:
```sh
typst watch main.typ
```
Refer to the [typst github repo](https://github.com/typst/typst?tab=readme-ov-file#usage) for more information on how to use typst (e.g. on custom font-paths if you don't want to install the font system-wide).
|
|
https://github.com/gvallinder/KTHThesis_Typst | https://raw.githubusercontent.com/gvallinder/KTHThesis_Typst/main/paperlist.typ | typst | MIT License | #pagebreak(to: "odd")
#heading(outlined: false, level: 1)[List of appended papers]
#heading(outlined: false, level: 2)[Paper A]
#lorem(26)
#heading(outlined: false, level: 2)[Paper B]
#lorem(35)
#heading(outlined: false, level: 2)[Paper C]
#lorem(36)
#heading(outlined: false, level: 2)[Paper D]
#lorem(25) |
https://github.com/platformer/typst-algorithms | https://raw.githubusercontent.com/platformer/typst-algorithms/main/test/assertions/assert_single_raw_text_in_code.typ | typst | MIT License | #import "../../algo.typ": code
#code[
```
blah blah blah
```
```
blah blah blah
```
]
|
https://github.com/GuTaoZi/SUSTech-thesis-typst | https://raw.githubusercontent.com/GuTaoZi/SUSTech-thesis-typst/main/template/content_zh.typ | typst | MIT License | #import "../utils/style.typ": *
#let content_zh(
) = {
set align(center)
text(font: FONTS.黑体, size: FSIZE.小二, "目录")
set text(font: FONTS.宋体, size: FSIZE.小四)
show outline.entry.where(
level: 1
): it => {
strong(it)
}
outline(title: none)
} |
https://github.com/mkpoli/ipsj-typst-template | https://raw.githubusercontent.com/mkpoli/ipsj-typst-template/master/src/main.typ | typst | #import "../lib.typ": techrep, acknowledgement, table, fake-bibliography
#import "@preview/roremu:0.1.0": roremu
#techrep(
title: [Typstによる情報処理研究報告の作成法],
title-en: "How to write IPSJ SIG Technical Report with Typst",
// title_en: [Template for IPSJ Technical Report using Typst],
affiliations: (
"IPSJ": [情報処理学会 \ IPSJ, Chiyoda, Tokyo 101–0062, Japan],
),
paffiliations: (
"JU": [現在,情報処理大学 \ Presently with Johoshori University]
),
authors: (
(
name: "情報 太郎",
name-en: "<NAME>",
affiliations: ("IPSJ",),
email: "<EMAIL>"
),
(
name: "処理 花子",
name-en: "<NAME>",
affiliations: ("IPSJ",),
email: none
),
(
name: "学会 次郎",
name-en: "<NAME>",
affiliations: ("IPSJ", "JU"),
email: "<EMAIL>"
)
),
abstract: [
#roremu(250)
],
keywords: ("情報処理学会", "研究報告", "Typst"),
abstract-en: [
#lorem(150)
],
keywords-en: ("IPSJ", "Technical Report", "Typst"),
[
= はじめに
#roremu(50)@Word
$E=m c^2$
#roremu(50, offset: 50)#footnote("脚注の例")
$ E=m c^2 $
#roremu(50, offset: 100)#footnote("脚注の例その2")
= 本論
#roremu(500)@LaTeX
= コードブロック
```
fn main() {
println!("Hello, world!");
}
```
= おわりに
#roremu(150)@XeLaTeX
],
bibliography: [
#bibliography("refs.yml", title: "参考文献")
#fake-bibliography(yaml("refs.yml"), show-unused: false)
]
) |
|
https://github.com/YKamataki/typst_templates | https://raw.githubusercontent.com/YKamataki/typst_templates/main/report.typ | typst | Creative Commons Zero v1.0 Universal | // The project function defines how your document looks.
// It takes your content and some metadata and formats it.
// Go ahead and customize it to your liking!
#let project(title: "", authors: (), date: none, subject: "", body) = {
// Set the document's basic properties.
set document(author: authors, title: title)
// Save heading and body font families in variables.
let body-font = "BIZ UDPMincho"
let sans-font = "BIZ UDPGothic"
// Set body font family.
set text(font: body-font, lang: "ja")
show heading: set text(font: sans-font)
// Set run-in subheadings, starting at level 3.
show heading: it => {
if it.level > 3 {
parbreak()
text(11pt, style: "italic", weight: "regular", it.body + ".")
} else {
it
}
}
// Date Row
align(right)[
#date
]
// Subject row
align(left)[
#subject
]
// Title row.
align(center)[
#block(underline(text(font: sans-font, weight: 700, 1.75em, title)))
#v(1em, weak: true)
]
// Author information.
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(right, author)),
),
)
// Main body.
set par(justify: true)
body
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/emphasis_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Adjusting the delta that strong applies on the weight.
Normal
#set strong(delta: 300)
*Bold*
#set strong(delta: 150)
*Medium* and *#[*Bold*]*
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/linear/components/components.typ | typst | The Unlicense | #import "./glossary.typ": *
#import "./pro-con.typ": *
#import "./toc.typ": *
#import "./decision-matrix.typ": *
|
https://github.com/chendaohan/rust_tutorials | https://raw.githubusercontent.com/chendaohan/rust_tutorials/main/books/5.基本类型之数值类型(value_type).typ | typst | #set heading(numbering: "1.")
#set text(size: 15pt)
Rust是静态强类型语言,Rust 的每个值都有确切的数据类型,总的来说可以分为两类:基本类型和复合类型。 基本类型意味着它们往往是一个最小化原子类型,无法解构为其它类型(一般意义上来说)。
= 整数(演示代码在`main()`中)
== 整数类型
`i`代表的是`integer`,`u`代表的是`unsigned integer`。写一个整数,它默认是`i32`类型的数,除非添加类型标识。isize 和 usize 类型取决于程序运行的计算机 CPU 类型: 若 CPU 是 32 位的,则这两个类型是 32 位的,同理,若 CPU 是 64 位,那么它们则是 64 位。
#block(
width: 60%,
table(
columns: (1fr, 1fr, 1fr),
align: horizon,
[长度], [有符号], [无符号],
[8 bit], [i8], [u8],
[16 bit], [i16], [u16],
[32 bit], [i32(默认)], [u32],
[64 bit], [i64], [u64],
[128 bit], [i128], [u128],
[arch], [isize], [usize]
)
)
== 整数字面量的表示
#block(
width: 50%,
table(
columns: (3fr, 2fr),
align: horizon,
[数字字面量], [示例],
[十进制], [98_222],
[十六进制], [0xff],
[八进制], [0o77],
[二进制], [0b1111_0000],
[字节 (仅限于 u8)], [b'A']
)
)
== 整数溢出
以`debug`模式编译时,会检查溢出,如果溢出则`panic!()`,以`release`模式编译时,不检查溢出。如果要显示处理可能的溢出,可以使用整数类型的方法:
- 使用 wrapping\_\* 方法在所有模式下都按照补码循环溢出规则处理,例如 wrapping_add
- 使用 checked\_\* 方法时发生溢出,则返回 None 值
- 使用 overflowing\_\* 方法返回该值和一个指示是否存在溢出的布尔值
- 使用 saturating\_\* 方法使值达到最小值或最大值
= 浮点数(演示在`float_type()`中)
== 浮点数类型
浮点类型数字 是带有小数点的数字,在 Rust 中浮点类型数字也有两种基本类型: f32 和 f64,分别为 32 位和 64 位大小。默认浮点类型是 f64,在现代的 CPU 中它的速度与 f32 几乎相同,但精度更高。
#block(
width: 40%,
table(
columns: (1fr, 1fr),
align: horizon,
[长度], [类型],
[32 bit], [f32],
[64 bit], [f64(默认)]
)
)
== 浮点数陷阱
- 浮点数往往是你想要数字的近似表达:浮点数类型是基于二进制实现的,但是我们想要计算的数字往往是基于十进制,例如 0.1 在二进制上并不存在精确的表达形式,但是在十进制上就存在。
- 浮点数在某些特性上是反直觉的:浮点数是可以比较的,比较运算实现的是 std::cmp::PartialEq 特征,但是并没有实现 std::cmp::Eq 特征。
== NaN
对于数学上未定义的结果,例如对负数取平方根 -42.1.sqrt() ,会产生一个特殊的结果:Rust 的浮点数类型使用 NaN (not a number)来处理这些情况。所有跟 NaN 交互的操作,都会返回一个 NaN,而且 NaN 不能用来比较。
= 数字运算(演示在`operations()`中)
Rust 支持所有数字类型的基本数学运算:加法、减法、乘法、除法和取模运算。
= 位运算(演示在`bitwise_operations()`中)
#block(
width: 80%,
table(
columns: (1fr, 5fr),
align: horizon,
[运算符], [位运算],
[&], [相同位置均为1时则为1,否则为0],
[|], [相同位置只要有1时则为1,否则为0],
[^], [相同位置不相同则为1,相同则为0],
[!], [把位中的0和1相互取反,即0置为1,1置为0],
[<<], [所有位向左移动指定位数,右位补0],
[>>], [所有位向右移动指定位数,带符号移动(正数补0,负数补1)]
)
)
= 总结
- Rust 拥有相当多的数值类型. 因此你需要熟悉这些类型所占用的字节数,这样就知道该类型允许的大小范围以及你选择的类型是否能表达负数
- 类型转换必须是显式的. Rust 永远也不会偷偷把你的 16bit 整数转换成 32bit 整数
- Rust 的数值上可以使用方法. 例如你可以用以下方法来将 13.14 取整:13.14_f32.round(),在这里我们使用了类型后缀,因为编译器需要知道 13.14 的具体类型 |
|
https://github.com/monashcoding/typst-polylux-theme | https://raw.githubusercontent.com/monashcoding/typst-polylux-theme/main/lib.typ | typst | #import "@preview/polylux:0.3.1": polylux-slide
#let mac-purple = rgb("#5757d3")
#let margin = 40pt
#let mac-theme(aspect-ratio: "16-9", body) = {
set page(paper: "presentation-" + aspect-ratio, margin: margin)
set text(font: "Poppins", size: 25pt)
set strong(delta: 200)
show heading: it => if it.level == 3 { text(weight: "semibold", it) } else { it }
show raw: set text(font: "Fira Code")
body
}
#let title-slide(title: [], subtitle: [], author: []) = {
polylux-slide[
#place(top + left, dx: -margin, dy: -margin, image("img/bg-1.png", width: 100%))
#place(bottom + right, dx: margin, dy: margin, image("img/bg-2.png", width: 100%))
#set align(center + horizon)
#image("img/mac-logo-text.png", width: 25%)
#v(-1em)
#text(2em, strong(title)) \
#text(.75em, weight: "light", tracking: 3pt, upper(subtitle))
#v(1em)
#text(.75em, author)
]
}
#let slide(title: [], body) = {
polylux-slide({
box(
inset: (y: 25pt),
underline(
stroke: 4pt + mac-purple,
offset: 20pt,
text(mac-purple, strong(title))
)
)
body
place(bottom + right, image("img/mac-logo.png", height: 50pt))
})
}
|
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Maths_Expertes_Exercices_26_03_2024.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Maths Expertes Exercices",
authors: (
"<NAME>",
),
date: "26 Mars, 2024",
)
#set heading(numbering: "1.1.")
== Exercice 43 p 128
=== 1.
On a $5^3 = 25 times 5$
$5 equiv 5 [31]$
et $25 equiv minus 6 [31]$
donc $5^3 equiv 5 times minus 6 [31]$
$5^3 equiv -30 [31]$
Or $-30 equiv 1 [31]$ car $-30 -1 = 31$
donc $5^3 equiv 1 [31]$
=== 2.
$5^15 = (5^3)^5$
donc $ 5^15 equiv 1^5 [31] equiv 1 [31]$
$=> 7 times 5^15 -6 equiv 7-6 [31] equiv 1[31]$
Par conséquent le reste de la division eucliedienne de $7 times 5^15 -6$ par $31$ est $1$
== Exerice 44 p 128
$100-9 = 31 times 7$
donc $100 equiv 9 [31]$
$=> 100^1000 equiv 9^1000 [31]$
Or #table(
columns: (auto, auto, auto, auto, auto),
inset: 10pt,
align: horizon,
table.header(
[k], [1], [2], [3], [4],
),
$9^k equiv ... [31]$,
$9$,
$3$,
$1$,
$9$,
)
On trouve que $9^k equiv ... [31]$ forme un cycle contenant 3 éléments.
De plus $1000 equiv 1 [3]$
donc $ 100^1000 equiv 9^1000 [31] equiv 9 [31]$
== Exercice 50
=== 1.
$10 equiv 1 [9]$
donc $10^k equiv 1 [9]$
$forall n in NN, n= sum^y_(k=0)(a_k times 10^k), y$ étant le nombre de chiffre de n
Donc $n equiv (sum^y_(k=0)(a_k times 10^k)) [9]$
$=> n equiv (sum^y_(k=0)a_k )[9]$
Par conséquent tout entier est divisible par 9 si et seulement si la somme de ses chiffres et aussi divisble par 9
=== 2.
Pour que $27 a 8$ soit divisible par 9 on doit avoir
$2+7+8+a equiv 0 [9]$
$2 equiv 2 [9]$ $7 equiv 7 [9]$ $8 equiv 8 [9]$
donc $2+7+8 equiv 17 [9] equiv 8 [9]$
par conséquent $a equiv -8 [9] equiv 1 [9]$
Ainsi $a = 1+9k$ avec $k in ZZ$
Or a est un chiffre en base 10 donc $0 lt.eq.slant a <10$
pour $k=0$ $a=1$ ce qui est dans l'intervalle
pour $k=1$ $a=10$ ce qui n'est pas dans l'intervalle
pour $k=-1$ $a=-8$ ce qui n'est pas dans l'intervalle
En conclusion $a=1$ et $27 a 8 = 2718$ qui est divisible par $9$
== Exercice 51 p 128
=== 1. #table(
columns: (auto, auto, auto, auto, auto),
inset: 10pt,
align: horizon,
table.header(
[k], [1], [2], [3], [4],
),
$10^k equiv ... [11]$,
$-1$,
$1$,
$-1$,
$1$,
)
On remarque que $10^k equiv ... [11]$ forme un cycle de 2 éléments et dépend donc de la parité de $k$
=== 2.
$67485 = 6 times 10^4 + 7 times 10^3 + 4 times 10^2 + 8 times 10^1 + 5 times 10^0$
$=> 67485 equiv 6 times 10^4 + 7 times 10^3 + 4 times 10^2 + 8 times 10^1 + 5 times 10^0 [11]$
$67485 equiv 6-7+4-8+5 [11] equiv 0 [11] $
On en conclut que $67485$ est divisible par 11 et est donc un multiple de 11.
=== 3.
Il faut vérifier que la somme des chiffres correspondant à une puissance paire de 10 soustrait de la somme des chiffres correspondant à une puissance impaire de 10 est divisible par 11.
|
|
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/common-software/inkscape.typ | typst |
= Inkscape
<software-inkscape>
Inkscape is software for creating and editing vector graphics:
https://inkscape.org/
Inkscape is a valuable tool that's useful in many parts of the shop.
A common use of Inkscape is to prepare art for import into the software that drives various tools around the shop. Protohaven members use Inkscape to create and edit designs for use with:
- Large Format Laser (LightBurn)
- CNC Embroidery (Artistic Designer)
- Vinyl Cutter (Sure Cuts A-Lot)
// - CNC Plasma Cutter (Mach3)
- CNC Router (Vcarve)
Inkscape can be used to prepare art for the Large Format Printer.
Inkscape is also a good general purpose tool for creating visuals: drawings, infographics, logos, title blocks, icons.
== Download
Inkscape is freely available to download and use for Linux, Windows, and MacOS:
https://inkscape.org/release/
== Help and Tutorials
=== Manual
The Inkscape project maintains a comprehensive manual:
https://inkscape-manuals.readthedocs.io/en/latest/index.html
The manual is updated regularly, and available for both online (HTML) and offline (PDF, ePub) reading.
=== Video
A short tutorial to get started with Inkscape:
- Inkscape Tutorial: Complete Starter Guide for New Users (with chapters) \
https://www.youtube.com/watch?v=fzk-suGcqrc
A comprehensive tutorial series for Inkscape is available from TJ Free:
https://www.youtube.com/playlist?list=PLqazFFzUAPc5lOQwDoZ4Dw2YSXtO7lWNv
Some videos from the series that are good places to start:
- Inkscape Lesson 1 - Interface and Basic Drawing \
https://www.youtube.com/watch?v=8f011wdiW7g
- Inkscape Lesson 10 - Trace Images with Bezier Tool \
https://www.youtube.com/watch?v=sagrkdmC_BI
- Inkscape Lesson 11 - Trace Bitmap Tool (Convert Raster to SVG) \
https://www.youtube.com/watch?v=E7HwLTQu2FI |
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/flywheel/decide.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Decide: Launcher Rebuild",
type: "decide",
date: datetime(year: 2023, month: 11, day: 28),
author: "<NAME>",
witness: "<NAME>",
)
We rated each choice by the following properties:
- Ease of building on a scale of 0 to 10. This not only factors in how simple the
design is, but also how familiar we are with it.
- Distance launched on a scale of 0 to 5.
- Consistency/Accuracy on a scale of 0 to 5.
#decision-matrix(properties: (
(name: "Ease of building"),
(name: "Distance Launched"),
(name: "Consistency/Accuracy"),
), ("Catapult", 8, 3, 3), ("Flywheel", 9, 5, 2), ("Puncher", 4, 2, 3))
#admonition(
type: "decision",
)[
We ended up choosing the flywheel due to its incredibly high ease of building.
This will help us get it built in time for our next tournament.
]
= CAD Design
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
[
We opted to use a 4" flex wheel as the wheel for our flywheel. We would have
liked to use a 3" one, but we did not have any available to us.
This meant that the speed of our flywheel was slightly higher than we would have
liked it to be, and reduced the torque.
Triballs are dropped onto the spinning wheel directly by the match loaders. The
intake does not work at all with this design.
],
image("./flywheel-wheel.svg", width: 70%),
image("./flywheel-gear-ratio.png"),
[
We ended up with a 30:6 ratio, using sprockets and chain instead of gears. We
would have liked to use gears, but they didn't clear the larger flex wheel we
were using. This leaves us with a final RPM of 3000.
],
)
#image("./technical-drawing-1.png")
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/accent_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test accent bounds.
$sqrt(tilde(T)) + hat(f)/hat(g)$
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/template.typ | typst | // 参考 https://github.com/Fr4nk1in-USTC/typst-notebook
//#import "typst-sympy-calculator.typ": *
#import "@preview/lemmify:0.1.6": *
#import "@preview/commute:0.2.0": node, arr, commutative-diagram
#let __print_commute = true
#let old-commutative-diagram = commutative-diagram
#let en-font = "New Computer Modern"
#let commutative-diagram(print: __print_commute, ..args) = {
if print {
old-commutative-diagram(..args)
}
else {
align(center)[
#text(style: "italic", font: "New Computer Modern")[
_Commutative diagram_
]
]
}
}
#let TODO = [#text("TODO", fill: red, font: en-font)]
#let _der(y, x, times, sign) = {
if times == [$1$] {
[$(#sign #y) / (#sign #x)$]
}
else {
[$(dif^#times #y) / (dif #x^#times)$]
}
}
#let der(y, x) = _der(y, x, $1$, $dif$)
#let derN(y, x, times) = _der(y, x, times, $dif$)
#let partialDer(y, x) = _der(y, x, $1$, $diff$)
#let partialDerN(y, x, times) = _der(y, x, times, $diff$)
#let elasticity(P, Q) = $((diff #Q)/(diff #P))/(#Q / #P)$
#let autoVec3(a, delim: "(" ) = $vec(#a _1, #a _2, #a _3, delim: delim)$
#let autoVecN(a, n, delim: "(" ) = $vec(#a _1, #a _2, dots.v, #a _#n, delim: delim)$
#let autoVecNF(f, n, delim: "(" ) = $vec(#(f(1)), #(f(2)), dots.v, #(f(n)), delim: delim)$
#let autoRVecNF(f, n ) = $(#(f(1)), #(f(2)), dots, #(f(n)))$
#let autoMat3(delim: "(", ..var) = {
let varList = var.pos()
let row(n) = varList.map(v => $#v _#n$)
let data = (row(1), row(2), row(3))
math.mat(delim: delim, ..data)
}
#let where = "where"
#let with = "with"
#let andC = $" 且 "$
#let orC = $" 或 "$
#let hb = $hat(bold(beta))$
#let sb = $bold(beta)^star$
#let bbeta = $bold(beta)$
#let balpha = $bold(alpha)$
#let bgamma = $bold(gamma)$
#let by = $bold(y)$
#let bx = $bold(x)$
#let bu = $bold(u)$
#let bv = $bold(v)$
#let inner(x, y) = $〈#x, #y〉$
#let HomoCoor = math.vec.with(delim: "[")
#let autoHomoCoor3 = autoVec3.with(delim: "[")
#let Det = math.mat.with(delim: "|")
#let notModels = sym.tack.r.double.not
#let Gal = math.op("Gal")
#let Hom = math.op("Hom")
#let Ext = math.op("Ext")
#let Ob = math.op("Ob")
#let cone = math.op("cone")
#let Proj = math.op("Proj")
#let Spec = math.op("Spec")
#let Spv = math.op("Spv")
#let Tor = math.op("Tor")
#let ht = math.op("height")
#let Ann = math.op("Ann")
#let Ass = math.op("Ass")
#let Sylow(p) = $"Sylow"-#p$
#let Isom = math.op("Isom")
#let diag = math.op("diag")
#let rank = math.op("rank")
#let GL = math.op("GL")
#let char = math.op("char")
#let Frac = math.op("Frac")
#let Inv(a) = $#a^(-1)$
#let conjugateLeft(g, a) = $#g^(-1) #a #g$
#let conjugateRight(g, a) = $#g #a #g^(-1)$
#let quotient(G, H) = $#G\\#H$
#let empty = ""
#let lift = math.arrow.t
#let quo = math.class("relation", $slash$)
#let ord = math.op("ord")
#let ei(x) = $e^(i #x)$
#let eiB(x) = $e^(#x i)$ // i Behind
#let sgn = math.op("sgn")
#let arctanh = math.op("arctanh")
#let Res(f, i) = $op("Res") (#f \; #i)$
#let lcm = math.op("lcm")
#let Der = math.op("Der")
#let Arg = math.op("Arg")
#let End = math.op("End")
#let ReT = math.op("Re")
#let ImT = math.op("Im")
#let ignoreOne(x) = {
if x == [1] {
[]
} else {
[#x]
}
}
#let argmax = math.op("argmax")
#let argmin = math.op("argmin")
#let incrementSign(x, i, k) = {
let i1 = int(i)
if i1 = 0 {
$#x_#k$
}
else {
$#x_#(i + k)$
}
}
#let linearCombination(name: $C$, start: 1, ..args) = {
let fun(list) = list.enumerate().map(
l => {
let (i, x) = l
$#name _(#(i + start)) #x $
})
.join(" + ")
// 不能这么写
// let fun_error(list) = list.enumerate().map(
// (i, x) => {
// $C_(#(i + 1)) #x $
// })
// .join(" + ")
fun(args.pos())
}
#let linearCombinationC = linearCombination.with(name: $C$)
#let linearCombinationA = linearCombination.with(name: $A$)
#let linearCombinationa = linearCombination.with(name: $a$)
#let linearCombinationb = linearCombination.with(name: $b$)
#let linearCombinationlambda = linearCombination.with(name: $lambda$)
#let linearCombinationmu = linearCombination.with(name: $mu$)
#let defaultSum = (
Var: $n$,
Lower: $0$,
Upper: $+infinity$
)
#let defaultProd = (
Var: $n$,
Lower: $1$,
Upper: $+infinity$
)
#let defaultDirectSum = (
Var: $n$,
Lower: $0$,
Upper: $+infinity$
)
#let directSum = math.plus.circle
#let sumf(var: defaultSum.Var, lower: defaultSum.Lower, upper: defaultSum.Upper) = $sum_(#var = #lower)^(#upper)$
#let prodf(var: defaultProd.Var, lower: defaultProd.Lower, upper: defaultProd.Upper) = $product_(#var = #lower)^(#upper)$
#let directSumf(var: defaultDirectSum.Var, lower: defaultDirectSum.Lower, upper: defaultDirectSum.Upper) = $directSum_(#var = #lower)^(#upper)$
#let emptyArrow(s, e) = arr(str(s), str(e), $$)
#let coker = math.op("coker")
#let coim = math.op("coim")
#let Ad1(x, G) = $"Ad"_#G (#x)$
#let Ad = math.op("Ad")
#let Aut = math.op("Aut")
#let algClosure(F) = $#F^"alg"$
#let inverseLimit = $limits(lim)_(arrow.l.long)$
#let directLimit = $limits(lim)_(arrow.long)$
#let AModule(A) = [$#A -$模]
#let closedBall(a, r) = $overline(B(#a, #r))$
#let GEquiv(G) = {
$#G -$
"等变"
}
#let Mod = math.op("Mod")
#let tensorProduct = math.times.circle
#let generatedBy(body) = $angle.l #body angle.r$
#let normalSub(H, G) = $#H lt.tri.eq #G$
#let norS = math.class("relation", math.lt.tri.eq)
#let semiProd = math.class("relation", math.times.r)
#let diam = math.op("diam")
//#let quot = math.class("relation", $\/$)
#let Stab = math.op("Stab")
#let Orb = math.op("Orb")
#let arrowCir = $limits(arrow)^(circle)$
#let existsST(var, condition) = $exists #var space s.t. space #condition$
#let forallSa(var, condition) = $forall #var space , space #condition$
#let funcDef(f, A, B, x, fx) = $#f: space #A &-> #B \ #x &|-> #fx$
#let seqLimit(n) = $lim_(#n -> +infinity)$
#let seqLimitn = $seqLimit(n)$
#let inj_str = "inj"
#let surj_str = "surj"
#let bij_str = "bij"
#let fourierTrans(f) = $hat(#f)$
#let def_str = "def"
#let nat_str = "nat"
// Theorem and definition environments.
#let base_env(type: "Theorem", numbered: true, fg: black, bg: white,
name, body) = locate(
location => {
let lvl = counter(heading).at(location)
let top = if lvl.len() > 0 { lvl.first() } else { 0 }
let i = counter(type + str(top)).at(location).first()
// show: block.with(spacing: 11.5pt)
// stack(
// dir: ttb,
// rect(fill: fg, radius: (top-right: 5pt), stroke: fg)[
// #strong(
// text(white)[
// #type
// #if numbered {
// counter(type).step()
// [ #top.#(i+1).]
// }
// #if name != none [ (#name) ]
// ]
// )
// ],
// rect(width: 100%,
// fill: bg,
// radius: ( right: 5pt ),
// stroke: (
// left: fg,
// right: bg + 0pt,
// top: bg + 0pt,
// bottom: bg + 0pt,
// )
// )[
// #emph(body)
// ]
// )
parbreak()
strong($#type
#if numbered {
counter(type + str(top)).step()
if top > 0{
[ #top.#(i+1).]
}
else{
[ #(i+1).]
}
}
$)
$#if name != [] [
(#name)
]$
set enum(numbering: "1)")
" "
body
// if name != none {
// label(name)
// }
parbreak()
}
)
#let noneNameChecker(name) = {
if name == [] {
none
}
else {
name
}
}
#let (
theorem: theo, lemma: lem, corollary: cor,
remark: rem, proposition: prop, example:ex , definition:def,
proof: pr, rules: thm-rules
) = default-theorems("thm-group", lang: "en")
#let (
theorem: theo1, lemma: lem1, corollary: cor1,
remark: rem1, proposition: prop1, example:ex1 , definition:def1,
proof: pr1, rules: thm-rules1
) = default-theorems("thm-group-linear", lang: "en", thm-numbering: thm-numbering-linear)
#let my-ans-style(
thm-type, name, number, body
) = block(spacing: 11.5pt, {
set enum(numbering: "Step 1.1.")
body
linebreak()
h(1fr)
box(scale(160%, origin: bottom + right, sym.square.stroked))
})
#let my-styling = (
thm-styling: my-ans-style,
thm-numbering: thm-numbering-linear
)
#let (answer, rules:ans-rules) = new-theorems("thm-ans", ("answer": "Answer"), ..my-styling)
#let _convert(f, name, body) = f(name: noneNameChecker(name))[
#body
#parbreak()
]
#let (alg, rules: alg-rules) = new-theorems("thm-group", ("alg": text[Algorithm]))
#let (alg1, rules: alg-rules1) = new-theorems("thm-group-linear", ("alg1": text[Algorithm]), thm-numbering: thm-numbering-linear)
#let theorem(name, body) = _convert(theo, name, body)
#let lemma(name, body) = _convert(lem, name, body)
#let corollary(name, body) = _convert(cor, name, body)
#let proposition(name, body) = _convert(prop, name, body)
#let definition(name, body) = _convert(def, name, body)
#let example(name, body) = _convert(ex, name, body)
#let remark(name, body) = _convert(rem, name, body)
#let proof(body) = [#pr[
#set text(size: 10pt)
#body
]
#linebreak()
]
#let algorithm(name, body) = _convert(alg, name, body)
#let theoremLinear(name, body) = _convert(theo1, name, body)
#let lemmaLinear(name, body) = _convert(lem1, name, body)
#let corollaryLinear(name, body) = _convert(cor1, name, body)
#let propositionLinear(name, body) = _convert(prop1, name, body)
#let exampleLinear(name, body) = _convert(ex1, name, body)
#let remarkLinear(name, body) = _convert(rem1, name, body)
#let definitionLinear(name, body) = _convert(def1, name, body)
#let proofLinear(body) = [#pr1[
#set text(size: 10pt)
#body
]
#linebreak()
]
#let algorithmLinear(name, body) = _convert(alg1, name, body)
//#let theorem = base_env.with(
// type: "Theorem",
// fg: blue,
// bg: rgb("#e8e8f8"),
//)
//
//#let proposition = base_env.with(
// type: "Proposition",
// fg: blue,
// bg: rgb("#e8e8f8"),
//)
//
//#let example = base_env.with(
// type: "Example",
// fg: orange,
// bg: rgb("#f8e8e8"),
//)
//#let definition = base_env.with(
// type: "Definition",
// fg: orange,
// bg: rgb("#f8e8e8"),
//)
//
//#let lemma = base_env.with(
// type: "Lemma",
// fg: purple,
// bg: rgb("#efe6ff"),
//)
//
//#let corollary = base_env.with(
// type: "Corollary",
// fg: green,
// bg: rgb("#e8f8e8"),
//)
//#let equationNumber = locate(
// location => {
// let lvl = counter(heading).at(location)
// let i = counter("equation_number").at(location).first()
// let top = if lvl.len() > 0 { lvl.first() } else { 0 }
// counter("equation_number").step()
// align(end)[(#top.#(i+1))]
// }
//)
// Proof environment
//#let proof(body) = block(spacing: 11.5pt, {
// set enum(numbering: "Step 1.1.")
// emph[Proof.]
// [ ] + body
// linebreak()
// h(1fr)
// box(scale(160%, origin: bottom + right, sym.square.stroked))
//})
//#let answer(body) = block(spacing: 11.5pt, {
// set enum(numbering: "Step 1.1.")
// body
// linebreak()
// h(1fr)
// box(scale(160%, origin: bottom + right, sym.square.stroked))
//})
#let note(title: "Note title", author: "Name", logo: none, date: none,
preface: none, code_with_line_number: true, withOutlined: true, withTitle: true, withHeadingNumbering: true,
withChapterNewPage: false,
body) = {
// Set the document's basic properties.
set document(author: (author, ), title: title)
show list: set align(top + left)
show list: set block(breakable: true)
show block: set align(top + left)
set block(breakable: true)
show enum: set block(breakable: true)
set page(
numbering: "1",
number-align: end,
// Running header.
header-ascent: 14pt,
header: locate(loc => {
let i = counter(page).at(loc).first()
if i == 1 { return }
set text(size: 8pt)
if calc.odd(i) { align(end, title) } else { align(start, title) }
}),
)
set text(font: "Noto Serif CJK SC", lang: "zh")
show: thm-rules
show: ans-rules
show: thm-rules1
show: alg-rules
show: alg-rules1
show emph: it => {
text(it, weight: "bold")
}
show math.equation: set text(font: ("Noto Serif CJK SC", "New Computer Modern Math"))
show math.equation: it => {
show block: set align(center)
it
}
show math.equation.where(block: true): set align(center)
set math.equation(numbering: "(1)")
set math.equation(numbering: num =>
"(" + (counter(heading).get() + (num,)).map(str).join(".") + ")") if withHeadingNumbering == true
let headingfunc = (it => it)
if withHeadingNumbering == false {
}
else {
headingfunc = (it => {
counter(math.equation).update(0)
it
})
}
show heading: headingfunc
// set ref(supplement: it => {
// let eq = math.equation
// let el = it
// if el.func() == heading {
// "章节"
// } else if el.func() == eq {
// "式"
// } else {
// ""
// }
//}
// )
// Set paragraph spacing.
set par(spacing: 1.2em)
let headingfunc1 = it => it
if withChapterNewPage == true{
headingfunc1 = it => {
pagebreak()
it
}
}
if withTitle{
// Title page.
// The page can contain a logo if you pass one with `logo: "logo.png"`.
v(0.6fr)
if logo != none {
align(right, image(logo, width: 26%))
}
v(9.6fr)
text(1.1em, date)
v(1.2em, weak: true)
text(2em, weight: 700, title)
// Author information.
pad(
top: 0.7em,
right: 20%,
align(start, author)
)
v(2.4fr)
pagebreak()
if withOutlined {
if preface != none {
[
= Preface
]
preface
pagebreak()
// Table of contents
[
= Contents
]
outline(title: none, depth: 3, indent: true)
} else {
outline(depth: 3, indent: true)
}
if withChapterNewPage == false{
pagebreak() // 补上目录的换页
}
}
}
show heading.where(level: 1) : headingfunc1
// Main body
set par(justify: true, first-line-indent: 22pt)
set heading(numbering: "1.")
set heading(numbering: none) if withHeadingNumbering == false
// Code
show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
show raw.where(block: true): block.with(
width: 100%,
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
// Code block with line numbers
show raw.where(block: true): it => {
if not code_with_line_number { return it }
set text(font: ("Serif Italic", "Noto Serif CJK SC"))
let lines = it.text.split("\n")
let length = lines.len()
let i = 0
let left_str = while i < length {
i = i + 1
str(i) + "\n"
}
grid(
columns: (auto, 1fr),
align(
right,
block(
inset: (
top: 10pt,
bottom: 10pt,
left: 0pt,
right: 5pt
),
left_str
)
),
align(left, it),
)
}
body
}
#let prop = sym.prop |
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/multicore/pset6a.typ | typst | #import "template.typ": *
#show: template.with(
title: "6.5081 PSET 6A",
subtitle: "<NAME>",
pset: true
)
= Problem 1
== (a)
*Yes, a memory barrier would be required in this case*
Ideally, we would introduce a memory barrier in every single place we could have an ordering of operations or reads that could lead to a critical failure. This happens on lines `15` and `10`.
One possible source for error that we cover is the potential for dequeueing an incorrect element if the expected enqueue is out of order, and the update of the array happens following that of the tail. In this case, without a memory barrier we would run into significant problems.
Another case that we protect against is the potential to read old values of head from memory if we have not updated it in the correct order. This could lead to a double dequeue operation, which would again cause significant issues later down the line.
We would like to ensure that the ordering of the updates for the array and then the head and tail are stable.
== (b)
*Yes, a volatile declaration would help*
This is because having an element as volatile would ensure that the value of the element is always read from memory, and not from a cache. This would ensure that the value of the element is always up to date and that we are not reading stale values. This would be particularly useful in the case of the head and tail variables, as we would like to ensure that the values are always up to date and that we are not reading stale values. Thus this could solve the potential issues we faced in *(a)*
= Problem 2
Below is my implementation of the first part of the problem:
```java
import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.*;
public class Boxes {
public interface Handler {
void onEmpty();
}
volatile int boxIdx = -1;
ReentrantLock lock = new ReentrantLock();
Condition cond = lock.newCondition();
AtomicInteger[] counts;
Handler[] handlers;
public Boxes(int m) {
counts = new AtomicInteger[m];
handlers = new Handler[m];
for (int i = 0; i < m; i++) {
counts[i] = new AtomicInteger(0);
}
}
public void enter(int i) {
lock.lock();
while (boxIdx != -1 && boxIdx != i) {
cond.await();
}
counts[i].incrementAndGet();
boxIdx = i;
lock.unlock();
}
public boolean exit() {
lock.lock();
int i = boxIdx;
if (i == -1) {
return false;
}
int cnt = cnt[i].decrementAndGet();
if (cnt == 0) {
if (handlers[i] != null) {
handlers[i].onEmpty();
} else {
boxIdx = -1;
cond.signalAll();
}
}
return true;
lock.unlock();
}
public void setExitHandler(int i, Handler h) {
handlers[i] = h;
}
}
```
Below is the fixed version of the code as well as the explanation:
```java
import java.util.concurrent.atomic.AtomicInteger;
public class Stack<T> {
private AtomicInteger top;
private T[] items;
private final Boxes boxes; // new code
public Stack(int capacity) {
boxes = new Boxes(2); // new code
top = new AtomicInteger();
items = (T[]) new Object[capacity];
}
public void push(T x) throws FullException {
boxes.enter(0); // enter the first box
try {
int i = top.getAndIncrement();
if (i >= items.length) { // stack is full
top.getAndDecrement(); // restore state
throw new FullException();
}
items[i] = x;
} finally {
boxes.exit(); // enter the second box
}
}
public T pop() throws EmptyException {
boxes.enter(1); // enter the second box
try {
int i = top.getAndDecrement() - 1;
if (i < 0) { // stack is empty
top.getAndIncrement(); // restore state
throw new EmptyException();
}
return items[i];
} finally {
boxes.exit(); // exit box
}
}
}
```
The previous implementation did not work, because parallel operations were not handled correctly. There could be multiple pushes and pops going on at the same time, which would cause major issues for the proper execution. Instead what we do is have two boxes, one for the pop and one for the push, that each function enters before executing the operation. This ensures that the operations are done in a serial manner apart from each other, and it is not the case the two functions are mixing in with each other.This prevents the case where increments and decrements on lines `18` and `32` cause some weird interleaving of actions that would cause the stack to be in an invalid state. It is okay to have multiple pushes or pops happening at the same time, but it is not okay to have a push and a pop happening at the same time. This is why we have the two boxes, to ensure that the operations are done in a serial manner.
= Problem 3
For the recurrences, we can use the master theorem to find the functional form. The parallelism is calculated as the result of the work divided by the critical path length.
== Work
$
W(n) &= 2 dot W(n \/ 2) + O(n)\
W(n) &= O(n dot log n)
$
== Critical Path Length
$
C(n) &= C(n \/ 2) + O(n)\
C(n) &= O(n)
$
== Parallelism
$
P(n) &= W(n) \/ C(n) = (2 dot P(n \/ 2) + O(n)) / (P(n \/ 2) + O(n))\
P(n) &= O(log n)
$
= Code
#note(
title: "Analysis"
)[
Because of the shifted due dates of the lab, I instead implemented the full parallel system instead of having a clear draft phase and then a refinement period. The code shown below is an accurate reflection of that. The serial version is still listed here as requested by 6A. I analyze and cover both extensively in 6B, so I will leave out the analysis here which I do not believe we need anyway.
]
== *`Firewall.java`*
```java
// imports
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.ReentrantLock;
/*
* requirements:
* -------------
* - only 256 packets are being processed at any one time
* - generate a histogram of all fingerprints
* - process 2^(numaddresseslog) packets to reach stable state
*/
import java.util.*;
class RangeSum {
TreeMap<Integer, Integer> ranges;
RangeSum() {
ranges = new TreeMap<>();
}
void add(int a, int b) {
if (a >= b) {
return;
}
Map.Entry<Integer, Integer> lb = ranges.lowerEntry(b);
if (lb != null && lb.getValue() >= a) {
while (lb != null && lb.getKey() <= b) {
a = Math.min(a, lb.getKey());
b = Math.max(b, lb.getValue());
ranges.remove(lb.getKey());
lb = ranges.lowerEntry(b);
}
}
ranges.put(a, b);
}
void remove(int a, int b) {
if (a >= b) {
return;
}
Map.Entry<Integer, Integer> floor = ranges.floorEntry(a);
ArrayList<int[]> update = new ArrayList<>();
while (floor != null && floor.getValue() >= a) {
if (floor.getKey() < a) {
update.add(new int[]{floor.getKey(), a});
}
if (floor.getValue() > b) {
update.add(new int[]{b, floor.getValue()});
}
ranges.remove(floor.getKey());
floor = ranges.floorEntry(b);
}
for (int[] interval: update) {
ranges.put(interval[0], interval[1]);
}
}
boolean verify(int x) {
Map.Entry<Integer, Integer> floor = ranges.floorEntry(x);
return floor != null && floor.getValue() > x;
}
}
class SerialFirewall {
// D and PNG arrays as described in the PSET handout
static HashMap<Integer, RangeSum> D = new HashMap<>();
static boolean[] PNG = new boolean[1 << 17]; // set to the max size
static HashMap<Long, Integer> hist = new HashMap<>();
public static void main(String[] args) {
// parse args
if (args.length != 11) {
System.out.println("Invalid number of arguments " + args.length + " != 11");
return;
}
int numAddressesLog = Integer.parseInt(args[0]);
int numTrainsLog = Integer.parseInt(args[1]);
double meanTrainSize = Double.parseDouble(args[2]);
double meanTrainsPerComm = Double.parseDouble(args[3]);
int meanWindow = Integer.parseInt(args[4]);
int meanCommsPerAddress = Integer.parseInt(args[5]);
int meanWork = Integer.parseInt(args[6]);
double configFraction = Double.parseDouble(args[7]);
double pngFraction = Double.parseDouble(args[8]);
double acceptingFraction = Double.parseDouble(args[9]);
int iterations = Integer.parseInt(args[10]);
PacketGenerator generator = new PacketGenerator(
numAddressesLog,
numTrainsLog,
meanTrainSize,
meanTrainsPerComm,
meanWindow,
meanCommsPerAddress,
meanWork,
configFraction,
pngFraction,
acceptingFraction
);
for (int i = 0; i < PNG.length; i++) {
PNG[i] = false;
}
for (int i = 0; i < (1 << numAddressesLog); i++) {
D.put(i, new RangeSum());
D.get(i).add(0, (1 << numAddressesLog));
}
double startTime = System.currentTimeMillis();
for (int i = 0; i < iterations + 500000; i++) {
if (i == 500000) {
startTime = System.currentTimeMillis();
}
Packet packet = generator.getPacket();
if (packet.type == Packet.MessageType.ConfigPacket) {
int addr = packet.config.address;
boolean png = packet.config.personaNonGrata;
int addrBegin = packet.config.addressBegin;
int addrEnd = packet.config.addressEnd;
boolean accept = packet.config.acceptingRange;
// edit PNG
PNG[addr] = png;
// edit D
if (!D.containsKey(addr)) {
D.put(addr, new RangeSum());
}
if (accept) {
D.get(addr).add(addrBegin, addrEnd);
} else {
D.get(addr).remove(addrBegin, addrEnd);
}
} else {
int source = packet.header.source;
int dest = packet.header.dest;
if (!PNG[source] && D.containsKey(dest) && D.get(dest).verify(source)) {
long fingerprint = Fingerprint.getFingerprint(packet.body.iterations, packet.body.seed);
hist.put(fingerprint, hist.getOrDefault(fingerprint, 0) + 1);
}
}
}
double endTime = System.currentTimeMillis();
double elapsed = (endTime - startTime) / 1000.0;
System.out.println("packet/s count: " + iterations / elapsed);
}
}
class ParallelFirewall {
// D and PNG arrays as described in the PSET handout
static HashMap<Integer, RangeSum> D = new HashMap<>();
static boolean[] PNG = new boolean[1 << 17]; // set to the max size
static HashMap<Long, Integer> hist = new HashMap<>();
static WaitFreeQueue[] workload;
static PacketGenerator generator;
static MCSLock[] locks;
static volatile AtomicInteger flight = new AtomicInteger(0);
static MCSLock histLock;
public static void main(String[] args) {
// parse args
if (args.length != 12) {
System.out.println("Invalid number of arguments " + args.length + " != 12");
return;
}
int numAddressesLog = Integer.parseInt(args[0]);
int numTrainsLog = Integer.parseInt(args[1]);
double meanTrainSize = Double.parseDouble(args[2]);
double meanTrainsPerComm = Double.parseDouble(args[3]);
int meanWindow = Integer.parseInt(args[4]);
int meanCommsPerAddress = Integer.parseInt(args[5]);
int meanWork = Integer.parseInt(args[6]);
double configFraction = Double.parseDouble(args[7]);
double pngFraction = Double.parseDouble(args[8]);
double acceptingFraction = Double.parseDouble(args[9]);
int time = Integer.parseInt(args[10]);
int threads = Integer.parseInt(args[11]);
generator = new PacketGenerator(
numAddressesLog,
numTrainsLog,
meanTrainSize,
meanTrainsPerComm,
meanWindow,
meanCommsPerAddress,
meanWork,
configFraction,
pngFraction,
acceptingFraction
);
for (int i = 0; i < PNG.length; i++) {
PNG[i] = false;
}
for (int i = 0; i < (1 << numAddressesLog); i++) {
D.put(i, new RangeSum());
D.get(i).add(0, (1 << numAddressesLog));
}
// allow the system to reach steady state
int steady_iterations = (int) Math.pow((1 << (numAddressesLog)), 3.0 / 2.0);
System.out.println("Steady iterations: " + steady_iterations);
for (int i = 0; i < steady_iterations; i++) {
Packet packet = generator.getPacket();
if (packet.type == Packet.MessageType.ConfigPacket) {
int addr = packet.config.address;
boolean png = packet.config.personaNonGrata;
int addrBegin = packet.config.addressBegin;
int addrEnd = packet.config.addressEnd;
boolean accept = packet.config.acceptingRange;
// edit PNG
PNG[addr] = png;
// edit D
if (!D.containsKey(addr)) {
D.put(addr, new RangeSum());
}
if (accept) {
D.get(addr).add(addrBegin, addrEnd);
} else {
D.get(addr).remove(addrBegin, addrEnd);
}
}
}
System.out.println("Steady state reached");
histLock = new MCSLock();
locks = new MCSLock[1 << numAddressesLog];
for (int i = 0; i < (1 << numAddressesLog); i++) {
locks[i] = new MCSLock();
}
workload = new WaitFreeQueue[threads];
for (int i = 0; i < threads; i++) {
workload[i] = new WaitFreeQueue(256);
}
Worker[] workers = new Worker[threads];
for (int i = 0; i < threads; i++) {
workers[i] = new Worker(i, workload[i]);
}
Distributor distributor = new Distributor();
Thread distributor_thread = new Thread(distributor);
distributor_thread.start();
Thread[] worker_threads = new Thread[threads];
for (int i = 0; i < threads; i++) {
worker_threads[i] = new Thread(workers[i]);
worker_threads[i].start();
}
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
//
distributor.running = false;
try {
distributor_thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < threads; i++) {
workers[i].running = false;
try {
worker_threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// System.out.println("Total packets processed: " + distributor.total_packets);
System.out.println("packet/s count: " + (double)distributor.total_packets / (time / 1000.0));
}
// implemented from chapter 3
static class WaitFreeQueue {
volatile int head = 0, tail = 0;
Packet[] items;
public WaitFreeQueue(int capacity) {
items = new Packet[capacity];
head = 0; tail = 0;
}
public void enq(Packet x) throws Exception {
if (tail - head == items.length) {
throw new Exception();
}
items[tail % items.length] = x;
tail++;
}
public Packet deq() throws Exception {
if (tail - head == 0) {
throw new Exception();
}
Packet x = items[head % items.length];
head++;
return x;
}
}
// make a distributor worker who takes in the generator and communicates with the labor workers, they will run as threads
static class Distributor implements Runnable {
volatile boolean running = true;
int total_packets = 0;
Distributor() {}
public void run() {
while (running) {
if (flight.get() >= 256) {
continue;
}
Packet packet = generator.getPacket();
flight.incrementAndGet();
if (packet.type == Packet.MessageType.ConfigPacket) {
while(running) {
try {
workload[packet.config.address % workload.length].enq(packet);
total_packets++;
break;
} catch (Exception e) {
continue;
}
}
} else {
while (running) {
try {
workload[packet.header.source % workload.length].enq(packet);
total_packets++;
break;
} catch (Exception e) {
continue;
}
}
}
}
}
}
static class Worker implements Runnable {
volatile boolean running = true;
int threadId;
WaitFreeQueue workload;
Worker(int threadId, WaitFreeQueue workload) {
this.threadId = threadId;
this.workload = workload;
}
public void run() {
while (running) {
try {
Packet packet = workload.deq();
if (packet.type == Packet.MessageType.ConfigPacket) {
int addr = packet.config.address;
boolean png = packet.config.personaNonGrata;
int addrBegin = packet.config.addressBegin;
int addrEnd = packet.config.addressEnd;
boolean accept = packet.config.acceptingRange;
locks[addr].lock();
// edit PNG
PNG[addr] = png;
// edit D
if (!D.containsKey(addr)) {
D.put(addr, new RangeSum());
}
if (accept) {
D.get(addr).add(addrBegin, addrEnd);
} else {
D.get(addr).remove(addrBegin, addrEnd);
}
locks[addr].unlock();
} else {
int source = packet.header.source;
int dest = packet.header.dest;
locks[source].lock();
boolean png = !PNG[source];
locks[source].unlock();
locks[dest].lock();
boolean d = D.containsKey(dest) && D.get(dest).verify(source);
locks[dest].unlock();
if (png && d) {
long fingerprint = Fingerprint.getFingerprint(packet.body.iterations, packet.body.seed);
histLock.lock();
hist.put(fingerprint, hist.getOrDefault(fingerprint, 0) + 1);
histLock.unlock();
}
}
flight.decrementAndGet();
} catch (Exception e) {
}
}
}
}
static class MCSLock {
private static class MCSNode {
volatile MCSNode next;
volatile boolean locked = false;
}
private final ThreadLocal<MCSNode> node;
private final AtomicReference<MCSNode> tail;
public MCSLock() {
tail = new AtomicReference<>(null);
node = ThreadLocal.withInitial(MCSNode::new);
}
public void lock() {
MCSNode currentNode = node.get();
MCSNode predecessor = tail.getAndSet(currentNode);
if (predecessor != null) {
currentNode.locked = true;
predecessor.next = currentNode;
// spin until predecessor gives up the lock
while (currentNode.locked) {
}
}
}
public void unlock() {
MCSNode currentNode = node.get();
if (currentNode.next == null) {
if (tail.compareAndSet(currentNode, null)) {
return;
}
// wait until successor appears
while (currentNode.next == null) {
}
}
currentNode.next.locked = false;
currentNode.next = null;
}
}
}
```
|
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/assets/example2/compared_new.typ | typst | #show underline : it => {highlight(fill: gray, text(red, it))}
#show strike : it => {highlight(fill: yellow, text(blue, it))}
= Introduction
Authors using Microsoft Word will first need to save the AIAA Meeting
PapersTemplate.dotx file in the “Templates” directory of their hard
drive. To do so, simply open the AIAA Meeting Papers Template.dotx file
and then click#strike[ ];#strike[“File\>Save];#strike[
];#strike[As:”];#strike[ ];#strike[to];#strike[ ];#strike[save];#strike[
];#strike[the];#strike[ ];#strike[template.]
= #strike[Procedure];#strike[ ];#strike[for];#underline[Some] #strike[Paper];#underline[other] #strike[Submission];#underline[headline]
All manuscripts are to be submitted electronically to the ScholarOne
Abstracts site created for each conference. The manuscript upload will
be enabled several weeks after acceptance notices have been sent.
Presenting authors of accepted papers will receive an email with
instructions when manuscript submission opens. It is
#strike[important];#underline[#strong[important];] that presenting
authors keep their email addresses up-to-date so they do not miss this
notice.
= General Guidelines
The following section outlines general (nonformatting) guidelines to
follow. These guidelines are applicable to all authors (except as
noted), and include information on the policies and practices relevant
to the publication of your #strike[manuscript.];#underline[CHANGED.]
== Publication by AIAA
Your manuscript cannot be published by AIAA if:
+ It has been published previously or
+ #strike[The];#strike[ ];#strike[work];#strike[
];#strike[contains];#underline[Changed]
#strike[copyright-infringing];#underline[for]
#strike[material];#underline[something] #strike[or];#underline[new]
+ #strike[An];#strike[ ];#strike[appropriate];#strike[
];#strike[copyright];#strike[ ];#strike[statement];#strike[
];#strike[has];#strike[ ];#strike[not];#strike[ ];#strike[yet];#strike[
];#strike[been];#strike[ ];#strike[selected.]
== Paper Review and Visa Considerations
It is the responsibility of the author to obtain any required government
or company reviews for their papers in advance of publication. Start
early to determine if the reviews are required; this process can take
several weeks.
If you plan to attend an AIAA Forum, technical conference or
professional development course held in the United States and you
require a visa for travel, it is incumbent upon you to apply for a visa
with the U.S. embassy (consular division) or consulate with ample time
for processing.#strike[ ];#strike[To];#strike[ ];#strike[avoid];#strike[
];#strike[bureaucratic];#strike[ ];#strike[problems,];#strike[
];#strike[AIAA];#strike[ ];#strike[strongly];#strike[
];#strike[suggests];#strike[ ];#strike[that];#strike[
];#strike[you];#strike[ ];#strike[submit];#strike[
];#strike[your];#strike[ ];#strike[formal];#strike[
];#strike[application];#strike[ ];#strike[to];#strike[
];#strike[U.S.];#strike[ ];#strike[authorities];#strike[
];#strike[a];#strike[ ];#strike[minimum];#strike[ ];#strike[of];#strike[
];#strike[120];#strike[ ];#strike[days];#strike[ ];#strike[in];#strike[
];#strike[advance];#strike[ ];#strike[of];#strike[ ];#strike[the];#strike[
];#strike[date];#strike[ ];#strike[of];#strike[
];#strike[anticipated];#strike[ ];#strike[travel.]
== Control ID Number vs Paper
Your paper was assigned a control ID number at the time you submitted
your abstract. It is critical that you reference the tracking number and
conference name when contacting AIAA regarding your submission. The
control ID number is not the final AIAA paper number. The paper number,
which appears in the format AIAA-20XX-XXXX, will be used to refer to
your paper in the program and in any publication format. It will not be
assigned until shortly before the conference. #strong[Do not include a
paper number anywhere on your paper, as this number will be stamped
automatically in the top right corner of your paper at the time of
processing.]
== #underline[Header]
#underline[New];#underline[ ];#underline[paragraph]
- #underline[something]
- #underline[new]
== Copyright
Before AIAA can print or publish any paper, the copyright information
must be completed in the submission system. Failure to complete the
electronic form correctly could result in your paper not being
published. The following fields must be completed:
+ Clearance Statement
+ Non-Infringement Statement
+ Publication Status Statement
|
|
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/class-handouts/glossary/glossary_terms.typ | typst |
#import "glossary_functions.typ": *
#let abrasive_term = glossary_entry(
term: [abrasive],
category: [general], // Be explicit about this one
meaning: [A substance used for grinding, polishing, or cleaning a hard surface.],
image: ""
)
#let adhesion_term = glossary_entry(
term: [adhesion],
category: [general], // Be explicit about this one
meaning: [The action or process of sticking a material to a surface or object.],
image: ""
)
#let blank_term = glossary_entry(
term: [blank],
category: [wood],
meaning: [A piece of wood rounded smooth or cut into a section for lathe use.],
image: ""
)
#let booth_term = glossary_entry(
term: [booth],
meaning: [An enclosed, ventilated space for spraying coatings.],
image: ""
)
#let bow_term = glossary_entry(
term: [bow],
category: [wood],
meaning: [A warp along the length of the face of the wood.],
image: "images/bow.png"
)
#let burl_term = glossary_entry(
term: [burl],
category: [wood],
meaning: [A burl is an unusual growth on a tree, producing swirls and other interesting grain patterns.],
image: ""
)
#let check_term = glossary_entry(
term: [check],
category: [wood],
meaning: [A crack in the interior of the wood running with the grain.],
image: "images/check_and_split.png"
)
#let crook_term = glossary_entry(
term: [crook],
category: [wood],
meaning: [A warp along the length of the edge of the wood.],
image: "images/crook.png"
)
#let cup_term = glossary_entry(
term: [cup],
category: [wood],
meaning: [A warp across the width of the face, in which the edges are higher or lower than the center of the wood.],
image: "images/cup.png"
)
#let curing_term_term = glossary_entry(
term: [curing],
meaning: [A chemical process where a substance transforms into a hard, continuous coating.],
image: ""
)
#let fence_term = glossary_entry(
term: [fence],
meaning: [Vertical surface that supports the workpiece as it passes through the tool.],
image: ""
)
#let flat_term = glossary_entry(
term: [flat],
meaning: [When a surface has no high spots, low spots, or twist.],
image: ""
)
#let gullet_term = glossary_entry(
term: [gullet],
meaning: [Space in the saw blade between teeth.],
image: ""
)
#let heartwood_term = glossary_entry(
term: [heartwood],
meaning: [Heartwood is the fully developed wood surrounding the core, usually darker than sapwood and very dense.],
image: ""
)
#let kerf_term = glossary_entry(
term: [kerf],
meaning: [Width of the cut.],
image: ""
)
#let masking_term_term = glossary_entry(
term: [masking],
meaning: [Covering a surface to protect it from paint, abrasives, or some other process that affects the workpiece.],
image: ""
)
#let push_block_term = glossary_entry(
term: [push block],
meaning: [A piece of wood or plastic notched to apply a mechanical pushing action on the workpiece.],
image: ""
)
#let push_pad_term = glossary_entry(
term: [push pad],
meaning: [Paddles with handles, with high friction surfaces to push the workpiece along a table or fence.],
image: ""
)
#let sapwood_term = glossary_entry(
term: [sapwood],
meaning: [Sapwood surrounds heartwood and is usually softer. It transports sap from roots to leaves. Sapwood has a different color than heartwood.],
image: ""
)
#let set_term = glossary_entry(
term: [set],
meaning: [Bend in the teeth to make kerf wider than the spine of the blade.],
image: ""
)
#let stick_welding_term = glossary_entry(
term: [Shielded Metal Arc Welding (Stick Welding)],
meaning: [Uses a metal electrode covered in flux to create weld.
As the current goes from electrode to metal, it melts the metals and electrode, creating a weld pool.
The flux coating turns into a gas that shields the weld and creates slag covering the weld.
Stick welding can be messy and the slag is hammered off of the weld after cooling.
Generally used for large structural metal construction where precision and cleanliness aren’t primary concerns.],
image: ""
)
#let snipe_term = glossary_entry(
term: [snipe],
meaning: [A circular cut made by a rotary cutting head lingering against a surface.],
image: ""
)
#let spalted_term = glossary_entry(
term: [spalted],
meaning: [
Spalted wood in the process of fungal decay that shows as black lines in the grain. Woodturners prize spalted wood because the black lines add an artistic element to the turning.],
image: ""
)
#let square_term = glossary_entry(
term: [square],
meaning: [Two faces of a board meeting at 90°.],
image: ""
)
#let swarf_term = glossary_entry(
term: [swarf],
meaning: [Chips and dust carried away from the workpiece by the saw blade during the cut.],
image: ""
)
#let table_term = glossary_entry(
term: [table],
meaning: [Horizontal surface that supports the workpiece as it passes through the tool.],
image: ""
)
#let tearout_term = glossary_entry(
term: [tearout],
meaning: [When a cutting head lifts fibers out of the workpiece instead of shearing them off.],
image: ""
)
#let twist_term = glossary_entry(
term: [twist],
meaning: [A distortion in which the two ends do not lie on the same plane Synonym: _wind_. Winding sticks assist in viewing this defect.],
image: "images/twist.png"
)
#let wind_term = glossary_entry(
term: [wind],
meaning: [A distortion in which the two ends do not lie on the same plane. Synonym: _twist_. Winding sticks assist in viewing this defect.],
image: "images/twist.png"
)
|
|
https://github.com/cnaak/untypsignia.typ | https://raw.githubusercontent.com/cnaak/untypsignia.typ/main/README.md | markdown | MIT License | # untypsignia.typ: unofficial typesetter's insignia emulations
The `untypsignia` is a 3rd-party, unofficial, unendorsed Typst package that exposes commands for
rendering, as `content` texts, some typesetters names in a stylized fashion, emulating their
respective _insignia_, i.e., marks by which they are known.
## Name
The package name is a blend of:
- "un", from "unofficial",
- "typ", from "Typst", and
- "signia", from "insignia", which means marks by which anything is known.
## Description
The typical use case of `untypsignia` in Typst is to emulate a given typesetting system's mark,
if available, when referring to them, in sentences like: "This document is typeset in `XYZ`", as
traditionally done in `TeX` systems and derivatives thereof.
Currently available insignia emulations include:
- `TeX`,
- `LaTeX`, and
- `Typst` (see below)
Despite there's no such a thing as a Typst "official" typography, according to this post on
[Discord](https://discord.com/channels/1054443721975922748/1054443722592497796/1107039477714665522),
it can be typeset with "whatever font" the surrounding text is being typeset. Moreover, Typst
[branding page](https://typst.app/legal/brand/) requires capitalization of the initial "T"
whenever the name is used in prose. Therefore, the "Typst" support in this package is a mere,
still unofficial, implementation of the capitalization of "Typst" in the currently used font.
## Font Requirements
For the `TeX` system and it's derivatives, the `"New Computer Modern"` font is required.
## Usage
The package exposes the following few, parameterless, functions:
- `#texmark()`,
- `#latexmark()`, and
- `#typstmark()`.
Except for the `#typstmark()`, each such command outputs their respective namesake signus
emulation, in the document's current `text` settings, with the exception of font — meaning text
size, color, etc... will apply to the signus emulation.
Aditionally, the signus emulation is produced, as `contexts` text inside a `box` — hence not
images — so as to avoid hyphenation to take place. This also applies to the `#typstmark()`
function, for lack of specific guidance, and also because "Typst" is a short word.
## Example
```typst
#set page(width: auto, height: auto, margin: 12pt, fill: rgb("19181f"))
#set par(leading: 1.5em)
#set text(font: "Rouge Script", fill: rgb("80f4b6"))
#import "@preview/untypsignia:0.1.1": *
#let say() = [I prefer #typstmark() over #texmark() or #latexmark().]
#for sz in (20, 16, 14, 12, 10, 8) {
set text(size: sz * 1pt)
say()
linebreak()
}
```
This example results in a 1-page document like this one:

## Citing
This package can be cited with the following bibliography database entry:
```yml
untypsignia-package:
type: Web
author: <NAME>.
title:
value: "untypsignia: unofficial typesetter's insignia emulations"
url: https://github.com/cnaak/untypsignia.typ
version: 0.1.1
date: 2024-08
```
|
https://github.com/Leedehai/typst-physics | https://raw.githubusercontent.com/Leedehai/typst-physics/master/changelog.md | markdown | MIT License | # Changelog
## 0.9.3
* Add `delim` to `vecrow(..)` to specify the delimiter.
## 0.9.2
* Let `braket()` take an optional third argument to render `braket(u,A,v)` as
`⟨u|A|v⟩`. The one argument case `braket(a)` is still rendered as `⟨a|a⟩` and
the two argument case `braket(u,v)` is still rendered as `⟨u|v⟩`.
* Let `expval()` take an optional second argument to render `expval(A,a)` as
`⟨a|A|a⟩`. The one argument case `expval(A)` is still rendered as `⟨A⟩`.
* **(breaking)** Differentiated big-O `Order(...)` and little-o `order(...)`.
* Let Taylor series term `taylorterm(...)` automatically add parenthesis, so
that e.g. `tarlorterm(f,x,1+a,n-1)`'s `1+a` and `n-1` can be put inside
parenthesis when needed.
* Fixed a rendering issue of `Set(...)` when it contains tall contents.
* Removed the `box(..)` layer from `tensor(...)`'s phantom index.
* Added 2D and 3D rotation matrix `rot2mat(...)` and `rot3mat(...)`.
* Added Gram matrix `grammat(...)`.
* **(breaking)** Removed `gradient` and `divergence`, since most users will use
the abbreviated names `grad` and `div`. This prevents name collisions when users
do wildcard importing, especially with Typst's built-in `gradient` that shows
color gradients on texts.
## 0.9.1
* Added show rules `super-T-as-transpose` and `super-plus-as-dagger`, so that
`..^T` and `..^+` can be rendered as a transpose operator and a dagger
(i.e. conjugate transpose) operator, respectively, just like handwriting.
* Adjusted spacing for `dd()`, following advice in TeXBook Chapter 18. The
intra spacing can be disabled by a new optional argument `compact:#true`.
* Fixed a spacing issue of `vecrow(..)`.
* **(breaking)** Let `iprod(..)` be rendered in the more familiar inner
product `⟨a,b⟩`, instead of `⟨a|b⟩`--that can be done with `braket(a,b)`.
* Added optional argument `big:#true` to Jacobian matrix and Hessian matrix, so
that the fractions can be rendered in an "uncramped" form. The default is the
"cramped" form just like LaTeX.
* Added `taylorterm(...)` to display terms in the Taylor series.
## 0.9.0
Changed the minimum Typst version to 0.10.0.
* Fixed the appearance of `braket`, `ketra`, and `mel`.
* Fixed Hessian matrix `hmax(...)`.
## 0.8.1
## 0.8.0
* Added CI.
* **(breaking)** Let `va(...)` (vector arrow) be not bold, according to the ISO
standard.
## 0.7.5
* First appeared in the official package collection
[typst/packages](https://github.com/typst/packages).
## 0.7.4
* Renamed from `physics` to `physica`, meaning _natural sciences_.
## 0.7.1
## 0.6
## 0.5
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/tidy/0.1.0/src/tidy-parse.typ | typst | Apache License 2.0 |
// Matches Typst docstring for a function declaration. Example:
//
// // This function does something
// //
// // param1 (string): This is param1
// // param2 (content, length): This is param2.
// // Yes, it really is.
// #let something(param1, param2) = {
//
// }
//
// The entire block may be indented by any amount, the declaration can either start with `#let` or `let`. The docstring must start with `///` on every line and the function declaration needs to start exactly at the next line.
// #let docstring-matcher = regex(`((?:[^\S\r\n]*/{3} ?.*\n)+)[^\S\r\n]*#?let (\w[\w\d\-_]+)`.text)
// #let docstring-matcher = regex(`([^\S\r\n]*///.*(?:\n[^\S\r\n]*///.*)*)\n[^\S\r\n]*#?let (\w[\w\d\-_]*)`.text)
#let docstring-matcher = regex(`(?m)^((?:[^\S\r\n]*///.*\n)+)[^\S\r\n]*#?let (\w[\w\d\-_]*)`.text)
// The regex explained:
//
// First capture group: ([^\S\r\n]*///.*(?:\n[^\S\r\n]*///.*)*)
// is for the docstring. It may start with any whitespace [^\S\r\n]*
// and needs to have /// followed by anything. This is the first line of
// the docstring and we treat it separately only in order to be able to
// match the very first line in the file (which is otherwise tricky here).
// We then match basically the same thing n times: \n[^\S\r\n]*///.*)*
//
// We then want a linebreak (should also have \r here?), arbitrary whitespace
// and the word let or #let: \n[^\S\r\n]*#?let
//
// Second capture group: (\w[\w\d\-_]*)
// Matches the function name (any Typst identifier)
// Matches an argument documentation of the form `/// - myparameter (string)`.
#let argument-documentation-matcher = regex(`[^\S\r\n]*/{3} - ([.\w\d\-_]+) \(([\w\d\-_ ,]+)\): ?(.*)`.text)
// Matches docstring references of the form `@@otherfunc` or `@@otherfunc()`.
#let reference-matcher = regex(`@@([\w\d\-_\)\(]+)`.text)
/// #set raw(lang: "typc")
/// Parse a Typst argument list either at
/// - call site, e.g., `f("Timbuktu", value: 23)` or at
/// - declaration, e.g. `let f(place, value: 0)`.
///
/// This function returns a tuple `(args, count-processed-chars)` where
/// `count-processed-chars` is the number of processed characters, i.e., the
/// length of the argument list and `args` is a list with an entry for each
/// argument.
///
/// The entries are lists with either one item if the argument is positional
/// or two items if the argument is named. In this case, the first item holds
/// the name, the second the value. Names as well as values are returned as
/// strings.
///
/// This function returns `none`, if the argument list is not properly closed.
/// Note, that valid Typst code is expected.
///
/// *Example: * Calling this function with the following string
///
/// ```
/// "#let func(p1, p2: 3pt, p3: (), p4: (entries: ())) = {...}"
/// ```
///
/// and index `9` (which points to the opening parenthesis) yields the result
/// ```
/// (
/// (
/// ("p1",),
/// ("p2", "3pt"),
/// ("p3", "()"),
/// ("p4", "(entries: ())"),
/// ("p5",),
/// ),
/// 44,
/// )
/// ```
///
/// This function can deal with
/// - any number of opening and closing parenthesis
/// - string literals
/// We don't deal with:
/// - commented out code (`//` or `/**/`)
/// - raw strings with #raw("``") syntax that contain `"` or `(` or `)`
///
/// - text (string): String to parse.
/// - index (integer): Position of the opening parenthesis of the argument list.
/// -> array
#let parse-argument-list(text, index) = {
if text.at(index) != "(" { return ((:), 0) }
index += 1
let brace-level = 1
let literal-mode = none // Whether in ".."
let arg-strings = ()
let current-arg = ""
let is-named = false // Whether current argument is a named arg
let previous-char = none
let count-processed-chars = 1
let maybe-split-argument(arg, is-named) = {
if is-named {
let colon-pos = arg.position(":")
return (arg.slice(0, colon-pos).trim(), arg.slice(colon-pos + 1).trim())
} else {
return (arg.trim(),)
}
}
for c in text.slice(index) {
let ignore-char = false
if c == "\"" and previous-char != "\\" {
if literal-mode == none { literal-mode = "\"" }
else if literal-mode == "\"" { literal-mode = none }
}
if literal-mode == none {
if c == "(" { brace-level += 1 }
else if c == ")" { brace-level -= 1 }
else if c == "," and brace-level == 1 {
arg-strings.push(maybe-split-argument(current-arg, is-named))
current-arg = ""
ignore-char = true
is-named = false
} else if c == ":" and brace-level == 1 {
is-named = true
}
}
count-processed-chars += 1
if brace-level == 0 {
if current-arg.trim().len() > 0 {
arg-strings.push(maybe-split-argument(current-arg, is-named))
}
break
}
if not ignore-char { current-arg += c }
previous-char = c
}
if brace-level > 0 { return none }
return (arg-strings, count-processed-chars)
}
/// This is similar to @@parse-argument-list but focuses on parameter lists
/// at the declaration site.
///
/// If the argument list is well-formed, a dictionary is returned with
/// an entry for each parsed
/// argument name. The values are dictionaries that may be empty or
/// have an entry for the key `default` containing a string with the parsed
/// default value for this argument.
///
///
///
/// *Example* \
/// Let us take the string
/// ```typc
/// "#let func(p1, p2: 3pt, p3: (), p4: (entries: ())) = {...}"
/// ```
/// Here, we would call `parse-parameter-list(source-code, 9)` and retrieve
/// #pad(x: 1em, ```typc
/// (
/// p0: (:),
/// p1: (default: "3pt"),
/// p2: (default: "()"),
/// p4: (default: "(entries: ())"),
/// )
/// ```)
///
/// - text (string): String to parse.
/// - index (integer): Index where the argument list starts. This index should point to the character *next* to the function name, i.e., to the opening brace `(` of the argument list if there is one (note, that function aliases for example produced by `myfunc.where(arg1: 3)` do not have an argument list).
/// -> none, dictionary
#let parse-parameter-list(text, index) = {
let result = parse-argument-list(text, index)
if result == none { return none }
let (arg-strings, count) = result
let args = (:)
for arg in arg-strings {
if arg.len() == 1 {
args.insert(arg.at(0), (:))
} else {
args.insert(arg.at(0), (default: arg.at(1)))
}
}
return args
}
// Take the result of `parse-argument-list()` and retrieve a list of positional and named
// arguments, respectively. The values are `eval()`ed.
#let parse-arg-strings(args) = {
let positional-args = ()
let named-args = (:)
for arg in args {
if arg.len() == 1 {
positional-args.push(eval(arg.at(0)))
} else {
named-args.insert(arg.at(0), eval(arg.at(1)))
}
}
return (positional-args, named-args)
}
/// Take a documentation string (for example a function or parameter description)
/// and process docstring cross-references (starting with `@@`), turning
/// them into links.
/// - text (string): Source code.
/// - parse-info (dictionary):
#let process-function-references(text, parse-info) = {
return text.replace(reference-matcher, info => {
let target = info.captures.at(0).trim(")").trim("(")
return "#link(label(\"" + parse-info.label-prefix + target + "()\"))[`" + target + "()`]"
})
}
#let example(code) = {
set text(size: .9em)
grid(
columns: 1,
gutter: 1em,
block(radius: 3pt, inset: 5pt, stroke: .5pt + luma(180), code, width: 100%),
block(
width: 100%,
fill: luma(230), radius: 3pt,
inset: 5pt,
rect(
width: 100%,
fill: white,
eval(code.text)
)
)
)
}
#let eval-docstring(docstring, parse-info) = {
let scope = parse-info.scope
let content = process-function-references(docstring.trim(), parse-info)
eval(content, mode: "markup", scope: scope)
}
/// Parse a function docstring that has been located in the source code with given match.
///
/// The return value is a dictionary with the keys
/// - `name` (string): the function name.
/// - `description` (content): the function description.
/// - `args`: A dictionary containing the argument list.
/// - `return-types` (array(string)): A list of possible return types.
///
/// The entries of the argument list dictionary are
/// - `default` (string): the default value for the argument.
/// - `description` (content): the argument description.
/// - `types` (array(string)): A list of possible argument types.
/// Every entry is optional and the dictionary also contains any non-documented arguments.
///
///
///
/// - source-code (string): The source code containing some documented Typst code.
/// - match (match): A regex match that matches a documentation string. The first capture
/// group should hold the entire, raw docstring and the second capture the function name
/// (excluding the opening parenthesis of the argument list if present).
/// - parse-info (dictionary):
/// -> dictionary
#let parse-function-docstring(source-code, match, parse-info) = {
let docstring = match.captures.at(0)
let fn-name = match.captures.at(1)
let fn-desc = ""
let started-args = false
let documented-args = ()
let return-types = none
for line in docstring.split("\n") {
let arg-match = line.match(argument-documentation-matcher)
if arg-match == none {
let trimmed-line = line.trim().trim("/")
if not started-args { fn-desc += trimmed-line + "\n"}
else { // Return type:
if trimmed-line.trim().starts-with("->") {
return-types = trimmed-line.trim().slice(2).split(",").map(x => x.trim())
} else {
documented-args.last().desc += "\n" + trimmed-line
}
}
} else {
started-args = true
let param-name = arg-match.captures.at(0)
let param-types = arg-match.captures.at(1).split(",").map(x => x.trim())
let param-desc = arg-match.captures.at(2)
documented-args.push((name: param-name, types: param-types, desc: param-desc))
}
}
let args = parse-parameter-list(source-code, match.end)
for arg in documented-args {
if arg.name in args {
args.at(arg.name).description = eval-docstring(arg.desc, parse-info)
args.at(arg.name).types = arg.types
} else {
assert(false, message: "The parameter \"" + arg.name + "\" does not appear in the argument list of the function \"" + fn-name + "\"")
}
}
if parse-info.require-all-parameters {
for arg in args {
assert(documented-args.find(x => x.name == arg.at(0)) != none, message: "The parameter \"" + arg.at(0) + "\" of the function \"" + fn-name + "\" is not documented. ")
}
}
return (
name: fn-name,
description: eval-docstring(fn-desc, parse-info),
args: args,
return-types: return-types
)
}
|
https://github.com/FA555/ignite | https://raw.githubusercontent.com/FA555/ignite/main/index.typ | typst | MIT License | #let config-dir = "config"
// #let data-dir = "data"
#let data-dir = sys.inputs.at("data-dir", default: "data")
#let serif-fonts = read(config-dir + "/serif-fonts.txt").split("\n")
#let sans-fonts = read(config-dir + "/sans-fonts.txt").split("\n")
#let font-size = 11pt
#set text(
size: font-size,
font: serif-fonts,
lang: "zh",
region: "cn",
)
#set page(
flipped: true,
margin: (top: 4%, bottom: 4%, left: 4%, right: 4%),
)
#show heading: set block(
above: .95em,
below: .65em,
)
#show heading.where(level: 1): it => {
let foreground = red.darken(40%)
let stroke = (paint: foreground, cap: "round", thickness: .75pt)
set text(
font: sans-fonts,
fill: foreground,
)
grid(
align: horizon,
columns: 3,
column-gutter: .5em,
line(stroke: stroke, length: .5em),
it,
line(stroke: stroke, length: 100%),
)
}
#let data-alphabetic = read(data-dir + "/index_alphabetic.txt").split("\n").filter(line => line.trim() != "").map(line => {
let parts = line.split()
(parts.slice(0, -2).join(" "), parts.at(-2), parts.at(-1))
})
#let initial = none
#columns(
4,
gutter: 3.5%,
{
for (i, entry) in data-alphabetic.enumerate() {
let cur-initial = entry.at(-1).at(0)
if cur-initial != initial {
heading(bookmarked: false, numbering: none, cur-initial)
}
initial = cur-initial
let (body, page-no, _) = entry
grid(
columns: (auto, 1fr, auto),
column-gutter: .5em,
align: (left + top, right + bottom),
body,
repeat(text(fill: gray)[.]),
text(page-no),
)
}
},
)
#pagebreak()
#let data-chapter = read(data-dir + "/index_unsorted.txt").split("\n").filter(line => line.trim() != "").map(line => {
let parts = line.split()
(parts.slice(0, -2).join(" "), parts.at(-2), parts.at(-1))
})
#columns(
4,
gutter: 3.5%,
{
for (i, entry) in data-chapter.enumerate() {
let (body, page-no, is-heading) = entry
if is-heading != "None" {
heading(bookmarked: false, numbering: none, body)
} else {
grid(
columns: (auto, 1fr, auto),
column-gutter: .5em,
align: (left + top, right + bottom),
body,
repeat(text(fill: gray)[.]),
text(page-no),
)
}
}
},
)
|
https://github.com/jiamingluuu/mata35-notes | https://raw.githubusercontent.com/jiamingluuu/mata35-notes/main/rotated-volume.typ | typst | #set page(paper: "a4")
#set text(11pt)
#set par(justify: true)
= Rotated Volume
Consider an arbitrary given function
$ y = f(x) $
// TODO: add picture here
and we are about to rotate the function about $x$-axis. After the rotation, the
under-curve area becomes solid 3 dimensional body's volume. The volume can be
computed by bring the idea when we derive the definition of under-curve area,
that is, integration.
Let's take a close look of the 3D body. Consider an arbitrary slice of the 3D
body,
// TODO: add picture here
as you can observe, the slice is a disc, whose $V$ volume is characterized by
the formula
$ V = pi r^2 h, $
where $r$ is the radius of circle in the cross section, $h$ is the height of the
slice. |
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/meta/ref.typ | typst | Apache License 2.0 | // Test references.
---
#set heading(numbering: "1.")
= Introduction <intro>
See @setup.
== Setup <setup>
As seen in @intro, we proceed.
---
// Error: 1-5 label `<foo>` does not exist in the document
@foo
---
= First <foo>
= Second <foo>
// Error: 1-5 label `<foo>` occurs multiple times in the document
@foo
---
#set heading(numbering: "1.", supplement: [Chapter])
#set math.equation(numbering: "(1)", supplement: [Eq.])
= Intro
#figure(
image("/files/cylinder.svg", height: 1cm),
caption: [A cylinder.],
supplement: "Fig",
) <fig1>
#figure(
image("/files/tiger.jpg", height: 1cm),
caption: [A tiger.],
supplement: "Tig",
) <fig2>
$ A = 1 $ <eq1>
#set math.equation(supplement: none)
$ A = 1 $ <eq2>
@fig1, @fig2, @eq1, (@eq2)
#set ref(supplement: none)
@fig1, @fig2, @eq1, @eq2
|
https://github.com/skriptum/diatypst | https://raw.githubusercontent.com/skriptum/diatypst/main/diaquarto/_extensions/diaquarto/typst-template.typ | typst | MIT License | #let horizontalrule = [
#pagebreak()
] |
https://github.com/dnx04/cv | https://raw.githubusercontent.com/dnx04/cv/main/template/styles.typ | typst | #let hBar() = [#h(5pt) | #h(5pt)]
#let latinFontList = (
"Source Sans 3",
"Calibri",
"Font Awesome 6 Brands",
"Font Awesome 6 Free",
)
#let latinHeaderFont = ("Calibri")
#let awesomeColors = (
skyblue: rgb("#0395DE"),
red: rgb("#DC3522"),
nephritis: rgb("#27AE60"),
concrete: rgb("#95A5A6"),
darknight: rgb("#131A28"),
)
#let regularColors = (
subtlegray: rgb("#ededee"),
lightgray: rgb("#343a40"),
darkgray: rgb("#212529"),
)
#let setAccentColor(awesomeColors, metadata) = {
let param = metadata.layout.awesome_color
return if type(param) == color {
param
} else {
awesomeColors.at(param)
}
} |
|
https://github.com/howardlau1999/sysu-thesis-typst | https://raw.githubusercontent.com/howardlau1999/sysu-thesis-typst/master/templates/cover-no-emblem.typ | typst | MIT License | #import "../functions/style.typ": *
#import "../functions/underline.typ": *
#import "../functions/hline.typ": *
#import "../info.typ": *
#import "../custom.typ": *
#v(30pt)
#set align(center + horizon)
#strong(论文中文题目)
#v(2em)
#strong(论文英文题目)
#v(60pt)
#set text(字号.三号)
#let fieldname(name) = [
#set align(right + top)
#strong(name)
#h(0.25em)
]
#let fieldvalue(value) = [
#set align(center + horizon)
#set text(font: 字体.宋体)
#grid(
rows: (auto, auto),
row-gutter: 0.2em,
value,
line(length: 100%)
)
]
#grid(
columns: (80pt, 280pt),
row-gutter: 1em,
fieldname(text("姓") + h(2em) + text("名")),
fieldvalue(中文作者名),
fieldname(text("学") + h(2em) + text("号")),
fieldvalue(学号),
fieldname(text("学") + h(2em) + text("院")),
fieldvalue(学院),
fieldname(text("专") + h(2em) + text("业")),
fieldvalue(专业),
fieldname("研究方向"),
fieldvalue(方向),
fieldname("指导教师"),
fieldvalue(中文导师名),
)
#v(2em)
#set text(字号.小二)
#text(日期) |
https://github.com/fuchs-fabian/typst-template-aio-studi-and-thesis | https://raw.githubusercontent.com/fuchs-fabian/typst-template-aio-studi-and-thesis/main/docs/manual-en.typ | typst | MIT License | #import "../src/lib.typ": *
#show: project.with(
lang: "en",
authors: (
(name: "<NAME>"),
),
title: "aio-studi-and-thesis v0.1.0",
subtitle: "English Manual",
cover-sheet: (
cover-image: none,
description: [
#text(fill: blue)[#link("https://github.com/fuchs-fabian/typst-template-aio-studi-and-thesis")]
A template for students to create documentation and theses
Translated with: #text(fill: blue.darken(60%))[#link("https://www.deepl.com")]
]
),
abstract: [
This template can be used for extensive documentation as well as for final theses such as bachelor theses.
However, it should always be clarified in advance whether the template is accepted for the planned use.
The template is suitable for both German-language and English-language theses.
It is characterised by the fact that it is highly customisable despite the predefined design.
Initially, all template parameters are optional by default. It is then suitable for documentation.
To make it suitable for theses, only one parameter needs to be changed.
]
)
= Use of the template
After importing the template, a number of options are available. As it may be hard to tell, this template is highly customisable. But don't worry, all parameters are optional. However, it is recommended to specify at least one author under `authors` with `name` and assign a `title`.
It is important to know that external packages are available to the template user by default.
These are:
- #link("https://Typst.app/universe/package/codly", "codly") (Full functional scope)
- #link("https://Typst.app/universe/package/glossarium", "glossarium") (`gls`, `glspl`)
== Minimal use
The import of at least `project` is required.
```Typst
#show: project.with(
// lang: "de",
authors: (
(name: "<NAME>"),
),
title: "Title of the document"
)
```
If the template is to be used in English, `lang` must be changed to `"en"`.
#card[
The translation was made with #link("https://www.deepl.com", "Deepl"), so that no guarantee can be given for the correctness and completeness of the translation.
]
== Maximum configuration options
If certain directories are to be hidden, only the parameters that have `show` in their name must be set to `false`.
If `custom-cover-sheet` is not `none`, the cover sheet is overwritten and `cover-sheet` no longer has any influence. The same applies to `custom-declaration`. If it is not `none`, then `declaration-on-the-final-thesis` is overwritten.
`declaration-on-the-final-thesis` only works if `thesis-compliant` is set to `true`.
If certain dictionaries are used, care must be taken to ensure that parameters with a `required` comment are also contained in the dictionary.
```Typst
#show: project.with(
lang: "de",
authors: (
(
name: "Unknown author", // required
id: "",
email: ""
),
),
title: "Unknown title",
subtitle: none,
date: none,
version: none,
thesis-compliant: false,
// Format
side-margins: (
left: 3.5cm, // required
right: 3.5cm, // required
top: 3.5cm, // required
bottom: 3.5cm // required
),
h1-spacing: 0.5em,
line-spacing: 0.65em,
font: "Roboto",
font-size: 11pt,
hyphenate: false,
// Color settings
primary-color: dark-blue,
secondary-color: blue,
text-color: dark-grey,
background-color: light-blue,
// Cover sheet
custom-cover-sheet: none,
cover-sheet: ( // none
university: ( // none
name: none, // required
street: none, // required
city: none, // required
logo: none
),
employer: ( // none
name: none, // required
street: none, // required
city: none, // required
logo: none
),
cover-image: none,
description: none,
faculty: none,
programme: none,
semester: none,
course: none,
examiner: none,
submission-date: none
),
// Declaration
custom-declaration: none,
declaration-on-the-final-thesis: ( // none
legal-reference: none, // required
thesis-name: none, // required
consent-to-publication-in-the-library: none, // required | true, false
genitive-of-university: none // required
),
// Abstract
abstract: none,
// Outlines
depth-toc: 4,
outlines-indent: 1em,
show-list-of-figures: false,
show-list-of-abbreviations: true,
list-of-abbreviations: (
(
key: "", // required
short: "", // required
plural: "",
long: "",
longplural: "",
desc: none,
group: "",
),
),
show-list-of-formulas: false,
custom-outlines: ( // none
(
title: none, // required
custom: none // required
),
),
show-list-of-tables: false,
show-list-of-todos: false,
literature-and-bibliography: none,
list-of-attachements: ( // none
(a: none), // required
)
)
```
#pagebreak()
= Use of your own ‘Utils’
As there are some functions in Typst that are not available in other programming languages, for example, we have implemented them ourselves. These are also available to the user of the template.
== Colors used
```Typst
blue // rgb("#009fe3")
dark-blue // rgb("#152f4e")
light-blue // rgb("#e8eff7")
dark-grey // rgb("#4a4a49")
green // rgb("#26a269")
purple // rgb("#613583")
```
== Own logic functions
This facilitated the implementation of certain logics for the template.
=== Validation of whether something is `none` or an empty string (`""`).
```Typst
#is-not-none-or-empty(content)
```
=== Validation of whether a dictionary contains a specific `key`.
```Typst
#dict-contains-key(dict: (), key)
```
=== Conversion of content to a string
```Typst
#to-string(content)
```
== Prefabricated contents
=== Simple outline (`simple-outline`)
These are listed in the table of contents.
```Typst
#simple-outline(
title: none,
target: none,
indent: 1em,
depth: none
)
```
=== Content for signing (`signing`)
```Typst
#signing(text: none)
```
#v(1em)
#signing()
#pagebreak()
=== Uniform highlighting of keywords (`emphasised`)
```Typst
#emphasized(fill: dark-blue, it)
```
*Example*:
```Typst
#show "My keyword" : it => emphasized(fill: purple, it)
```
#show "My keyword" : it => emphasized(fill: purple, it)
My keyword
=== TODO Handling
To obtain the TODO string, simply call up the following:
```Typst
#txt-todo
```
#txt-todo
To have a TODO that can also be listed in a table of contents with TODOs and highlighted in the text, the following function can be used:
```Typst
#todo(it)
```
*Example*:
```Typst
#todo("Still to be completed")
// or
#todo[This must also be filled in]
```
#todo("Still to be completed")
#todo[This must also be filled in]
To generate a table of contents for these TODOs, the parameter `show-list-of-todos` in `project` must be set to `true`:
```Typst
show-list-of-todos: true,
```
#pagebreak()
= Use of the ‘general assets’
== Card (`card`)
```Typst
#card(
primary-color: dark-blue,
background-color: light-blue,
title: none,
img: none,
body
)
```
=== Example of the simplest use
```Typst
#card[My text in a card]
```
#card[My text in a card]
=== Example with title
```Typst
#card(title: "My Card")[Content]
```
#card(title: "My Card")[Content]
=== Example with image
```Typst
#card(img: image("certificate.png"))[Content]
```
#card(img: image("certificate.png"))[Content]
#pagebreak()
=== Example with title and image
```Typst
#card(
title: "Card with title and image",
img: image("certificate.png")
)[Content]
```
#card(
title: "Card with title and image",
img: image("certificate.png")
)[Content]
== Author(s) box (`author-box`)
```Typst
#author-box(
background-color: light-blue,
plural: false,
body
)
```
=== Example with one author
```Typst
#author-box[firstname lastname]
```
#author-box[firstname lastname]
=== Example with several authors
```Typst
#author-box(
plural: true
)[firstname1 lastname1, firstname2 lastname2]
```
#author-box(
plural: true
)[firstname1 lastname1, firstname2 lastname2]
#pagebreak()
== Button (`button`)
The fill color (`fill`), the border (`stroke`) and the text color (`text-color`) can be set here.
```Typst
#button(
url: "",
fill: none,
stroke: none,
text-color: none,
body
)
```
=== Example of the simplest use
```Typst
#button[My Button]
```
#button[My button]
=== Example with a link
```Typst
#button(url: "https://github.com/fuchs-fabian")[My link]
```
#button(url: "https://github.com/fuchs-fabian")[My link]
#pagebreak()
= Use of the ‘Assets for project management’
#card[
These assets are suitable for documentation. Please note that their use for a thesis must be agreed with the supervisor in advance.
]
== Persona (`persona`)
```Typst
#persona(
primary-color: dark-blue,
text-color: dark-grey,
background-color: light-blue,
title: txt-todo,
img: image("images/persona.png", width: 6.5em),
name: txt-todo,
age: txt-todo,
family: txt-todo,
job: txt-todo,
do-and-say: txt-todo,
wishes: txt-todo,
see-and-hear: txt-todo,
challenges: txt-todo,
typical-day: txt-todo,
goals: txt-todo
)
```
#pagebreak()
*Example*:
```Typst
#persona(
title: [Student],
//img: none,
name: [<NAME>],
age: [26],
family: [single],
job: [working student],
do-and-say: [
I have no idea how to write documentation or a thesis using LaTex or Word. It's too much work for me to have to adapt everything by hand.
],
wishes: [
A template that I can use for both documentation and theses.
],
see-and-hear: [
- Word is not particularly user-friendly when it comes to creating a professional document.
- LaTex is too powerful to understand well.
],
challenges: [
- To convince professors that there are new and more beautiful ways to create documents
- That this template may be used.
],
typical-day: [
Writing project work and documentation.
],
goals: [
An easier way to create documentation and theses without having to use Word or LaTex.
]
)
```
#persona(
title: [Student],
//img: none,
name: [<NAME>],
age: [26],
family: [single],
job: [working student],
do-and-say: [
I have no idea how to write documentation or a thesis using LaTex or Word. It's too much work for me to have to adapt everything by hand.
],
wishes: [
A template that I can use for both documentation and theses.
],
see-and-hear: [
- Word is not particularly user-friendly when it comes to creating a professional document.
- LaTex is too powerful to understand well.
],
challenges: [
- To convince professors that there are new and more beautiful ways to create documents
- That this template may be used.
],
typical-day: [
Writing project work and documentation.
],
goals: [
An easier way to create documentation and theses without having to use Word or LaTex.
]
)
#pagebreak()
== Retrospective (`retro`)
```Typst
#retro(
primary-color: dark-blue,
secondary-color: blue,
text-color: dark-grey,
background-color: light-blue,
heading-starts-with: 2,
day: txt-todo,
sprint: none,
info: none,
img: image("images/starfish.png", height: 100pt),
more: none,
keep: none,
start: none,
stop: none,
less: none,
improvements: none,
impediments: none,
measures: none
)
```
#pagebreak()
*Example*:
```Typst
#retro(
heading-starts-with: 3,
day: [29/07/2024],
sprint: [1],
info: [
This is my description of the retrospective.
],
//img: none,
more: [
Understanding new technologies and programming languages
],
keep: none,
start: [
Always create documentation and theses with Typst
],
stop: none,
less: none,
improvements: [
- Easier writing of documentation and theses
- Standardised template for all documentation at the university
],
impediments: [
- Formalities and design guidelines
],
measures: [
- Talking to professors
],
)
```
#pagebreak()
#retro(
heading-starts-with: 3,
day: [29/07/2024],
sprint: [1],
info: [
This is my description of the retrospective.
],
//img: none,
more: [
Understanding new technologies and programming languages
],
keep: none,
start: [
Always create documentation and theses with Typst
],
stop: none,
less: none,
improvements: [
- Easier writing of documentation and theses
- Standardised template for all documentation at the university
],
impediments: [
- Formalities and design guidelines
],
measures: [
- Talking to professors
],
)
#pagebreak()
== SMART-Table (`smart`)
```Typst
#smart(
primary-color: dark-blue,
text-color: dark-grey,
background-color: light-blue,
justify: false,
s: txt-todo,
m: txt-todo,
a: txt-todo,
r: txt-todo,
t: txt-todo
)
```
*Example*:
```Typst
#smart(
justify: false,
s: [
#lorem(10)
],
m: [
#lorem(10)
],
a: [
#lorem(10)
],
r: [
#lorem(10)
],
t: [
#lorem(10)
]
)
```
#smart(
justify: false,
s: [
#lorem(10)
],
m: [
#lorem(10)
],
a: [
#lorem(10)
],
r: [
#lorem(10)
],
t: [
#lorem(10)
]
)
#pagebreak()
== User Story
```Typst
#user-story(
primary-color: dark-blue,
text-color: dark-grey,
background-color: light-blue,
id: txt-todo,
title: txt-todo,
sprint: txt-todo,
status: txt-todo,
description: txt-todo,
url: "",
url-without-id: "",
acceptance-criteria: none,
s: none,
m: none,
a: none,
r: none,
t: none,
body
)
```
#pagebreak()
*Example*:
```Typst
#user-story(
id: [1],
title: [The title of the user story],
sprint: [1],
status: [Accepted],
description: [
#lorem(10)
],
s: [
#lorem(10)
],
m: [
#lorem(10)
],
a: [
#lorem(10)
],
r: [
#lorem(10)
],
t: [
#lorem(10)
],
none
)
```
#user-story(
id: [1],
title: [The title of the user story],
sprint: [1],
status: [Accepted],
description: [
#lorem(10)
],
s: [
#lorem(10)
],
m: [
#lorem(10)
],
a: [
#lorem(10)
],
r: [
#lorem(10)
],
t: [
#lorem(10)
],
none
)
#pagebreak()
#set heading(numbering: none)
= Special thanks and recommendation
In creating and publishing this template, the support of one person and their template was invaluable. Thanks to their help, I was able to make this template available to everyone:
#text(size: 1.5em)[#link("https://github.com/SillyFreak", "<NAME> (SillyFreak)")]
I recommend taking a look at his templates as well:
- #link("https://github.com/TGM-HIT/typst-diploma-thesis")
- #link("https://github.com/SillyFreak/typst-package-template")\
Fork of: #link("https://github.com/typst-community/typst-package-template")\ |
https://github.com/HFU-CV-projects/typst-template | https://raw.githubusercontent.com/HFU-CV-projects/typst-template/main/main.typ | typst | #import "@preview/lovelace:0.3.0": * // This is a library for pseudocode
#show figure.caption: set align(start); // The caption alignment of the figure is set to the start/left (the default position is center).
#show figure.caption: set text(8pt) // Figure text size
#show heading: set text(18pt) // Heading text size
#show heading: set block(spacing: 1.5em) // spacing after and before heading
#set list(indent: 1em) // list indent
#set text(font: "New Computer Modern Sans") // text font
#show cite: set text(style: "italic") // cites are italic
#set par(justify: true) // block letter
// #set page(paper: "a4") // a4 is default
// Use this for cite color (in this case blue)
#show cite: it => {
// color everthing except brackets
show regex("[a-zA-Zöü&\d.,.-]"): set text(fill: blue)
// or regex("[\p{L}\d+]+") when using the alpha-numerical style
it
}
// Use this for ref color (in this case blue)
#show ref: it => {
if it.element == none {
// This is a citation, which is handled above.
return it
}
show regex("[a-zA-Zöü&\d.,.-]"): set text(fill: blue)
it
}
// Table of contents main cheapters are strong/bold
#show outline.entry.where(
level: 1,
): it => {
v(12pt, weak: true)
strong(it)
}
// --------------------------------- TITLE/COVER PAGE -----------------------------------------------------
// use this variables:
#let bachelor_or_Master = "b" // "b" or "m" for bachelor or master
#let your_name = "<NAME>"
#let science_type = "science" // of Science or of Arts? (Science or arts)
#let matriculation_number = "123456"
#let faculty = "digital media"
#let degree_course = "Computer Science in media" // e.g Computer Science in Media
#let university_supervisor= "Prof. Dr. <NAME>"
#let second_supervisior = "Not Prof. <NAME>"
#let external_thesis = true // Are you writing this thesis in a company? (true, false)
#let submitted = "30.11.2024"
#let thesis_title_line_1 = "Here are some cool title"
#let thesis_title_line_2 = "for your amazing thesis"
#let degree = ""
#let d_short = ""
#if (bachelor_or_Master == "b" or bachelor_or_Master == "B") {
d_short = "B"
degree = "Bachelor"
} else if (bachelor_or_Master == "m" or bachelor_or_Master == "M"){
d_short = "M"
degree = "Master"
}
#let science_short = ""
#if (science_type == "science" or science_type == "Science") {
science_short = "Sc."
} else if (bachelor_or_Master == "Arts" or bachelor_or_Master == "arts"){
science_short = "A."
}
#let first_supervisor_form = ""
#let second_supervisior_form = ""
#if (external_thesis) {
first_supervisor_form = "University supervisor"
second_supervisior_form = "External supervisor"
} else {
first_supervisor_form = "First supervisor"
second_supervisior_form = "Second supervisor"
}
// HFU logo
#place(
dx: (100% - 180pt),
image("images/Hochschule_Furtwangen_HFU_logo.svg", width: 200pt)
)
// second logo if necessary
#place(
dy: 7pt,
dx: 0pt,
image("images/placeholder.png", width: 150pt, height: 70pt)
)
#v(100pt) // vertical space
#strong(text([#degree Thesis], size: 45pt, baseline: 20pt)) //use strong for bold
#text([by], size: 15pt, baseline: 8pt) \ // this "/" is a linebreak
#strong(text([#your_name], size: 20pt))
#text([This thesis submitted for the degree of], size: 15pt, baseline: 17pt) \
#strong(text([#degree of #science_type (#d_short. #science_short)], size: 20pt, baseline: 10pt))
#text([on the faculty of #faculty], size: 15pt) \
#v(35pt)
#strong(text([#thesis_title_line_1], size: 25pt, spacing: 18pt)) \
#strong(text([#thesis_title_line_2], size: 25pt, spacing: 18pt)) \
#v(40pt)
#let title_size = 15pt
#place(
dy: 25pt,
table(
columns: 2,
stroke: none,
align: left,
inset: 6pt,
text([Degree course:], size: title_size), text([#degree_course, #degree], size: title_size),
text([Matriculation number:], size: title_size), text([#matriculation_number], size: title_size),
[],[],
[],[],
[],[],
text([#first_supervisor_form:], size: title_size), text([#university_supervisor], size: title_size),
text([#second_supervisior_form:], size: title_size), text([#second_supervisior], size: title_size),
text([submitted], size: title_size), text([#submitted], size: title_size),
))
#pagebreak()
= Abstract
cite:\
@hahne_real-time_2012.\
#cite(<hahne_real-time_2012>, supplement: [p.~11]).\
#cite(<hahne_real-time_2012>, form: "year").\
#cite(<hahne_real-time_2012>, form: "author").\
#cite(<hahne_real-time_2012>, style: "alphanumeric") \
#cite(<hahne_real-time_2012>, style: "vancouver") \
#cite(<hahne_real-time_2012>, style: "american-physics-society")
multiple cites:\
#cite(<hahne_real-time_2012>, style: "american-physics-society") #cite(<fake_cite1>, style: "american-physics-society") #cite(<fake_cite2>, style: "american-physics-society") \
#cite(<hahne_real-time_2012>) #cite(<fake_cite1>) #cite(<fake_cite2>)
#emph[Emph text]\
#strong([Bold text]) \
#text([Text size], size: 7pt) \
#text([Text size], size: 10pt)\
#let text_size = 15pt
#text([Text size], size: text_size)\
math:\
When it comes to math, you use \$ you math \$:
$ mat(
delim: "[",
r_11, r_12, r_13, p_x;r_21, r_22, r_23, p_y;r_31, r_32, r_33, p_z;0, 0, 0, 1,
) $ \
$ X , theta , phi.alt arrow.r R G B , sigma $ \
some inline examble:
$ T(t) = exp(- integral_(t_n)^t sigma (r (s)) d s) $ Where $sigma (r(s))$ is the volume density along the ray depending on the position $r(s)$ on ray $r(t) = o + t d$. \"The Function $T(t)$ denotes the accumulated transmittance along the ray from $t n$ to $t$, i.e., the probability that the ray travels from $t n$ to $t$ without hitting any other particle." \
product:
#align(center,$T_n = product^n_(i=1) exp(-sigma_i ⋅ Delta_(s_i))$)
scripting:
#let num1 = 1
#let num2 = 2
#num1 + #num2 = #{num1 + num2}
#{
let num3 = 1
let num4 = 2
let result = num1 + num2
[#num3 + #num4 = #result]
}
#for letter in "abc nope" {
if letter == " " {
break
}
letter
}
#text([This], fill: red) #text([text], fill: gradient.radial(..color.map.rainbow)) #text([has], fill: cmyk(100%, 0%, 33%, 0%)) some #text([color], fill: rgb(255, 0%, 255))
- List1
- List2
- List3
#figure(image("images/placeholder.png", width: 20%), caption: [This Image has 20% width. You can also use other types like mm, cm, em, pt]) <fig:placeholder>
#figure(image("images/placeholder.png", width: 20em), caption: [with 20em])
This is a reference to the placeholder image: @fig:placeholder \
This is a reference to the implementation: @implementation \
This is a reference to the implementation with name: #ref(<implementation>, supplement: [Implementation])
#pagebreak()
table with alignment:
#align(
figure(
table(
columns: 3,
stroke: none,
inset: 6pt,
[#strong[Title 1]],
[#strong[Title 1]],
[#strong[Title 1]],
[Column 1], [A 24324], [B 20.3412],
[Column 2], [A 00498], [B 58.9121],
[Column 4], [A 04195], [#highlight(fill: rgb(122, 205, 255), "B 389.1807")],
[Column 5], [A 18757], [194.9974],
[Column 6], [A 14663], [#highlight(fill: rgb(255, 174, 122), "B 1.6392")],
),
)) <tab:my_table>
grid with variables:
#let width = 35pt
#let height = 35pt
#let text_size = 9pt
#grid(
columns: 11, // 2 means 2 auto-sized columns
rows: 2,
gutter: 2mm, // space between columns
image("images/placeholder.png", width: width, height: height),
image("images/placeholder.png", width: width, height: height),
image("images/placeholder.png", width: width, height: height),
image("images/placeholder.png", width: width, height: height),
image("images/placeholder.png", width: width, height: height),
image("images/placeholder.png", width: width, height: height),
image("images/placeholder.png", width: width, height: height),
image("images/placeholder.png", width: width, height: height),
image("images/placeholder.png", width: width, height: height),
image("images/placeholder.png", width: width, height: height),
image("images/placeholder.png", width: width, height: height),
[Image 1], [Image 2], [Image 3],[Image 4],[Image 5],[Image 5],[Image 7],[Image 8],[Image 9],[#text([Image, 10], size: text_size)], [#text([Image, 11], size: text_size)]
)
Some Pseudocode. You need to import Lovelace for this. Typst has more libraries for pseudocode and other things.
#pseudocode-list()[
+ *Function* compute_some_stuff(a, b, list, threshold):
+ Set scale to 2.0
+ result = 0
+ *For* x in list:
+ sum list with x
+ *If* result*scale > threshold
+ return: result
+ *End If*
+ *End For*
+ return: max value from list
+ *End*
]
#pagebreak()
= Zusammenfassung
#lorem(500)
#pagebreak()
#set heading(numbering: "1.") // start heading numbering
#outline(depth: 4, indent: 2em) // include table of context.
#set page(numbering: "1")
#counter(page).update(1)
= Introduction <introduction>
== Depth1
=== Depth2
==== Depth3
#lorem(200)
#pagebreak()
= Related Work <related-work>
#lorem(200)
#pagebreak()
= Method <Validation>
#lorem(200)
#pagebreak()
= Implementation <implementation>
#lorem(200)
#pagebreak()
= Conclusion <conclusion>
#lorem(200)
#pagebreak()
= Discussion <discussion>
#lorem(200)
#pagebreak()
= Use of AI in this thesis <use-of-ai-in-this-thesis>
#pagebreak()
// inser bibliography is necessary.
#bibliography("references.bib", full: false, style:"apa") |
|
https://github.com/jonatchoum/quarto-jon-thesis-template | https://raw.githubusercontent.com/jonatchoum/quarto-jon-thesis-template/main/_extensions/jon_thesis/typst-template.typ | typst | // Official declaration of originality, both in English and Italian
// taken directly from <NAME>'s email
#let declaration-of-originality = (
"en": [
I declare to be responsible for the content I'm presenting in order to obtain the final degree, not to have plagiarized in all or part of, the work produced by others and having cited original sources in consistent way with current plagiarism regulations and copyright. I am also aware that in case of false declaration, I could incur in law penalties and my admission to final exam could be denied
],
"it": [
Dichiaro di essere responsabile del contenuto dell'elaborato che presento al fine del conseguimento del titolo, di non avere plagiato in tutto o in parte il lavoro prodotto da altri e di aver citato le fonti originali in modo congruente alle normative vigenti in materia di plagio e di diritto d'autore. Sono inoltre consapevole che nel caso la mia dichiarazione risultasse mendace, potrei incorrere nelle sanzioni previste dalla legge e la mia ammissione alla prova finale potrebbe essere negata.
],
"fr": [
]
)
// FIXME: workaround for the lack of `std` scope
#let std-bibliography = bibliography
#let template(
// Your thesis title
title: [Thesis Title],
// The academic year you're graduating in
academic-year: [2023/2024],
// Your thesis subtitle, should be something along the lines of
// "Bachelor's Thesis", "Tesi di Laurea Triennale" etc.
subtitle: [Bachelor's Thesis],
// The paper size, refer to https://typst.app/docs/reference/layout/page/#parameters-paper for all the available options
paper-size: "a4",
// Candidate's informations. You should specify a `name` key and
// `matricola` key
candidate: (),
// The thesis' supervisor (relatore)
supervisor: "",
// An array of the thesis' co-supervisors (correlatori).
// Set to `none` if not needed
co-supervisor: (),
// An affiliation dictionary, you should specify a `university`
// keyword, `school` keyword and a `degree` keyword
affiliation: (),
// Set to "it" for the italian template
// Set to "fr" for the french template
lang: "fr",
// The thesis' bibliography, should be passed as a call to the
// `bibliography` function or `none` if you don't need
// to include a bibliography
bibliography: none,
// The university's logo, should be passed as a call to the `image`
// function or `none` if you don't need to include a logo
logo: none,
logo2: none,
// Abstract of the thesis, set to none if not needed
abstract: none,
// Acknowledgments, set to none if not needed
acknowledgments: none,
// The thesis' keywords, can be left empty if not needed
keywords: none,
// The thesis' content
body
) = {
// Set document matadata.
set document(title: title, author: candidate.name)
// Set the body font, "New Computer Modern" gives a LaTeX-like look
set text(font: "New Computer Modern", lang: lang, size: 12pt)
// Configure the page
set page(
paper: paper-size,
// Margins are taken from the university's guidelines
margin: (right: 3cm, left: 3.5cm, top: 3.5cm, bottom: 3.5cm)
)
// Configure equation numbering and spacing.
set math.equation(numbering: "(1)")
show math.equation: set block(spacing: 0.65em)
// Configure raw text/code blocks
show raw.where(block: true): set text(size: 0.8em, font: "Fira Code")
show raw.where(block: true): set par(justify: false)
show raw.where(block: true): block.with(
fill: gradient.linear(luma(240), luma(245), angle: 270deg),
inset: 10pt,
radius: 4pt,
width: 100%,
)
show raw.where(block: false): box.with(
fill: gradient.linear(luma(240), luma(245), angle: 270deg),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Configure figure's captions
show figure.caption: set text(size: 0.8em)
// Configure lists and enumerations.
set enum(indent: 10pt, body-indent: 9pt)
set list(indent: 10pt, body-indent: 9pt, marker: ([•], [--]))
// Configure headings
set heading(numbering: "1.a.I")
show heading.where(level: 1): it => {
if it.body not in ([References], [Riferimenti]) {
block(width: 100%, height: 20%)[
#set align(center + horizon)
#set text(1.3em, weight: "bold")
#smallcaps(it)
]
} else {
block(width: 100%, height: 10%)[
#set align(center + horizon)
#set text(1.1em, weight: "bold")
#smallcaps(it)
]
}
}
show heading.where(level: 2): it => block(width: 100%)[
#set align(center)
#set text(1.1em, weight: "bold")
#smallcaps(it)
]
show heading.where(level: 3): it => block(width: 100%)[
#set align(left)
#set text(1em, weight: "bold")
#smallcaps(it)
]
// Title page
set align(center)
block[
#let jb = linebreak(justify: true)
#text(1.5em, weight: "bold", affiliation.university) #jb
#text(1.2em, [
#smallcaps(affiliation.school) #jb
#affiliation.degree #jb
])
]
grid(
columns: (1fr,1fr),
rows: (auto),
gutter: 3pt,
grid.cell(
colspan: 1,
if logo != none {
logo
}
),
grid.cell(
colspan: 1,
if logo2 != none {
logo2
}
),
)
// v(3fr)
// if logo != none {
// logo
// }
// v(3fr)
// v(3fr)
// if logo2 != none {
// logo2
// }
// v(3fr)
text(1.5em, subtitle)
v(1fr, weak: true)
text(2em, weight: 700, title)
v(4fr)
grid(
columns: 2,
align: left,
grid.cell(
inset: (right: 40pt)
)[
#if lang == "en" {
smallcaps("supervisor")
} else if lang == "fr" {
smallcaps("tuteur")
} else {
smallcaps("relatore")
}\
*#supervisor*
#if co-supervisor != none {
if lang == "en" {
smallcaps("co-supervisor")
} else if lang == "fr" {
smallcaps("pilote de formation")
} else {
smallcaps("correlatore")
}
linebreak()
co-supervisor.map(it => [
*#it*
]).join(linebreak())
}
],
grid.cell(
inset: (left: 40pt)
)[
\ \ \
#if lang == "en" {
smallcaps("candidate")
} else if lang == "fr" {
smallcaps("apprenti")
} else {
smallcaps("candidato")
}\
*#candidate.name* \
#candidate.matricola
]
)
v(5fr)
text(1.2em, [
#if lang == "en" {
"Academic Year "
} else if lang == "fr" {
"Année scolaire"
} else {
"Anno Accademico "
}
#academic-year
])
pagebreak(to: "odd")
set par(justify: true, first-line-indent: 1em)
set align(center + horizon)
text(style: "italic", "fake page 1 confi")
pagebreak()
text(style: "italic", "fake page 2 confi")
pagebreak()
// Declaration of originality, prints in English or Italian
// depending on the `lang` parameter
// heading(
// level: 2,
// numbering: none,
// outlined: false,
// if lang == "en" {
// "Declaration of Originality"
// } else if lang == "fr" {
// "Déclaration sur l'honneur"
// } else {
// "Dichiarazione di Originalità"
// }
// )
// text(style: "italic", declaration-of-originality.at(lang))
// pagebreak(weak: true)
// Acknowledgments
if acknowledgments != none {
heading(
level: 2,
numbering: none,
outlined: false,
if lang == "en" {
"Acknowledgments"
} else if lang == "fr" {
"Remerciements"
} else {
"Ringraziamenti"
}
)
acknowledgments
pagebreak(weak: true)
}
// Abstract
if abstract != none {
heading(
level: 2,
numbering: none,
outlined: false,
"Abstract"
)
abstract
}
// Keywords
if keywords != none {
heading(
level: 2,
numbering: none,
outlined: false,
if lang == "en" {
"Keywords"
} else if lang == "fr" {
"Mots-clefs"
} else {
"Parole chiave"
}
)
keywords
}
pagebreak(weak: true, to: "odd")
// Table of contents
// Outline customization
show outline.entry.where(level: 1): it => {
if it.body != [References] {
v(12pt, weak: true)
link(it.element.location(), strong({
it.body
h(1fr)
it.page
}))}
else {
text(size: 1em, it)
}
}
show outline.entry.where(level: 3): it => {
text(size: 0.8em, it)
}
outline(depth: 3, indent: true)
pagebreak(to: "odd")
// Main body
show link: underline
set page(numbering: "1")
set align(top + left)
counter(page).update(1)
body
pagebreak(to: "odd")
// Bibliography
if bibliography != none {
heading(
level: 1,
numbering: none,
if lang == "en" {
"References"
} else if lang == "fr" {
"Références"
} else {
"Riferimenti"
}
)
show std-bibliography: set text(size: 0.9em)
set std-bibliography(title: none)
bibliography
}
} |
|
https://github.com/Skimmeroni/Appunti | https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Interi/Congruenza.typ | typst | Creative Commons Zero v1.0 Universal | #import "../Metodi_defs.typ": *
Sia $n in ZZ$ con $n > 0$ e siano $a$ e $b$ due numeri interi. $a$ e $b$
si dicono *congruenti* (o *congrui*) *modulo* $n$ se vale $n | a - b$,
ovvero se esiste un certo $k in ZZ$ tale per cui $a - b = n k$. In altre
parole, due numeri interi $a$ e $b$ sono congruenti modulo $n$ se la loro
divisione per $n$ restituisce il medesimo resto. Per indicare che $a$ e
$b$ sono congruenti modulo $n$ si usa la notazione $a equiv b mod n$.
#example[
Avendosi $12 | 38 - 14$, é possibile scrivere $38 equiv 14 mod
12$. Si noti inoltre come sia $38$ sia $14$, divisi per $12$,
diano resto $2$.
]
La definizione puó essere estesa anche al caso in cui $n = 0$. Si noti
infatti come, se vale $n = 0$, si ha $a - b = 0 dot k$, ovvero $a = b$.
Pertanto, la congruenza modulo 0 coincide semplicemente con la relazione
di uguaglianza in $ZZ$.
La definizione puó essere inoltre estesa anche al caso in cui $n < 0$.
Infatti, basta osservare che $n | a − b$ se e solo se $−n | a − b$ per
concludere che $a equiv b mod n$ se e solo se $a equiv b mod − n$. Per
questo motivo, non é limitativo considerare $n > 0$.
#lemma[
Sia $n in ZZ$ con $n > 0$. Dati quattro interi $a$, $b$, $c$ e $d$,
se vale $a equiv b mod n$ e $c equiv d mod n$ allora vale $a + b equiv
c + d mod n$ e $a b equiv c d mod n$.
]
#example[
La congruenza lineare dell'@Example-congruence-solution, che aveva
per soluzione particolare $c = 5$. Avendosi $"MCD"(21, 30) = 3$, si
ha $frac(30, 3) = 10$. Pertanto, tale congruenza lineare ha per
soluzioni ogni intero nella forma $6 + 10 h$ con $h in ZZ$. In
particolare, le soluzioni non congruenti modulo $n$ fra di loro sono
$c = 6$, $c = 16$ e $c = 26$.
]
#lemma[
Siano $a, b, c, n in ZZ$, con $c != 0$. Allora $a c equiv b c mod n$
equivale a $a equiv b mod frac(n, "MCD"(c, n))$.
] <Simplification-law-congruences>
#proof[
Per definizione di congruenza modulo $n$, l'espressione $a c equiv b c
mod n$ equivale a $n | a c - b c$. Deve allora esistere un certo $q in
ZZ$ tale per cui $a c - b c = n q$, ovvero $(a - b) c = n q$. Siano
$c = tilde(c) "MCD"(c, n)$ e $n = tilde(n) "MCD"(c, n)$. Si ha:
$ (a - b) c = n q => (a - b) tilde(c) cancel("MCD"(c, n)) =
tilde(n) cancel("MCD"(c, n)) q => (a - b) tilde(c) = tilde(n) q =>
tilde(n) | (a - b) tilde(c) $
Per il @Euclid-lemma, almeno una delle due proposizioni fra $tilde(n) |
a - b$ e $tilde(n) | tilde(c)$ deve essere vera. La prima proposizione
equivale a $a equiv b mod tilde(n)$; ricordando la definizione di
$tilde(n)$, si ha $a equiv b mod frac(n, "MCD"(c, n))$.
]
#corollary("Legge di cancellazione per le congruenze lineari")[
Siano $a, b, c, n in ZZ$, con $c$ non nullo e con $c$ ed $n$ coprimi.
Allora $a c equiv b c mod n$ equivale a $a equiv b mod n$.
] <Cancellation-law-congruences>
#proof[
Se $c$ ed $n$ sono coprimi, allora $"MCD"(c, n) = 1$. Applicando il
@Simplification-law-congruences, si ha che $a c equiv b c mod n$
equivale a $a equiv b mod frac(n, 1)$, ovvero $a equiv b mod n$.
]
#theorem[
Per ogni numero intero $n > 0$, la congruenza modulo $n$ é una
relazione di equivalenza su $ZZ$.
] <Congruence-mod-is-equivalence>
#proof[
La congruenza modulo $n$ definisce su $ZZ$ la relazione $cal(R)$
data da:
$ forall a, b in ZZ, (a, b) in cal(R) "se e solo se" a equiv b mod n $
La relazione in questione é:
+ Riflessiva: $forall a in ZZ$ vale $a equiv a mod n$. Infatti,
$a equiv a mod n$ equivale a dire $a - a = 0 = k n$, che é valido
per $k = 0$ e per qualsiasi $a in ZZ$;
+ Simmetrica: $forall a, b in ZZ$, $a equiv b mod n$ implica $b equiv
a mod n$. Infatti, $a equiv b mod n$ equivale a dire $a − b = k n$ per
un certo $k in ZZ$. Moltiplicando per $-1$ ambo i membri si ha $-(a − b)
= -(k n)$, ovvero $b − a = (−k) n$, cioé $b equiv a mod n$;
+ Transitiva: $forall a, b, c in ZZ$, $a equiv b mod n$ e $b equiv c mod n$
implicano $a equiv c mod n$. Infatti, $a equiv b mod n$ e $b equiv c mod
n$ equivalgono a dire, rispettivamente, $a − b = k n$ e $b − c = h n$ per
certi $h, k in ZZ$. Sommando la seconda alla prima:
$ a − b + (b - c) = k n + (b − c) => a - cancel(b) + cancel(b) - c =
k n + h n => a - c = (k + h) n => a equiv c mod n $
Pertanto, é una relazione di equivalenza.
]
Viene detta *congruenza lineare modulo* $n$ qualunque espressione nella forma:
$ a x equiv b mod n " con " a, b, n in ZZ $
Dove $a$, $b$ ed $n$ sono termini noti ed $x$ é una incognita. Naturalmente,
le _soluzioni_ di una congruenza lineare sono tutti e soli quei $c in ZZ$
tali che, sostituiti ad $x$, rendono valida l'espressione. Se esiste almeno
un $c$ con queste caratteristiche, si dice che la congruenza lineare _ammette_
soluzione.
#example[
Si consideri la congruenza lineare $2 x equiv 3 mod 7$. Una possibile
soluzione per tale congruenza é $c = 5$, dato che $2 dot 5 = 10$ ed
effettivamente $10 equiv 3 mod 7$. Anche $c = 26$ é una possibile
soluzione, dato che $2 dot 26 = 52 equiv 3 mod 7$.
] <Congruence>
#theorem[
Siano $a$, $b$, $n in ZZ$, con $a != 0$. La congruenza lineare $a x
equiv b mod n$ ammette soluzione se e soltanto se $"MCD"(a, n) | b$.
] <Congruence-solutions-exist>
#proof[
Da definizione di congruenza modulo $n$, si ha che $a x equiv b
mod n$ equivale a $n | a x - b$, che a sua volta equivale a $a x
- b = n k$ per un certo $k in ZZ$. Spostando $b$ al secondo membro,
si ha $a x - n k = b$; dato che tutti i numeri che figurano in
questa equazione sono numeri interi, si sta avendo a che fare
con una equazione diofantea, nello specifico nelle variabili $x$
e $k$. Per il @Diophantine-solutions-exist, l'equazione ha soluzione
se e soltanto se $"MCD"(a, n) | b$, ma dato che tale equazione é
solamente una riscrittura di $a x equiv b mod n$, allora anche
quest'ultima avrá soluzione se e solo se sono rispettate tali
condizioni.
]
#example[
- La congruenza lineare dell'@Congruence ha soluzioni, perché
$"MCD"(a, n) = 1$ ed é vero che $1 | 3$;
- La congruenza lineare $2 x equiv 3 mod 4$ non ha soluzioni,
perché $"MCD"(a, n) = 2$ ed é falso che $2 | 3$.
]
Il @Congruence-solutions-exist fornisce implicitamente un approccio
per cercare una soluzione particolare di una congruenza lineare,
ovvero costruendo una equazione diofantea a questa equivalente e
risolvendola. La soluzione particolare é data dalla componente $x$
della soluzione particolare di tale equazione.
#example[
Si consideri la congruenza lineare $21 x equiv 6 mod 30$. L'equazione
diofantea associata é $21 x - 30 k = 6$. Si ha:
#set math.mat(delim: none)
$
mat(
30 & = 21 dot 1 + 9;
21 & = 9 dot 2 + 3;
9 & = 3 dot 3 + 0;
)
space space space
mat(
b & = a dot 1 + 9 => 9 = b - a;
a & = 2 (b - a) + 3 => 3 = 3 a - 2 b;
)
space space space
(6) 21 - (4) 30 = 6
$
Da cui si ricava la soluzione particolare $c = 6$ per la
congruenza lineare.
] <Example-congruence-solution>
#theorem[
Siano $a$, $b$, $n in ZZ$, con $a != 0$. Si consideri la congruenza
lineare $a x equiv b mod n$: se $x_(0) in ZZ$ ne é una soluzione,
allora lo sono anche tutti ed i soli numeri interi $x_(h)$ nella
forma:
$ x_(h) = x_(0) + h (frac(n, "MCD"(a, n))) " con" h in ZZ $
In particolare, fra queste ne esistono esattamente $"MCD"(a, n)$
non congruenti modulo $n$ fra di loro.
]
#proof[
Per il @Congruence-solutions-exist, $a x equiv b mod n$ ha soluzione se
e soltanto se ha soluzione l'equazione diofantea equivalente $a x - n k
= b$ con $k in ZZ$. Per il @Diophantine-all-solutions si ha che se
$(x_(0), k_(0)) in ZZ times ZZ$ é una soluzione particolare di
tale equazione, allora lo sono tutte e sole le coppie $(x_(h), k_(h))
in ZZ times ZZ$ nella forma:
$ x_(h) = x_(0) + h (frac(n, "MCD"(a, n))) space space space
k_(h) = k_(0) - h (frac(n, "MCD"(a, n)))
" con" h in ZZ $
L'espressione per $x_(h)$ é quella cercata. Per provare che la congruenza
lineare ha esattamente $"MCD"(a, n)$ soluzioni non congruenti modulo $n$
fra di loro, si consideri $h_(1), h_(2) in ZZ$. Si ha:
$ x_(0) + h_(1) (frac(n, "MCD"(a, n))) equiv
x_(0) + h_(2) (frac(n, "MCD"(a, n))) mod n <==>
(frac(n, "MCD"(a, n))) (h_(1) - h_(2)) equiv 0 mod n $
Deve allora esistere un certo $q in ZZ$ tale per cui:
$ (frac(n, "MCD"(a, n))) (h_(1) - h_(2)) equiv 0 mod n =>
(frac(cancel(n), "MCD"(a, n))) (h_(1) - h_(2)) = q cancel(n) =>
h_(1) - h_(2) = q "MCD"(a, n) $
Pertanto, le $"MCD"(a, n)$ soluzioni non congruenti modulo $n$ fra
di loro che si stavano cercando sono tutte e sole le soluzioni con
$h = 0, 1, ..., ("MCD"(a, n) - 1)$.
]
Viene detto *sistema di congruenze lineari* qualunque espressione nella forma:
$
A_(i) x equiv B_(i) mod N_(i) =
cases(
a_(1) x equiv b_(1) & mod n_(1),
a_(2) x equiv b_(2) & mod n_(2),
dots.v,
a_(m) x equiv b_(m) & mod n_(m)
) " con " a_(1), ..., a_(m), b_(1), ..., b_(m), n_(1), ..., n_(m) in ZZ
$
Dove $a_(1), ..., a_(m)$, $b_(1), ..., b_(m)$ e $n_(1), ..., n_(m)$
sono termini noti ed $x$ é una incognita. Le _soluzioni_ di un sistema
di congruenze lineari sono tutti e soli quei $c in ZZ$ tali che,
sostituiti ad $x$, verificano contemporaneamente tutte le $m$ congruenze
lineari modulo $n_(i)$ che lo compongono. Se esiste almeno un $c$ con
queste caratteristiche, si dice che il sistema di congruenze lineari
_ammette_ soluzione.
#lemma("Condizione necessaria per la solubilitá di un sistema di congruenze lineari")[
Un sistema di congruenze lineari $A_(i) x equiv B_(i) mod N_(i)$ ha
soluzione soltanto se, per ogni $i = 1, ..., m$, si ha $"MCD"(a_(i),
n_(i)) | b_(i)$.
] <System-sufficient-condition>
#proof[
Per il @Congruence-solutions-exist, si ha che $a x equiv b mod n$ ha
soluzione se e soltanto se $"MCD"(a, n) | b$. Dato che un sistema di
congruenze lineari ha soluzione soltanto se tutte le congruenze che
lo compongono hanno soluzione, tale sistema avrá soluzione soltanto
se $"MCD"(a_(i), n_(i)) | b_(i)$ é valido per ogni $i = 1, ..., m$.
]
Si noti come il @System-sufficient-condition sia una implicazione
a senso unico, ovvero potrebbero esistere dei sistemi di congruenze
lineari che lo verificano ma che comunque non hanno soluzione. Infatti,
le congruenze lineari che costituiscono un sistema potrebbero essere
solubili individualmente, ma nessuna di queste avere una soluzione che
sia comune a tutte.
#theorem("Teorema Cinese del Resto")[
Si consideri un sistema di congruenze lineari come quello presentato
di seguito:
$
cases(
x equiv b_(1) & mod n_(1),
dots.v,
x equiv b_(2) & mod n_(2),
x equiv b_(m) & mod n_(m)
) " con " b_(1), ..., b_(m), n_(1), ..., n_(m) in ZZ
$
Ovvero, dove i termini $a_(1), ..., a_(m)$ sono tutti pari ad 1. Si assuma
inoltre che i termini $n_(1), ..., n_(m)$ siano tutti positivi e che siano
a due a due coprimi, ovvero $"MCD"(n_(i), n_(j)) = 1$ per ogni $1 lt.eq i
lt.eq m$ e $1 lt.eq j lt.eq m$ tali per cui $i != j$.
Allora il sistema é risolubile. In particolare, se $c$ e $c'$ sono due
soluzioni, allora vale:
$ c equiv c' mod N " dove " N = n_(1) dot n_(2) dot ... dot n_(m) =
product_(i = 1)^(m) n_(i) $
] <Chinese-remainder-theorem>
#proof[
Per ogni $i = 1, ..., m$, sia $N_(i) = frac(N, n_(i))$ (essendo
$N = product_(i = 1)^(m) n_(i)$ é garantito che $N_(i)$ sia un
numero intero, perché $n_(i)$ é uno dei fattori di $N$). Per
ipotesi, si ha $"MCD"(n_(i), n_(j)) = 1$ per $i != j$. Tuttavia,
é facile verificare che anche $"MCD"(N_(i), n_(i)) = 1$.
Infatti, si supponga per assurdo che $"MCD"(N_(i), n_(i)) != 1$.
Deve allora esistere un numero primo $p$ tale per cui $p | n_(i)$
e $p | N_(i)$, ovvero che é divisore sia di $n_(i)$ che di $N_(i)$.
Essendo $N_(i) = n_(1) dot ... dot n_(i - 1) dot n_(i + 1) dot ...
dot n_(m)$, per il @Euclid-lemma deve esistere un $n_(j)$ con $j !=
i$ tale per cui $p | n_(j)$. Ma allora, valendo sia $p | n_(i)$ sia
$p | n_(j)$, si ha che $n_(i)$ ed $n_(j)$ hanno un divisore in comune,
e quindi non sono primi, contro l'ipotesi che invece lo siano. Occorre
allora assumere che $"MCD"(N_(i), n_(i)) = 1$.
Si consideri la congruenza lineare $N_(i) y equiv 1 mod
n_(i)$ nell'incognita $y$, che ha $y_(i)$ per soluzione.
Per il @Congruence-solutions-exist, tale congruenza lineare
ha soluzione se vale $"MCD"(N_(i), n_(i)) | 1$, ed é stato
appena mostrato che $"MCD"(N_(i), n_(i)) = 1$, pertanto é
garantito che $y_(i)$ esista. Sia $c$ definito come:
$ c = sum_(i = 1)^(m) N_(i) y_(i) b_(i) =
N_(1) y_(1) b_(1) + ... + N_(m) y_(m) b_(m) $
É possibile verificare che $c$ é una soluzione del sistema, ovvero
che $c equiv b_(j) mod n_(j)$ per $j != i$. Valendo $n_(j) | N_(i)$
per qualsiasi $j != i$, é possibile scrivere $N_(i) equiv 0 mod n_(j)$,
e quindi $c equiv N_(j) y_(j) b_(j) mod n_(j)$. Avendo trovato che vale
$N_(j) n_(j) equiv 1 mod n_(j)$, moltiplicando ambo i membri per $b_(j)$
si ha $N_(j) n_(j) b_(j) equiv b_(j) mod n_(j)$ (questo é legittimo
perché $N_(j) n_(j)$ e $1$ sono primi fra di loro, esiste un lemma
che lo prova).
Avendosi la soluzione $c$, sia $c'$ un'altra soluzione del sistema.
Allora deve valere $c equiv c' mod n_(i)$, ovvero $n_(i) | c − c'$
per ogni i = $1, ..., m$. Poichè gli $n_(i)$ sono a due a due coprimi,
segue che anche $N$ é divisore di $c − c'$, ovvero $c equiv c' mod N$.
Questo dimostra che $c$ è l'unica soluzione del sistema modulo $N$, a
meno di multipli di $N$.
]
#example[
Si consideri il seguente sistema di congruenze lineari:
$ cases(x equiv 2 mod 3, x equiv 3 mod 5, x equiv 2 mod 7) $
Tale sistema rispetta le ipotesi del @Chinese-remainder-theorem,
dato che tutti i termini noti a sinistra dell'equivalenza sono
pari ad $1$, i termini noti a destra sono tutti positivi e sono
tutti coprimi fra di loro a due a due.
Si ha allora $N = 3 dot 5 dot 7 = 105$. Per ciascuna congruenza lineare
del sistema si calcoli $N_(i) = frac(N, n_(i))$:
$ N_(1) = frac(N, n_(1)) = frac(105, 3) = 35 space space space
N_(2) = frac(N, n_(2)) = frac(105, 5) = 21 space space space
N_(3) = frac(N, n_(3)) = frac(105, 7) = 15 $
Da cui si ottengono le congruenze lineari:
#set math.mat(delim: none)
$ mat(
N_(1) y equiv 1 mod n_(1) & =>
35 y equiv 1 mod 3 & => 2
y equiv 1 mod 3 & =>
y_(1) = 2;
N_(2) y equiv 1 mod n_(2) & =>
21 y equiv 1 mod 5 & =>
y equiv 1 mod 5 & =>
y_(2) = 1;
N_(3) y equiv 1 mod n_(3) & =>
15 y equiv 1 mod 7 & =>
y equiv 1 mod 7 & =>
y_(3) = 1
) $
La soluzione del sistema é allora data da:
$ c = sum_(i = 1)^(3) N_(i) y_(i) b_(i) =
35 dot 2 dot 2 + 21 dot 1 dot 3 + 15 dot 1 dot 2 = 233 $
E da tutti gli interi a questo congruenti modulo $105$.
]
|
https://github.com/metamuffin/typst | https://raw.githubusercontent.com/metamuffin/typst/main/tests/typ/visualize/shape-rounded.typ | typst | Apache License 2.0 | // Test rounded rectangles and squares.
---
// Ensure that radius is clamped.
#rect(radius: -20pt)
#square(radius: 30pt)
|
https://github.com/xsro/xsro.github.io | https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/nlct/solution/5.6.typ | typst | #import "common.typ":exercise
#exercise(code:"5.6")[
Verify that $D_+W(t)$ satisfies @5.12(5.12 in textbook) when $V(t,x(t))=0$.
$
D_+ W <= (c_4 L)/(2 sqrt(c_1)) norm(u(t))
$<5.12>
Hint: Using Exercise 3.24, show that $
V(t+h,x(t+h))<=c_4 h^2 L^2 norm(u)^2 \/2 + h o(h)
$ where $o(h)/h arrow 0$ as $h arrow 0$.
Then apply $c_4>=2 c_1$
]
From textbook, the system is
$
dot(x)=f(t,x,u),x(0)=x_0\
y=h(t,x,u)
$
From $V(t,x(t))=0$ and @Vbound, we have $x(t)=0$
Let $V(t,x(t))=0$.
$
D_+W &= lim sup_(h arrow 0^+) 1/h [W(t+h,x(t+h))-W(t,x(t))]\
&= lim sup_(h arrow 0^+) 1/h sqrt(V(t+h,x(t+h)))
$
From @Vbound, We have
$
V(t+h,x(t+h)) <=
c_4/2 norm(x(t+h))^2\
$
From textbook 5.9, we have
$
norm(f(t,x(t),u)-f(t,x(t),0)) <= L norm(u)
$
Use Taylor Series:
$
x(t+h)= f(t,x,u) h + o(h) \
arrow.stroked
norm(x(t+h))^2
<=(norm(f(t,x,u))h+norm(o(h)))^2
$
$
1/h^2 V(t+h,x(t+h))
<= c_4/2 (norm(x(t+h))/h)^2
<= c_4/2 (norm(f(t,x,u))+norm(o(h))/h)^2
$
$
lim sup_(h arrow 0^+) 1/h sqrt(V(t+h,x(t+h)))
<= sqrt(c_4/2) norm(f(t,x,u))
<= sqrt(c_4/2) L norm(u)
$
since $sqrt(c_4\/(2c_1))>=1$. Thus
$
D_+ W <= sqrt(c_4/2) L norm(u) sqrt(c_4\/(2c_1))= (c_4 L)/(2 sqrt(c_1)) norm(u(t))
$
which agrees with the right hand side of @5.12 |
|
https://github.com/alex-touza/fractal-explorer | https://raw.githubusercontent.com/alex-touza/fractal-explorer/main/paper/src/utilities.typ | typst | #import "../meta.typ": PRINT
#let numbered_eq = math.equation.with(
block: true,
numbering: n => {
let h = counter(heading).get().first()
[(#h.#n)]
},
)
#let printable-hyperlink(text, src) = {
if (PRINT) [#text <#link(src)>] else [#underline[#link(src, text)]]
}
#let pritable-doclink(label) = {
let pageref(label) = context {
let loc = locate(label)
let nums = counter(page).at(loc)
link(loc, numbering(loc.page-numbering(), ..nums))
}
ref(label)
if (PRINT) [, pàg. #pageref(label)]
}
#let pageref(label) = context {
let loc = locate(label)
let nums = counter(page).at(loc)
link(loc, numbering(loc.page-numbering(), ..nums))
} |
|
https://github.com/ntjess/toolbox | https://raw.githubusercontent.com/ntjess/toolbox/main/toolbox.typ | typst | #import "./cetz-plus/arrow.typ": arrow
#import "./cetz-plus/git-graph.typ"
#import "./shadow-box.typ": shadow-box
/// Create the SVG element as a string, embedding the video tag within it.
#let video-to-svg(video-path) = {
let ext = video-path.split(".").last()
let svg-template = ```
<svg xmlns="http://www.w3.org/2000/svg">
<foreignObject width="100%" height="100%">
<video xmlns="http://www.w3.org/1999/xhtml" width="100%" height="100%" controls="" >
<source src="{video-path}" type="video/{ext}" />
</video>
</foreignObject>
</svg>
```.text
svg-template.replace("{video-path}", video-path).replace(
"{ext}", ext
)
}
|
|
https://github.com/binhtran432k/ungrammar-docs | https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/main.typ | typst | #import "components/glossary.typ": print_glossary, gls
#import "components/format.typ": project, appendix
#import "glossaries.typ": GLOSSARIES
#set raw(syntaxes: "/gherkin.sublime-syntax")
#let m = yaml("metadata.yml")
#show: project.with(
logo: image("components/logo.svg", width: 26%),
doc_type: m.doc_type,
department: m.department,
cover_head: m.cover_head,
major: m.major,
subject: m.subject,
supervisors: m.supervisors,
committee: m.committee,
secretary: m.secretary,
reviewer: m.reviewer,
title: m.title,
author: m.students.map(student => student.at("name")),
students: m.students,
declaration: include "contents/declaration.typ",
acknowledgments: include "contents/acknowledgments.typ",
glossaries: GLOSSARIES,
)
#include "contents/introduction.typ"
#pagebreak(weak: true)
#include "contents/literature-review/index.typ"
#pagebreak(weak: true)
#include "contents/requirements-analysis/index.typ"
#pagebreak(weak: true)
#include "contents/system-design/index.typ"
#pagebreak(weak: true)
#include "contents/system-implementation/index.typ"
#pagebreak(weak: true)
#include "contents/evaluation/index.typ"
#pagebreak(weak: true)
#include "contents/conclusions/index.typ"
#pagebreak(weak: true)
#show: appendix
#include "contents/appendix/documentation.typ"
#pagebreak(weak: true)
#bibliography("references.bib")
|
|
https://github.com/freundTech/typst-typearea | https://raw.githubusercontent.com/freundTech/typst-typearea/main/tests/header.query.typ | typst | MIT License | #import "../typearea.typ": *
#show: typearea.with(
width: 100pt,
height: 100pt,
div: 5,
header-include: false,
header-height: 10pt,
header-sep: 5pt,
header: context [
#layout(size => [
#metadata(here().position() + size + (align: align.alignment))<result>
])
]
)
#metadata((
page: 1,
x: 20pt,
y: 15pt, // Because the header is align(bottom) our y position includes the height of the header
width: 40pt,
height: 10pt,
align: start + bottom,
))<expected>
|
https://github.com/sora0116/unix_seminar | https://raw.githubusercontent.com/sora0116/unix_seminar/master/handout/main.typ | typst | #set page(numbering: "1")
#set heading(numbering: "1.1")
#set text(size: 12pt, font: ("New Computer Modern", "<NAME>"))
#[
#align(center + horizon)[
#text(2em)[第10回Unixゼミ\ Cプログラム(デバッグ編)]
#text(1.3em)[高木 空]
#datetime(year: 2024, month: 7, day: 1).display("[year]年[month]月[day]日")
]
#pagebreak()
]
#outline(title: "目次", indent: 1em)
#pagebreak()
#include "./gdb/main.typ"
#include "./lldb/main.typ"
#include "./perf/main.typ"
|
|
https://github.com/OJII3/tuat-typst | https://raw.githubusercontent.com/OJII3/tuat-typst/main/lib.typ | typst | #let tuatTemplate(
title: "実験報告書", // タイトル(上部)
date1: "", // 日付1
date2: "", // 日付2
date3: "", // 日付3
date4: "", // 日付4
date5: "", // 日付5
collaborator1: "", // 共同作業者1
collaborator2: "", // 共同作業者2
collaborator3: "", // 共同作業者3
collaborator4: "", // 共同作業者4
collaborator5: "", // 共同作業者5
submitDate: "", // 提出日
resubmitDate: "", // 再提出日
deadline: "", // 期限日
redeadline: "", // 再提出期限日
subject: "", // 科目名
teacher: "", // テーマ指導教員
grade: "", // 学年
semester: "", // 学期
credit: "", // 単位
theme: "", // テーマ
studentId: "", // 学籍番号
author: "", // 名前
doc,
) = {
let rows = {
let n = 0
while n < 18 {
n += 1
(36pt,)
}
}
let columns = (32pt, 3fr, 3fr, 1fr, 1fr, 1fr)
let pattern1(col1) = (
table.cell(colspan: 3, [#col1]),
table.cell(colspan: 3, []),
)
let pattern2(col1, col2) = (
table.cell(colspan: 3, [#col1]),
table.cell(colspan: 3, [#col2]),
)
let pattern3(col1, col2, col3) = (
[#col1],
[#col2],
[#col3],
table.cell(colspan: 3, []),
)
let pattern4(col1, col2, col3) = (
table.cell(colspan: 2, [#col1]),
[#col2],
table.cell(colspan: 3, [#col3]),
)
let pattern5(col1, col2, col3, col4, col5) = (
table.cell(colspan: 2, [#col1]),
[#col2],
[#col3],
[#col4],
[#col5],
)
let table_header = table.header(..pattern2([*実験演習記録*], [*判定・指示*]))
align((center + horizon), heading(numbering: none, title))
align(
horizon,
table(
rows: rows,
columns: columns,
align: (center + horizon),
stroke: (x: 1pt, y: 1pt),
..(
for i in (2, 7, 8, 9) {
(
table.hline(y: i, start: 0, end: 6, stroke: 1pt),
table.hline(y: i, start: 3, end: 6, stroke: none),
)
}
),
..(
for i in (3, 4, 5, 6) {
(
table.hline(y: i, start: 0, end: 2, stroke: (dash: "dashed")),
table.hline(y: i, start: 3, end: 6, stroke: none),
)
}
),
..(
for i in (10, 11, 12, 13) {
(
table.hline(y: i, start: 0, end: 3, stroke: (dash: "dashed")),
table.hline(y: i, start: 3, end: 6, stroke: none),
)
}
),
table_header,
..pattern3([], [年月日時], [共同作業者]),
..pattern3(1, [#date1], [#collaborator1]),
..pattern3(2, [#date2], [#collaborator2]),
..pattern3(3, [#date3], [#collaborator3]),
..pattern3(4, [#date4], [#collaborator4]),
..pattern3([], [#date5], [#collaborator5]),
..pattern1([*レポート提出記録*]),
..pattern3([], [提出年月日], [期限年月日]),
..pattern3([初], [#submitDate], [#deadline]),
..pattern3([再], [#resubmitDate], [#redeadline]),
..pattern3([], [], []),
..pattern3([], [], []),
..pattern3([], [], []),
..pattern5([*科目名*], [*テーマ指導教員*], [*学年*], [*学期*], [*単位*]),
..pattern5([#subject], [#teacher], [#grade], [#semester], [#credit]),
..pattern4([*テーマ番号・テーマ名*], [*学籍番号*], [*名前*]),
..pattern4([#theme], [#studentId], [#author]),
),
)
align((center + horizon), [東京農工大学 工学部 知能情報システム工学科])
doc
}
|
|
https://github.com/TechnoElf/mqt-qcec-diff-presentation | https://raw.githubusercontent.com/TechnoElf/mqt-qcec-diff-presentation/main/content/results.typ | typst | #import "@preview/cetz:0.2.2": canvas, plot, chart, styles, draw, palette
#import "@preview/tablex:0.0.8": tablex
#import "@preview/unify:0.6.0": qty
#import "../template/conf.typ": slide
#import "data.typ": *
#slide(title: "")[
#box(width: 100%, height: 80%, align(center + horizon)[
#text(size: 60pt)[*Results*]
])
]
#slide(title: "Results")[
#set text(size: 12pt)
#figure(
canvas({
draw.set-style(
axes: (bottom: (tick: (
label: (angle: 45deg, anchor: "east"),
)))
)
chart.columnchart(
mode: "clustered",
label-key: 0,
value-key: range(1, 7),
size: (20, 8),
x-label: [Run Time (s)],
x-tick: 45,
y-label: [Count],
y-max: 40,
y-min: 0,
legend: "legend.inner-north-east",
labels: ([Proportional], [Myers' Diff (Reversed, Processed)], [Myers' Diff (Processed)], [Myers' Diff (Reversed)], [Myers' Diff], [Patience Diff]),
bar-style: i => { if i >= 1 { palette.red(i) } else { palette.cyan(i) } },
results-r1-b5q16-hist.bins-mu.zip(
results-r1-b5q16-hist.cprop.mu,
results-r1-b5q16-hist.cmyersrev-pmismc.mu,
results-r1-b5q16-hist.cmyers-pmismc.mu,
results-r1-b5q16-hist.cmyersrev-p.mu,
results-r1-b5q16-hist.cmyers-p.mu,
results-r1-b5q16-hist.cpatience-p.mu
)
)
}),
caption: [
Benchmark instances sorted into bins based on their run time.
The size of the bins increases exponentially to better reflect the distribution of the results.
The benchmark runs that did not finish within the time limit are excluded from these results.
]
)
]
#slide(title: "Results")[
#set text(size: 14pt)
#figure(
canvas({
draw.set-style(
axes: (bottom: (tick: (
label: (angle: 45deg, anchor: "east"),
)))
)
chart.columnchart(
size: (20, 9),
x-ticks: (),
y-label: [Run Time Improvement (%)],
y-max: 100,
y-min: -100,
sort-by-circuit-size(unclip(results-r1-b5q16)).map(r =>
([#r.name], calc.max(-(r.cmyers-pmismc.mu / r.cprop.mu * 100 - 100), -100))
)
)
}),
caption: [
The run time improvement of the application scheme based on the processed Myers' algorithm relative to the proportional application scheme for each benchmark instance.
]
)
]
#slide(title: "Results")[
#set text(size: 14pt)
#figure(
canvas({
plot.plot(
size: (20, 8),
x-label: [Absolute Circuit Size Difference (gates)],
y-label: [Run Time Improvement (%)],
y-max: 100,
y-min: -100,
legend: "legend.inner-north-east",
{
plot.add-hline(style: (stroke: black), 0)
plot.add(
mark: "triangle",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff],
unclip(results-r1-b5q16).map(r =>
(r.circuit-size-difference, calc.max(-(r.cmyers-p.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "square",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff (Processed)],
unclip(results-r1-b5q16).map(r =>
(r.circuit-size-difference, calc.max(-(r.cmyers-pmismc.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "o",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff (Reversed)],
unclip(results-r1-b5q16).map(r =>
(r.circuit-size-difference, calc.max(-(r.cmyersrev-p.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "x",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff (Reversed, Processed)],
unclip(results-r1-b5q16).map(r =>
(r.circuit-size-difference, calc.max(-(r.cmyersrev-pmismc.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "+",
mark-style: (fill: none),
style: (stroke: none),
label: [Patience],
unclip(results-r1-b5q16).map(r =>
(r.circuit-size-difference, calc.max(-(r.cpatience-p.mu / r.cprop.mu * 100 - 100), -100))
)
)
}
)
}),
caption: [The run time improvement dependent on the circuit size difference for each diff algorithm.]
)
]
#slide(title: "Results")[
#set text(size: 14pt)
#figure(
canvas({
plot.plot(
size: (20, 8),
x-label: [Total Circuit Size (gates)],
y-label: [Run Time Improvement (%)],
y-max: 100,
y-min: -100,
legend: "legend.inner-north-east",
{
plot.add-hline(style: (stroke: black), 0)
plot.add(
mark: "triangle",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff],
unclip(results-r1-b5q16).map(r =>
(r.total-circuit-size, calc.max(-(r.cmyers-p.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "square",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff (Processed)],
unclip(results-r1-b5q16).map(r =>
(r.total-circuit-size, calc.max(-(r.cmyers-pmismc.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "o",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff (Reversed)],
unclip(results-r1-b5q16).map(r =>
(r.total-circuit-size, calc.max(-(r.cmyersrev-p.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "x",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff (Reversed, Processed)],
unclip(results-r1-b5q16).map(r =>
(r.total-circuit-size, calc.max(-(r.cmyersrev-pmismc.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "+",
mark-style: (fill: none),
style: (stroke: none),
label: [Patience],
unclip(results-r1-b5q16).map(r =>
(r.total-circuit-size, calc.max(-(r.cpatience-p.mu / r.cprop.mu * 100 - 100), -100))
)
)
}
)
}),
caption: [The run time improvement dependent on the total circuit size for each diff algorithm.]
)
]
#slide(title: "Results")[
#set text(size: 14pt)
#figure(
canvas({
plot.plot(
size: (20, 8),
x-label: [Equivalence Rate],
y-label: [Run Time Improvement (%)],
y-max: 100,
y-min: -100,
legend: "legend.inner-north-east",
{
plot.add-hline(style: (stroke: black), 0)
plot.add(
mark: "triangle",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff],
unclip(results-r1-b5q16).map(r =>
(r.equivalence-rate, calc.max(-(r.cmyers-p.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "square",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff (Processed)],
unclip(results-r1-b5q16).map(r =>
(r.equivalence-rate, calc.max(-(r.cmyers-pmismc.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "o",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff (Reversed)],
unclip(results-r1-b5q16).map(r =>
(r.equivalence-rate, calc.max(-(r.cmyersrev-p.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "x",
mark-style: (fill: none),
style: (stroke: none),
label: [Myers' Diff (Reversed, Processed)],
unclip(results-r1-b5q16).map(r =>
(r.equivalence-rate, calc.max(-(r.cmyersrev-pmismc.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add(
mark: "+",
mark-style: (fill: none),
style: (stroke: none),
label: [Patience],
unclip(results-r1-b5q16).map(r =>
(r.equivalence-rate, calc.max(-(r.cpatience-p.mu / r.cprop.mu * 100 - 100), -100))
)
)
}
)
}),
caption: [The run time improvement dependent on the circuit equivalence rate for each diff algorithm.]
)
]
#slide(title: "Results")[
#set text(size: 14pt)
#figure(
canvas({
plot.plot(
size: (20, 8),
x-label: [Equivalence Rate],
y-label: [Run Time Improvement (%)],
y-max: 100,
y-min: -100,
legend: "legend.inner-north-east",
{
plot.add-hline(style: (stroke: black), 0)
plot.add(
mark: "square",
mark-style: (stroke: green, fill: none),
style: (stroke: none),
label: [Myers' Diff (Processed)],
unclip(results-r1-b5q16).map(r =>
(r.equivalence-rate, calc.max(-(r.cmyers-pmismc.mu / r.cprop.mu * 100 - 100), -100))
)
)
plot.add-vline(style: (stroke: red), 0.35)
}
)
}),
caption: [The run time improvement dependent on the circuit equivalence rate for each diff algorithm.]
)
]
#slide(title: "Results")[
#set text(size: 14pt)
#figure(
canvas({
draw.set-style(
axes: (bottom: (tick: (
label: (angle: 45deg, anchor: "east"),
)))
)
chart.columnchart(
size: (20, 9),
x-ticks: (),
y-label: [Run Time Improvement (%)],
y-max: 100,
y-min: -100,
filter(sort-by-circuit-size(unclip(results-r1-b5q16))).map(r =>
([#r.name], calc.max(-(r.cmyers-pmismc.mu / r.cprop.mu * 100 - 100), -100))
)
)
}),
caption: [
The run time improvement of the application scheme based on the processed Myers' algorithm relative to the proportional application scheme for each benchmark instance.
The benchmark instances are filtered so the application scheme is only used for those where the circuits are more than 40% equivalent.
]
)
]
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/foundations/eval.typ | typst | --- eval ---
// Test the eval function.
#test(eval("1 + 2"), 3)
#test(eval("1 + x", scope: (x: 3)), 4)
#test(eval("let x = x + 1; x + 1", scope: (x: 1)), 3)
--- eval-mode ---
// Test evaluation in other modes.
#eval("[_Hello" + " World!_]") \
#eval("_Hello" + " World!_", mode: "markup") \
#eval("RR_1^NN", mode: "math", scope: (RR: math.NN, NN: math.RR))
--- eval-syntax-error-1 ---
// Error: 7-12 expected pattern
#eval("let")
--- eval-in-show-rule ---
#show raw: it => text(font: "PT Sans", eval("[" + it.text + "]"))
Interacting
```
#set text(blue)
Blue #move(dy: -0.15em)[🌊]
```
--- eval-runtime-error ---
// Error: 7-17 cannot continue outside of loop
#eval("continue")
--- eval-syntax-error-2 ---
// Error: 7-12 expected semicolon or line break
#eval("1 2")
--- eval-path-resolve ---
// Test absolute path.
#eval("image(\"/assets/images/tiger.jpg\", width: 50%)")
--- eval-path-resolve-in-show-rule ---
#show raw: it => eval(it.text, mode: "markup")
```
#show emph: image("/assets/images/tiger.jpg", width: 50%)
_Tiger!_
```
--- eval-path-resolve-relative ---
// Test relative path.
#test(eval(`"HELLO" in read("./eval.typ")`.text), true)
--- issue-2055-math-eval ---
// Evaluating a math expr should renders the same as an equation
#eval(mode: "math", "f(a) = cases(a + b\, space space x >= 3,a + b\, space space x = 5)")
$f(a) = cases(a + b\, space space x >= 3,a + b\, space space x = 5)$
|
|
https://github.com/Tiggax/zakljucna_naloga | https://raw.githubusercontent.com/Tiggax/zakljucna_naloga/main/src/figures/monod.typ | typst | #import "../additional.typ": todo
#import "@preview/cetz:0.2.2": canvas, plot, draw, vector
#let example = canvas(
length: 1cm,
{
plot.plot(
size: (12,8),
axes: ($S$,$mu(S)$),
legend: "legend.inner-south-east",
x-label: $S$,
y-label: $mu(S)$,
y-max: 1,
{
for k in (0.1,0.5,1.0,1.5) {
plot.add(
domain: (0,10),
samples: 1000,
label: $K_S = #k$,
x => (x / (k + x))
)
}
}
)
}
)
#let function(k: 1, mu_max: 1) = canvas(
length: 1cm,
plot.plot(
size: (12,8),
y-max: 1.2,
x-min: 0,
x-label: $S$,
x-tick-step: none,
y-label: $mu(S)$,
y-tick-step: none,
{
plot.add(
domain: (0,4),
samples: 100,
x => (x / (k + x))
)
//plot.add-vline(k, style: (stroke: (dash: "dashed", paint: blue)))
plot.add-hline(mu_max, style: (stroke: (dash: "dashed", paint: red)))
plot.annotate({
import draw: *
line((0,mu_max/2), (k,mu_max/2), stroke: (dash: "dashed"), name: "fn")
line((k,mu_max/2), (k,0), stroke: (dash: "dashed", paint: green), name: "ks")
content((2, mu_max + 0.05), text(fill: red)[$mu_"max"$])
content((v => vector.add(v, (0,0.05)), "fn.mid"),text(size: 0.8em, fill: black)[$mu(K_S) = mu_"max" / 2$])
content((v => vector.add(v, (0.2,)), "ks.mid"),text(fill: green)[$K_S$])
})
}
)
) |
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/molebeny/molebenKJozefovi.typ | typst | #import "/style.typ": *
#import "/styleMoleben.typ": *
= Moleben k sv. Jozefovi
#align(horizon + center)[#primText[
#text(50pt)[Moleben k\
svätému\
Jozefovi]
]]
#let values = (
"tropar1": (6, none, "Všetci anjeli a svätí na nebesiach – s obdivom vychvaľujú tvoju vznešenosť, – Jozef, Bohom vyvolený ženích. – My na zemi máme v tebe mocného ochrancu. – Preto s dôverou sa k tebe utiekame – a pokorne voláme: – „Zachráň nás od úkladov diablových, – najmocnejší ochranca <NAME>!“"),
"tropar2": (4, none, "Útekom cez púšť do Egypta – s najčistejšou svojou snúbenicou – zachránil si Ježiša pred mečom Herodesovým, – chráň aj nás na púšti tohto života, – kde nás satan prenasleduje, – zbav nás jeho úkladov i večnej záhuby."),
"velebenie": ("Velebíme ťa, – všetkými oslavovaný – Ženích nepoškvrnenej Panny, – najvyšší ochranca <NAME>", (
"Spravodlivý sťa palma zakvitne – a vyrastie sťa céder z Libanonu.",
"Jeho blesky ožarujú zemekruh – a jeho slávu vidia všetky národy.",
"U ustanovil ho za Pána svojho domu – a za správcu všetkého svojho majetku,",
"Slávou a cťou – si ho ovenčil.",
"Sláva: I teraz: Aleluja, aleluja, aleluja, sláva tebe, Bože."
)),
"prokimen": (4, "Spravodlivý sa teší v Pánovi – a spolieha sa na neho.", "Počuj, Bože, môj hlasitý nárek, keď volám k tebe."),
"evanjelium": ("Mt", "Keď mudrci odišli, Jozefovi sa vo sne zjavil Pánov anjel a povedal: „Vstaň, vezmi so sebou dieťa i jeho matku, ujdi do Egypta a zostaň tam, kým ti nedám vedieť, lebo Herodes bude hľadať dieťa, aby ho zmárnil.“ On vstal, vzal za noci dieťa i jeho matku a odišiel do Egypta. Tam zostal až do Herodesovej smrti, aby sa splnilo, čo povedal Pán skrze proroka: „Z Egypta som povolal svojho syna.“ Keď Herodes zbadal, že ho oklamali, veľmi sa rozhneval a dal povraždiť v Betleheme a na jeho okolí všetkých chlapcov od dvoch rokov nadol podľa času, ktorý zvedel od mudrcov. Vtedy sa splnilo, čo povedal prorok Jeremiáš: „V Ráme bolo počuť hlas, plač, nárek a veľké kvílenie: Ráchel oplakáva svoje deti a odmieta útechu, lebo ich niet.“ Po Herodesovej smrti sa Pánov anjel zjavil vo sne Jozefovi v Egypte a povedal mu: „Vstaň, vezmi dieťa i jeho matku a chod’ do izraelskej krajiny. Tí, čo striehli na život dieťaťa už pomreli.“ On vstal, vzal dieťa i jeho matku a prišiel do izraelskej krajiny. Ale keď sa dopočul, že v Júdei kraľuje Archelaos namiesto svojho otca Herodesa, bál sa ta ísť. Varovaný vo sne, odobral sa do Galilejského kraja. Keď ta prišiel, usadil sa v meste, ktoré sa volá Nazaret, aby sa splnilo, čo predpovedali proroci: „Budú ho volať Nazaretský.“"),
"verse": (none, none),
"stichiry": (
(8, "O preslavno čudese", "Ó, preslávny ženích, Jozef, – aký blažený bol tvoj život s prečistou Bohorodičkou! – S ňou si sa delil o všetky radosti. – S ňou si prežíval všetky strasti. – Všetky myšlienky i tajomstvá ste mali spoločné. – Vo vašej rodine najväčšia láska prekvitala. – U vás prebýval pokoj a šťastie. – tridsať rokov ste spolu žili. – Tridsať rokov ste sa spolu starali o Syna Božieho, – odmeňovaní jeho milosťami."),
("Blažený je muž dobrej ženy. Dvojnásobný je počet jeho dní."),
(none, none, "Aké to prúdy nebeských milostí – vlievali sa do tvojej požehnanej duše, – keď si počúval slová nepoškvrnenej Panny? – S najväčšou úctou si prijímal jej rady, jej útechy a povzbudenia. – Ty si bol svedkom a účastníkom jej vrúcnych modlitieb. – Spolu s ňou si prenikal do večných tajomstiev."),
("Dobrá žena je radosťou svojho muža a jeho roky naplňuje pokojom."),
(none, none, "Jozef, ochranca svä<NAME>, – dostal si nesmierne milosti a dary <NAME>. – Boh ťa obdaril veľkou múdrosťou. – Tvoja duša sa skvela nádherou panickej čistoty. – Dojemná bola hĺbka tvojej pokory. – Plamene tvojej vrúcnej lásky prenikli nebesá. – Aj nám svojimi vrúcnymi modlitbami – vypros tieto veľké dary."),
(4, none, "Jozef, ženích nad všetkých vyznamenaný – tvoju požehnanú dušu stále naplňovali radosti i strasti. – Ale v radostiach si sa nevyvyšoval – a v trápeniach si neklesal. – Vo všetkom si bol vyrovnaný, – do vôle Božej oddaný. – Aj nám vypros milosti, – aby sme ťa nasledovali.")
),
"modlitba": "K tebe, svätý Jozef, vo svojom súžení sa utiekame. Vyprosili sme si pomoc tvojej Nevesty a aj teba dôverne o ochranu žiadame. Pre lásku, ktorá ťa spájala s prečistou Pannou a Bohorodičkou, a pre otcovskú lásku, s ktorou si objímal božské Dieťa, vrúcne ťa prosíme, pozri na dedičstvo, ktoré Ježiš Kristus získal svojou predrahou Krvou. Príď nám na pomoc svojím mocným príhovorom a pomáhaj nám vo všetkých našich potrebách.
Starostlivý Ochranca Svätej rodiny, bedli nad vyvoleným dedičstvom Ježiša Krista. Najláskavejší Otče, odvráť od nás všetku nákazu bludu a nemravnosti. Pomáhaj nám z neba, náš najmocnejší Dobrodinec, aby sme premohli sily temnosti. A ako si kedysi vyslobodil Ježiša z najväčšieho nebezpečenstva života, tak teraz obhajuj svätú Cirkev pred všetkými protivenstvami a nás všetkých prijmi pod svoju ochranu, aby sme podľa tvojho príkladu a s tvojou pomocou viedli svätý život, nábožne zomreli a dosiahli večnú blaženosť v nebi.",
"ektenia": (
"Zmiluj sa, Bože, nad nami pre svoje veľké milosrdenstvo, prosíme ťa, vypočuj nás a zmiluj sa.",
"Prosme, aby naše mesto (alebo obec) i ostatné mestá, obce a celá krajina boli uchránené od hladu, pohrôm, zemetrasenia, povodní, krupobitia, ohňa, meča, vpádu nepriateľa. Nech dobrý a láskyplný Boh vypočuje naše prosby a odvráti od nás svoj spravodlivý hnev a zmiluje sa nad nami.",
"Prosme, aby naše mesto (alebo obec) i ostatné mestá, obce a celá krajina boli uchránené od hladu, pohrôm, zemetrasenia, povodní, krupobitia, ohňa, meča, vpádu nepriateľa. Nech dobrý a láskyplný Boh vypočuje naše prosby a odvráti od nás svoj spravodlivý hnev a zmiluje sa nad nami.",
"Milosťou, štedrosťou a láskou tvojho jednorodeného Syna, s ktorým si velebený spolu s tvojím presvätým, dobrým a životodarným Duchom teraz i vždycky i na veky vekov."
)
)
#pagebreak()
#nacaloPoOtcenas
#tropar(..values.at("tropar1"))
#sit(..values.at("tropar2"))
#if values.at("velebenie") != none [#velebenie(..values.at("velebenie"))]
#note[Ľud sa postaví.]
#K[Vnímajme! Pokoj všetkým! Premúdrosť, vnímajme!]
#prokimen(..values.at("prokimen"))
#chvaly()
#evanjelium(..values.at("evanjelium"))
#verse(..values.at("verse"))
#stichiry(values.at("stichiry"))
#modlitba(values.at("modlitba"))
#ektenia(values.at("ektenia"))
#prepustenie |
|
https://github.com/HarryLuoo/sp24 | https://raw.githubusercontent.com/HarryLuoo/sp24/main/math321/hw13.typ | typst | #set math.equation(numbering:"1")
#set page(margin: (x: 1cm, y: 1cm), columns: 1, flipped: false)
= HW 13 <NAME>
== 1
recall cauchy integral formula $
f(z_0) = 1/(2 pi i) integral_(C) f(z)/(z-z_0) dif z $
For our integral, $f(z) = z^3 + e^(z^2), z_0 = 1+i$
applying the CIF:
$
integral_(C) (z^3+ e^(z^2))/(z-(1+i)) dif z = 2pi i f(1+i) &= 2pi i ((1+i)^3 + e^((1+i)^2)) \
& = 2 pi i (e^(2i)+ 2i - 2 )
$
== 2
recall the CIF $
f^(n) (z_0) = (n!)/(2 pi i) integral_(C) (f(z))/((z-z_0)^(n+1)) dif z
$
Here, $z_0 =0, n = 1, quad "let" f(z) = e^(z)+e^(z^3) $
$
integral_(C) (f(z))/(z^2) dif z &= (2 pi i )/(1) f^((1)) (0) \
& = 2 pi i (e^(0) + 3(0)^2 e^(0)) =
#rect(inset: 8pt)[
$ display( 2 pi i)$
]
$
== 3
Using the CIF, take $z_0 = -1, n=2, f(z) = z^2024 + 4z$
$
integral_(C) (f(z))/((z+1)^3) dif z &= (2 pi i )/(2) f^((2)) (-1) \
$ <eq.5>
where $f^((2))(-1) = 2024*2023 (-1) ^ 2022 = 4094552$ , @eq.5 becomes $
integral_(C) (z^2024 + 4z)/((z+1)^3) dif z &=
#rect(inset: 8pt)[
$ display( 4094552 pi i )$
]
$
== 4
Using the CIF, take $f(z) = cos (z), z_0=0$
$
integral_(|z|=3) (cos(z))/(z^5) dif z &=2pi i cos^((4)) (0) \
& = 2 pi i cos(0)/4! =
#rect(inset: 8pt)[
$ display( (pi i)/12 )$
]
$
== 5
- (a)find poles
$
1+z^2 = (z+i)(z-i) => z_1 = -i, z_2 = i\
"Res"(f,z_1) = lim_(z -> -i) (z+i)/(1+z^2) = -1/(2i) \
"Res"(f,z_2) = lim_(z -> i) (z-i)/(1+z^2) = 1/(2i)
$
- (b)
Consider subsitution $f(z) = ( 1)/(1+x^2)$ , we can use a semicircular contour in the upper half-plane, which will enclose only the pole at z = i.
$
integral_(gamma) f(z) dif z &= integral_(-R)^(R) f(z) dif z + integral_(C) f(z) dif z = 2pi i "Res"(f,z=i) + underbrace(integral_(C) f(z) dif z,(*)) $
for the second term, parametrize $z = R e^(i theta)$ , $ (*) = integral_(C) (1)/(1+R e^(i 2theta)) dif theta,quad theta in [0,pi] $
as $R-> infinity$, the second term becomes 0, and the integral becomes $
integral_(-infinity)^(infinity) f(z) dif z &= 2 pi i "Res"(f,z=i) \
& = 2 pi i (1/(2i)) = pi $
Since $ (1)/(1+x^2)$ is even, $
#rect(inset: 8pt)[
$ display( integral_(0)^(infinity) (1)/(1+x^2) dif x = pi/2 )$
]
$
== 6
- (a)
Find all the poles $
(1+z^2)^2 &=0 \
z^2 &= -1 \
z &= plus.minus i
$
Recall that we can find the residue by$
"Res"(f,z_0) = lim_(z -> z_0)(1)/(n-1)! (d/(d z))^(n-1) [(z-z_0)^(n) f(z)]
$
Take $n = 2, z_0 = i$, we have $
"Res"(f,i)= lim_(z -> i) (dif )/(dif z)[(z-i)^2 f(z)] &= lim_(z -> i) (dif )/(dif z)[(z-i)^2/((z - i)^2 (z+i)^2)] \
& = lim_(z -> i) (dif )/(dif z)[1/((z+i)^2)] \
& = lim_(z -> i) -2/(z+i)^3 \
&#rect(inset: 8pt)[
$ display( = -i/4 )$
]
$
similarly, take $n = 2, z_0 = -i$, we have $
"Res"(f,-i) = lim_(z -> -i) (dif)/(dif z) [(z-z_0)^2/(z^2-i^2)^2] &= lim_(z -> -i) (dif)/(dif z) [(z+i)^2/((z+i)^2 (z-i)^2)] \
& = lim_(z -> -i) (dif)/(dif z) [(z-i)^(-2)] \
& = lim_(z -> -i) (-2(z-i)^(-3)) \
&#rect(inset: 8pt)[
$ display( & = i/4)$
]
$
- (b)
recall Cauchy residue thm, $ integral_(gamma) f(z) dif z = 2 pi i sum_(k=1)^(n) "Res"(f,z_k)
$
Consider subsitution $f(z) = ( 1)/((1+z^2)^2)$ , we can use a semicircular contour in the upper half-plane, which will enclose only the pole at z = i.#image("assets/2024-04-30-23-11-37.png", width: 30%)
$
integral_(gamma) f(z) dif z &= integral_(-R)^(R) f(z) dif z + integral_(C) f(z) dif z = 2pi i "Res"(f,z=i) $
$
=> integral_(-R)^(R) f(z) dif z &= 2pi i "Res"(f,z=i) - integral_(C) f(z) dif z \
& = 2 pi i (-i/4) - underbrace(integral_(C) f(z) dif z,(*)) \
$ <eq.7>
for $(*)$ , parametrize $z = R e^(i theta)$ , $ (*) = integral_(C) (1)/(1+R e^(i theta)) dif theta,quad theta in [0,pi] $
When $R-> infinity$, @eq.7 becomes $
integral_(-infinity)^(infinity) f(z) dif z &= 2 pi i (-i/4) - underbrace(integral_(C) (1)/(1+R e^(i theta)) dif theta, --> 0) \
& = pi/2 $
Since $ (1)/(1+x^2)^2$ is even, $
integral_(0)^(infinity) (1)/(1+x^2)^2 dif x =
#rect(inset: 8pt)[
$ display( pi/4)$
]
$
== 7
$
f(z) = (z^2)/((z^2+1)(z^2+4))
$
- (a)
$ (z^2)/((z+i)(z-i)(z+2i)(z-2i)) => z_1 = i, z_2 = -i, z_3 = 2i, z_4 = -2i \
"Res"(f,z_1) = lim_(z->i ) (z^2)/((z+i)(z+2i)(z-2i)) = -1/(6i)\
"Res"(f,z_2) = lim_(z->-i ) (z^2)/((z-i)(z+2i)(z-2i)) = 1/(6i)\
"Res"(f,z_3) = lim_(z->2i ) (z^2)/((z-i)(z+i)(z+2i)) = 1/(3i)\
"Res"(f,z_4) = lim_(z->-2i ) (z^2)/((z-i)(z+i)(z-2i)) = -1/(3i)
$
- (b)
Similarly to 6(b), we can use a semicircular contour in the upper half-plane, which will enclose only the poles at z = i, 2i. The contour integration over the complex arc is still 0 as $R-> infinity$
$
integral_(gamma) f(z) dif z &= integral_(-R)^(R) f(z) dif z + integral_(C) f(z) dif z \ => integral_(-infinity)^(infinity) f(z) dif z &= 2pi i ( "Res"(f,z_1) + "Res"(f,z_3)) =
pi/3\
$
Since $f(x)$ is even, $
integral_(0)^(R) f(x) dif x = 1/2 integral_(-infinity)^(infinity) f(x) dif x =
#rect(inset: 8pt)[
$ display( pi/6)$
]
$
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/modern-technique-report/0.1.0/README.md | markdown | Apache License 2.0 | = Modern Technique Report
A template support modern technique report in Typst.
= Usage
```typst
#import "@preview/modern-technique-report:0.1.0": *
#show: modern-technique-report.with(
title: [Project Name \ Multiline When too Long],
subtitle: [
*Fourth Edition*, \ by _<NAME>_ and _<NAME>_
],
series: [Mathematics Courses \ Framework Series],
author: grid(
align: left + horizon,
columns: 3,
inset: 7pt,
[*Member*], [<NAME>], [<EMAIL>],
[], [<NAME>], [<EMAIL>],
[], [<NAME>], [<EMAIL>],
[*Advisor*], [<NAME>], [<EMAIL>],
),
date: datetime.today().display("[year] -- [month] -- [day]"),
background: image("bg.jpg"),
theme_color: rgb(21, 74, 135),
font: "New Computer Modern",
title_font: "Noto Sans",
)
```
Then a cover page and a content page will be automatically generated. Template also manipulates the style of headings and some contents.
|
https://github.com/heloineto/utfpr-tcc-template | https://raw.githubusercontent.com/heloineto/utfpr-tcc-template/main/main.typ | typst | #import "template/template.typ": *
#show: project.with(
institution: "UNIVERSIDADE TECNOLÓGICA FEDERAL DO PARANÁ",
authors: (
"NO<NAME> E POR EXTENSO DO(A) AUTOR(A)",
),
title: "O TÍTULO DEVE SER CLARO E PRECISO: SUBTÍTULO (SE HOUVER) DEVE SER PRECEDIDO DE DOIS PONTOS CONFIRMANDO SUA VINCULAÇÃO AO TÍTULO",
english-title: "Put your english title here",
city: "CIDADE",
year: "ANO DA ENTREGA",
advisor: "Orientador(a): Nome completo e por extenso.",
approval-date: datetime(day: 19, month: 9, year: 2023),
approvers: (
(
name: "Nome completo e por extenso do Membro 1 (de acordo com o Currículo Lattes)",
degree: "Titulação (Especialização, Mestrado, Doutorado)",
institution: "Nome completo e por extenso da instituição a qual possui vínculo",
),
(
name: "Nome completo e por extenso do Membro 2 (de acordo com o Currículo Lattes)",
degree: "Titulação (Especialização, Mestrado, Doutorado)",
institution: "Nome completo e por extenso da instituição a qual possui vínculo",
),
(
name: "Nome completo e por extenso do Membro 3 (de acordo com o Currículo Lattes)",
degree: "Titulação (Especialização, Mestrado, Doutorado)",
institution: "Nome completo e por extenso da instituição a qual possui vínculo",
),
),
keywords: (
"ferramenta",
"trabalhos acadêmicos",
"formatação",
"editor de documentos",
"desenvolvimento web",
),
goal: [
Trabalho de conclusão de curso de graduação/Dissertação/Tese apresentada como requisito para obtenção do título de Bacharel/Licenciado/Tecnólogo/Mestre/Doutor em Nome do Curso/Programa da Universidade Tecnológica Federal do Paraná (UTFPR).
],
abstract: [
Um dos desafios enfrentados pelos pesquisadores é a formatação de trabalhos acadêmicos, o que consome uma quantidade significativa de tempo e recursos (KHAN, 2018). A não conformidade com as diretrizes de formatação estabelecidas pelas instituições e revistas científicas pode resultar na rejeição dos trabalhos submetidos (ALI, 2010). Com o objetivo de solucionar esse problema, este trabalho propõe o desenvolvimento de um sistema que auxilie os escritores na redação de trabalhos científicos por meio de modelos de formatação predefinidos. Essa ferramenta garantirá o cumprimento de aspectos como margens, fontes e espaçamentos, além de automatizar tarefas repetitivas, como a criação de listas, sumário e referências. Dessa forma, espera-se reduzir o tempo gasto em revisões e aumentar a qualidade dos trabalhos. A implementação dessa ferramenta promoverá a produtividade dos escritores, uma vez que eles poderão direcionar seu tempo para a produção dos conteúdos, em oposição à formatação do documento. Para iniciar e demonstrar a eficácia do sistema proposto, será direcionado o foco em auxiliar os alunos dos cursos de graduação da UTFPR na escrita do Trabalho de Conclusão de Curso (TCC). Isso ocorrerá por meio da criação de modelos de formatação específicos para as diretrizes estabelecidas pela instituição, garantindo assim a conformidade dos trabalhos dos alunos com os requisitos exigidos.
],
english-keywords: ("tool", "academic works", "formatting", "document editor", "web development"),
english-abstract: [
One of the challenges faced by researchers is the formatting of academic work, which consumes a significant amount of time and resources (KHAN, 2018). Non-compliance with the formatting guidelines established by institutions and scientific journals may result in the rejection of submitted works (ALI, 2010). With the aim of solving this problem, this work proposes the development of a system that assists researchers in writing scientific works through predefined formatting models. This tool will ensure compliance with aspects such as margins, fonts and spacing, in addition to automating repetitive tasks, such as creating lists, tables of contents and references. In this way, it is expected to reduce the time spent on revisions and increase the quality of the work. Implementing this tool will promote writers' productivity, as they will be able to direct their time to producing content, as opposed to formatting the document. To begin and demonstrate the effectiveness of the proposed system, the focus will be on assisting students on UTFPR undergraduate courses in writing their final paper. This will occur through the creation of specific formatting models for the guidelines established by the institution, thus ensuring that student work complies with the requirements.
],
acknowledgment: [
Agradeço principalmente aos meus pais, Heloi Júnior e Adriane Portela, pois, sem o suporte destes não seria possível a realização da minha graduação e o desenvolvimento deste trabalho de conclusão de curso.
Agradeço também o Prof. MSc. <NAME>, pela idealização inicial desse trabalho e por sua orientação ao longo do mesmo.
A Secretaria do Curso, pela cooperação e prestatividade.
Enfim, a todos os meus colegas e professores, que contribuíram para minha formação acadêmica
]
)
= INTRODUÇÃO
Parte inicial do texto, na qual devem constar o tema e a delimitação do assunto tratado, objetivos da pesquisa e outros elementos necessários para situar o tema do trabalho. Após o início de uma seção, recomenda-se a inserção de um texto ou, no mínimo, uma nota explicativa sobre a seção iniciada. Evitar, por exemplo:
= INTRODUÇÃO
== Contextualização
=== Memorial da pesquisa
== Paginação
Todas as folhas do trabalho, a partir da folha de rosto, devem ser contadas sequencialmente, mas não numeradas. A numeração deve ser inserida à partir da primeira folha da parte textual (Introdução), em algarismos arábicos, no canto superior direito da folha. Havendo apêndices e anexos, as suas folhas devem ser paginadas de maneira contínua.
== Exemplos de utilização de numeração progressiva
Nos títulos com indicativo numérico não se utilizam pontos, hífen, travessão, ou qualquer sinal após o indicativo de seção ou de título.
A numeração progressiva para as seções do texto deve ser adotada para evidenciar a sistematização do conteúdo do trabalho.
Destacam-se gradativamente os títulos das seções, utilizando-se tipograficamente com recursos como letra maiúscula, negrito, itálico ou sublinhado.
No sumário, os títulos devem aparecer de forma idêntica ao texto.
Ver os exemplos na folha seguinte:
= SEÇÃO PRIMÁRIA (CAIXA ALTA E NEGRITO)
As seções primárias devem iniciar sempre em páginas distintas. Entre uma seção e outra sempre haverá um texto.
Texto justificado, com recuo especial na primeira linha de 1,5 cm. Não utilizar tab (1,25 cm). Os títulos das seções devem ser separados do texto que os precede por 1 (um) espaço (1,5 cm).
== Seção secundária (negrito)
Texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto.
=== Seção terciária (sem negrito)
Texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto.
==== Seção quaternária (sublinhado)
Texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto.
===== Seção quinária (itálico)
Texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto, texto.
@figure1
@figure2
#pagebreak()
#figure(
image("profile.jpg", width: 80%),
caption: "Foto de perfil",
source: "Autoria própria (2023)",
label: <figure1>
)
#figure(
image("profile.jpg", width: 80%),
caption: "Foto de perfil",
source: "Autoria própria (2023)",
label: <figure2>
)
#figure(
table(
columns: (auto, auto),
inset: 10pt,
align: horizon,
[*Area*], [*Parameters*],
$ pi h (D^2 - d^2) / 4 $,
[
$h$: height
$D$: outer radius
$d$: inner radius
],
$ sqrt(2) / 12 a^3 $,
[$a$: edge length]
),
caption: "Foto de perfil",
source: "Autoria própria (2023)",
kind: "board",
supplement: [Quadro],
label: <figure3>
)
Hello #cite("10.5032/jae.2014.05030"). |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/underover_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test braces.
$ x = underbrace(
1 + 2 + ... + 5,
underbrace("numbers", x + y)
) $
|
https://github.com/thanhdxuan/dacn-report | https://raw.githubusercontent.com/thanhdxuan/dacn-report/master/report-week-6/contents/03-datahandling.typ | typst | = Xử lý trường hợp bị khuyết dữ liệu (Thắng) |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1D200.typ | typst | Apache License 2.0 | #let data = (
("GREEK VOCAL NOTATION SYMBOL-1", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-2", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-3", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-4", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-5", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-6", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-7", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-8", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-9", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-10", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-11", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-12", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-13", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-14", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-15", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-16", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-17", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-18", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-19", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-20", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-21", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-22", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-23", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-24", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-50", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-51", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-52", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-53", "So", 0),
("GREEK VOCAL NOTATION SYMBOL-54", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-1", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-2", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-4", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-5", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-7", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-8", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-11", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-12", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-13", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-14", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-17", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-18", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-19", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-23", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-24", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-25", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-26", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-27", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-29", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-30", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-32", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-36", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-37", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-38", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-39", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-40", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-42", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-43", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-45", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-47", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-48", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-49", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-50", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-51", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-52", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-53", "So", 0),
("GREEK INSTRUMENTAL NOTATION SYMBOL-54", "So", 0),
("COMBINING GREEK MUSICAL TRISEME", "Mn", 230),
("COMBINING GREEK MUSICAL TETRASEME", "Mn", 230),
("COMBINING GREEK MUSICAL PENTASEME", "Mn", 230),
("GREEK MUSICAL LEIMMA", "So", 0),
)
|
https://github.com/yochem/apa-typst | https://raw.githubusercontent.com/yochem/apa-typst/main/README.md | markdown | # APA7 template for Typst
This template tries to be as correct as possible in complying to the APA7
formatting guidelines. If something seems incorrect, please let me know.
It however tries to be as unopinionated as possible: it just follows the
guidelines and changes nothing else. It also tries to let you change document
formatting the Typst way. This means no weird or undocumented template
variables.
Currently not ready yet!
## To Do
- [ ] Student title page
- [x] Infer font size
- [ ] Add bibliography style
- [ ] typst.toml
- [ ] Documentation
- [ ] Cleanup
- [ ] Localization: https://github.com/typst/typst/pull/2329
- [x] quotes (§8.26-27)
- [x] figures (§8.26-27)
|
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/akatisty/akatistJezisKristus.typ | typst | #import "/style.typ": *
#import "/styleAkatist.typ": *
= Akatist k Ježišovi Kristovi
#align(horizon + center)[#primText[
#text(60pt)[Akatist k \
Ježišovi\
Kristovi]
]]
#let akatist = (
(
"index": 1,
"kondak": [Mocný vojvodca a Pane, premožiteľ pekla, zachránený od večnej smrti, spievam ti pieseň chvály ja, tvoje stvorenie a tvoj sluha. A keďže tvoje milosrdenstvo je nevýslovné: osloboď ma od všetkých bied, keď volám: Ježišu, Synu Boží, zmiluj sa nado mnou.],
"zvolanie": [Ježišu, Synu Boží, zmiluj sa nado mnou!],
"ikos": [Tvorca anjelov a Pane mocností, aby sa oslávilo tvoje najsvätejšie meno, otvor môj nechápavý rozum a jazyk, ako si kedysi hluchonemému otvoril sluch i jazyk a on prehovoril a volal:],
"prosby": (
[Ježišu predivný, ty úžas pre anjelov!],
[Ježišu najmocnejší, vyslobodenie prarodičov!],
[Ježišu presladký, chvála patriarchov!],
[Ježišu preslávny, kráľov posila!],
[Ježišu preľúbezný, naplnenie prorokov!],
[Ježišu prepodivný, sila mučeníkov!],
[Ježišu najtichší, radosť zasvätených!],
[Ježišu najláskavejší, radosť pre kňazov!],
[Ježišu najmilosrdnejší, v pustovníctve vytrvanie!],
[Ježišu presladký, radosť nábožných!],
[Ježišu najúctyhodnejší, múdrosť panicov!],
[Ježišu predvečný, spása hriešnikov!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 2,
"kondak": [Keď si videl, Pane, vdovu veľmi plakať, zľutoval si sa a vzkriesil si jej syna, ktorého niesli na pohreb. Ty miluješ človeka, zľutuj sa aj nado mnou a vzkries moju dušu, umŕtvenú hriechmi, ktorá volá: Aleluja.],
"zvolanie": none,
"ikos": [Pane, Filip sa usiloval pochopiť nepochopiteľnú múdrosť, a tak povedal: Ukáž nám Otca. Ty však si mu riekol: Taký dlhý čas si so mnou, či si nespoznal, že Otec je vo mne a ja som v ňom? Preto tebe, Nevystihnuteľný, s bázňou volám:],
"prosby": (
[Ježišu, Bože predvečný!],
[Ježišu, Kráľ všemocný!],
[Ježišu, Vládca najtrpezlivejší!],
[Ježišu, Spasiteľ najláskavejší!],
[Ježišu, ochranca môj predobrý!],
[Ježišu, očisť moje hriechy!],
[Ježišu, odním moje neprávosti!],
[Ježišu, odpusť nespravodlivosti moje!],
[Ježišu, nádej moja, neopusť ma!],
[Ježišu, môj pomocník, neodvrhuj ma!],
[Ježišu, Stvoriteľ môj, spomeň si na mňa!],
[Ježišu, pastier môj, nezatrať ma!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 3,
"kondak": [Mocou z výsosti si vystrojil apoštolov, Ježišu, keď zotrvávali v Jeruzaleme. Aj mňa, pozbaveného všetkých dobrých skutkov, zaodej horlivosťou svojho presvätého Ducha a daj, aby som s láskou spieval: Aleluja.],
"zvolanie": none,
"ikos": [Pozval si mýtnikov a hriešnikov a neveriacich, veď v tebe, Ježišu, je bohatstvo milosrdenstva. Neprehliadni teraz ani mňa, ktorý som ako oni, ale prijmi sťa drahocenný olej túto pieseň:],
"prosby": (
[Ježišu, sila nepremožiteľná!],
[Ježišu, milota nekonečná!],
[Ježišu, krása úžasná!],
[Ježišu, láska nevýslovná!],
[Ježišu, Syn Boha živého!],
[Ježišu, nado mnou hriešnym zmiluj sa!],
[Ježišu, počuj ma, v neprávostiach počatého!],
[Ježišu, očisť ma, v hriechoch narodeného!],
[Ježišu, vyuč ma nepotrebného!],
[Ježišu, osvieť ma zatemneného!],
[Ježišu, očisť ma poškvrneného!],
[Ježišu, vyveď ma zblúdeného!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 4,
"kondak": [Peter, zachvátený búrkou pochybovačných myšlienok, začal sa topiť. Keď uzrel ťa, Ježišu, ako v tele kráčaš po vodách, spoznal v tebe pravého Boha. A keď sa mu dostalo záchrannej ruky, riekol: Aleluja.],
"zvolanie": none,
"ikos": [Dopočul sa slepý, Pane, že ideš cestou okolo, a volal: Ježišu, <NAME>, zmiluj sa nado mnou! A ty si ho zavolal k sebe a otvoril si mu oči. Osvieť teda svojou milosťou aj duchovné oči môjho srdca, lebo k tebe volám a hovorím:],
"prosby": (
[Ježišu, nebešťanov Stvoriteľ!],
[Ježišu, pozemšťanov Vykupiteľ!],
[Ježišu, pekla Premožiteľ!],
[Ježišu, všetkého tvorstva Ozdoba!],
[Ježišu, duše mojej útecha!],
[Ježišu, osvietenie môjho umu!],
[Ježišu, radosť môjho srdca!],
[Ježišu, zdravie môjho tela!],
[Ježišu, Spasiteľ môj, zachráň ma!],
[Ježišu, svetlo moje, prežiar ma!],
[Ježišu, zbav ma každej muky!],
[Ježišu, spas mňa nehodného!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 5,
"kondak": [Ako si nás kedysi vyliatím svojej božskej Krvi, Ježišu, vykúpil spod kliatby zákona, tak nás vytrhni aj zo siete, do ktorej nás had zamotal telesnými vášňami, klamnými zvodmi a hriešnymi pokleskami, nás, čo ti spievame: Aleluja.],
"zvolanie": none,
"ikos": [Keď hebrejské deti uvideli v ľudskej podobe toho, ktorý svojou rukou stvoril človeka, a spoznali, že je to Pán, náhlili sa uctiť si ho vetvami a pritom spievali: Hosana. Aj my ti prinášame pieseň a voláme:],
"prosby": (
[Ježišu, Bože opravdivý!],
[Ježišu, Synu Dávidov!],
[Ježišu, Kráľ najslávnejší!],
[Ježišu, Baránok nepoškvrnený!],
[Ježišu, Pastier obdivuhodný!],
[Ježišu, v detstve moja ochrana!],
[Ježišu, vodca v mojej mladosti!],
[Ježišu, chvála v mojej starobe!],
[Ježišu, nádej v smrti mojej!],
[Ježišu, život po zosnutí!],
[Ježišu, útecha moja na tvojom súde!],
[Ježišu, moja túžba, nezahanbi ma!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 6,
"kondak": [Aby si vyplnil predpovede a výroky Božích prorokov, Ježišu, zjavil si sa na zemi, a hoci si neobsiahnuteľný, žil si medzi ľuďmi, vzal si na seba naše choroby, a my, uzdravení tvojimi ranami, neprestávame ti spievať: Aleluja.],
"zvolanie": none,
"ikos": [Svetlo tvojej pravdy zažiarilo vesmíru a démonská lesť bola zahnaná. Lebo modly nemohli zniesť tvoju moc, Spasiteľ, a tak padli. A my, ktorí sme dosiahli spásu, ti spievame:],
"prosby": (
[Ježišu, ty Pravda, čo lož zaháňaš!],
[Ježišu, Svetlo prevyšujúce všetky svetlá!],
[Ježišu, Kráľu, čo moc všetkých premáhaš!],
[Ježišu, Boh lásky!],
[Ježišu, chlieb života, nasýť mňa hladného!],
[Ježišu, prameň múdrosti, napoj mňa smädného!],
[Ježišu, odev veselosti, zaodej ma smrteľného!],
[Ježišu, záštita radosti, zastaň sa ma nehodného!],
[Ježišu, ty obdarúvaš prosiacich, daruj mi plač nad mojimi hriechmi!],
[Ježišu, teba hľadajúci nachodia, nájdi moju dušu!],
[Ježišu, ty otváraš klopajúcim, otvor moje srdce kajúce!],
[Ježišu, Vykupiteľu hriešnych, zotri moje neprávosti!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 7,
"kondak": [Chcel si vyjaviť tajomstvo skryté od vekov, preto si sa dal viesť na zabitie ako ovča, Ježišu, a ako baránok pred svojím strihačom neotvoril si ústa. Ty ako Boh vstal si z mŕtvych, slávne si vystúpil na nebesia a spolu so sebou si pozdvihol aj nás, ktorí voláme: Aleluja.],
"zvolanie": none,
"ikos": [Ukázal, že je prepodivným Stvorením, lebo sme v ňom spoznali Stvoriteľa: Hľa, bez muža sa stal človekom z Panny, vstal z hrobu bez toho, aby porušil pečate, a telesne vošiel k apoštolom, hoci dvere boli zatvorené. My nad tým žasneme a spievame:],
"prosby": (
[Ježišu, Slovo nevysloviteľné!],
[Ježišu, Slovo neporovnateľné!],
[Ježišu, sila nevystihnuteľná!],
[Ježišu, múdrosť nedozierna!],
[Ježišu, božstvo neopísateľné!],
[Ježišu, panstvo nesmierne!],
[Ježišu, kráľovstvo neporaziteľné!],
[Ježišu, vláda nepominuteľná!],
[Ježišu, sila najvyššia!],
[Ježišu, moc večná!],
[Ježišu, Stvoriteľ môj, ku mne štedrý buď!],
[Ježišu, Spasiteľu môj, zachráň ma!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 8,
"kondak": [Vidiac s úžasom, že Boh sa stal človekom, odvráťme sa od márneho sveta a svoje mysle zamerajme na božské veci. Lebo Boh preto zostúpil na zem, aby vyviedol na nebesia nás, čo mu spievame: Aleluja.],
"zvolanie": none,
"ikos": [Celý bol na zemi, ale nebesá vôbec neopustil Nesmierny, keď dobrovoľne za nás trpel, svojou smrťou našu smrť premohol a vzkriesením daroval život tým, čo spievajú:],
"prosby": (
[Ježišu, blaženosť srdca!],
[Ježišu, sila tela!],
[Ježišu, jasanie duše!],
[Ježišu, bystrosť umu!],
[Ježišu, radosť svedomia!],
[Ježišu, nádej pevná!],
[Ježišu, večná pamiatka!],
[Ježišu, chvála vznešená!],
[Ježišu, sláva moja veľkolepá!],
[Ježišu, túžba moja, nezatrať ma!],
[Ježišu, Pastier môj, nájdi ma!],
[Ježišu, Spasiteľ môj, spas ma!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 9,
"kondak": [Všetky anjelské bytosti neprestajne oslavujú na nebesiach tvoje presväté meno, Ježišu, pričom spievajú: Svätý, Svätý, Svätý. A my hriešni smrteľnými perami na zemi spievame: Aleluja.],
"zvolanie": none,
"ikos": [Krasoreč mnohovravných je ako prejav nemých rýb, keď majú hovoriť o tebe, Ježišu, Spasiteľu náš, lebo nedokážu vysvetliť, ako môžeš byť nezmeniteľným Bohom a zároveň dokonalým človekom. My, hoci sa tajomstvu divíme, s vierou spievame:],
"prosby": (
[Ježišu, Bože predvečný!],
[Ježišu, Kráľ nad kráľmi!],
[Ježišu, Vládca nad vládcami!],
[Ježišu, Sudca živých a mŕtvych!],
[Ježišu, nádej tých, čo sú bez nádeje!],
[Ježišu, útecha plačúcich!],
[Ježišu, sláva úbohých!],
[Ježišu, neodsúď ma za moje skutky!],
[Ježišu, pre svoje milosrdenstvo očisť ma!],
[Ježišu, sklesnutosť odo mňa odožeň!],
[Ježišu, osvieť myšlienky môjho srdca!],
[Ježišu, daj, nech na smrť pamätám!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 10,
"kondak": [Chcel si spasiť svet, ty Východ východov, a tak si prišiel k temnému západu nášho bytia, ponížil si sa až na smrť, preto bolo povýšené tvoje meno nad všetky iné mená, a od všetkých nebeských i pozemských pokolení počuješ: Aleluja.],
"zvolanie": none,
"ikos": [Kráľu predvečný, Tešiteľ, pravý Kristus, očisť nás od každej škvrny, ako si očistil desať malomocných. Uzdrav nás, ako si uzdravil ziskuchtivú dušu mýtnika Zacheja, aby sme ti v pokore spievali a volali:],
"prosby": (
[Ježišu, poklad, ktorý nikto zničiť nemôže!],
[Ježišu, ty neprebádateľné bohatstvo!],
[Ježišu, ty pokrm posily!],
[Ježišu, nápoj nevyčerpateľný!],
[Ježišu, odev chudobných!],
[Ježišu, vdovám zástanca!],
[Ježišu, sirôt ochranca!],
[Ježišu, pomoc tých, čo ťažko pracujú!],
[Ježišu, cestujúcich sprievodca!],
[Ježišu, kormidelník plaviacich sa!],
[Ježišu, zátišie búrkou zachváteným!],
[Ježišu, Bože, mňa z pokleskov zodvihni!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 11,
"kondak": [Prinášam ti vrúcnu pieseň, ja nehodný, a volám k tebe ako Kanaánčanka: Ježišu, zmiluj sa nado mnou, lebo nie dcéra, ale moje telo je vášňami prudko zmietané, ba aj zlosť ho spaľuje. Uzdrav ma teda, keď volám: Aleluja.],
"zvolanie": none,
"ikos": [Ako si vyjasnil duševný zrak Pavlovi, svietniku, čo vyžaroval svetlo ľuďom v tme nevedomosti, ktorý ťa prv prenasledoval, avšak pochopil silu hlasu tvojej božskej múdrosti, tak osvieť aj moje temné duševné zreničky, lebo ti volám:],
"prosby": (
[Ježišu, Kráľu môj, nad všetkých mocný!],
[Ježišu, Bože môj, nad všetkých silný!],
[Ježišu, Pane môj, vládca nad smrťou!],
[Ježišu, Stvoriteľ môj preslávny!],
[Ježišu, Radca môj predobrý!],
[Ježišu, Pastier môj veľmi štedrý!],
[Ježišu, Vládca môj preláskavý!],
[Ježišu, môj premilosrdný Spasiteľ!],
[Ježišu, osvieť moje zmysly zatemnené vášňami!],
[Ježišu, uzdrav moje telo hriechmi doráňané!],
[Ježišu, očisť môj rozum od márnych myšlienok!],
[Ježišu, uchráň mi srdce od zlých žiadostí!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 12,
"kondak": [Obdaruj ma milosťou, veď odpúšťaš všetky dlhy, Ježišu, a prijmi mňa, kajúcnika, ako si prijal Petra, ktorý ťa zaprel. Povolaj mňa, čo klesám, ako kedysi Pavla, čo ťa prenasledoval, a čuj môj spev: Aleluja.],
"zvolanie": none,
"ikos": [Keď ospevujeme tvoje vtelenie, všetci ťa zvelebujeme a spolu s Tomášom veríme, že si Pán a Boh, ktorý tróni spolu s Otcom a chce súdiť živých i mŕtvych. Daj, aby som potom stál po tvojej pravici ja, čo spievam:],
"prosby": (
[Ježišu, Kráľ večný, zmiluj sa nado mnou!],
[Ježišu, kvet voňavý, naplň ma svojimi vôňami!],
[Ježišu, teplo hrejivé, zohrej ma!],
[Ježišu, chrám predvečný, obklop ma!],
[Ježišu, jasné rúcho, zaodej ma!],
[Ježišu, drahocenná perla, ožiar ma!],
[Ježišu, vzácny drahokam, vo mne zaskvej sa!],
[Ježišu, Slnko spravodlivosti, osvieť ma!],
[Ježišu, svetlo sväté, prežiar ma!],
[Ježišu, zbav ma duchovnej i telesnej choroby!],
[Ježišu, z ruky protivníka vytrhni ma!],
[Ježišu, z neuhasiteľného ohňa aj ostatných večných múk vysloboď ma!],
[Ježišu, Synu Boží, zmiluj sa nado mnou!],
)
), (
"index": 13,
"kondak": [Ó, presladký a vždy štedrý Ježišu, prijmi teraz túto našu skromnú modlitbu, ako si prijal dva haliere vdovy, chráň svoje dedičstvo od viditeľných i neviditeľných nepriateľov, od vpádu násilníkov, od chorôb a hladu, od všetkého zármutku a smrtonosných rán a vytrhni z nadchádzajúcich múk všetkých, čo ti spievajú: Aleluja.],
"zvolanie": none,
"ikos": none,
"prosby": none,
"modlitba": none,
)
);
#akatistGenerate(akatist)
|
|
https://github.com/Blezz-tech/math-typst | https://raw.githubusercontent.com/Blezz-tech/math-typst/main/Картинки/Демо вариант 2024/Задание 01.1.typ | typst | #import "@preview/cetz:0.1.2"
#import "/lib/my_cetz.typ": defaultStyle
#set align(center)
#cetz.canvas(length: 1cm, {
import cetz.draw: *
import cetz.angle: angle
set-style(..defaultStyle)
set-style( angle: ( radius: 0.8
, label-radius: 1.2
, fill: green.lighten(80%)
, stroke: ( paint: green.darken(50%))
)
, content: ( padding: 1pt )
)
let (A, B, C) = ((0,0), (6,0), (5,4))
angle( A, B, C, label: text([$32 degree$]) )
line(A, B, C, close: true)
circle-through(A, B, C, name: "c")
line(B, "c.center", C)
circle("c.center", radius: .05, fill: black)
content(A, $ A $, anchor: "top-right")
content(B, $ B $, anchor: "top-left")
content(C, $ C $, anchor: "bottom-left")
content("c.center", $ O $, anchor: "top", padding: 5pt)
}) |
|
https://github.com/pedrofp4444/BD | https://raw.githubusercontent.com/pedrofp4444/BD/main/report/content/[5] Implementação Física/povoamento.typ | typst | #let povoamento = {
[
== Povoamento da base de dados
Para o povoamento da base de dados, implementámos duas abordagens distintas. A primeira abordagem utilizou um ficheiro SQL, onde, através de instruções INSERT, inserimos um número reduzido de entradas para facilitar a visualização e a execução de queries simples. Esta abordagem permite uma compreensão mais clara das operações básicas da base de dados.
A segunda abordagem foi realizada utilizando Python, que permitiu a inserção de um volume maior de dados na base de dados. Utilizando a biblioteca _mysql.connector_, estabelecemos a conexão com o servidor MySQL e gerámos dados aleatórios para povoar a base de dados de forma programática. Esta técnica é particularmente útil para simular um ambiente mais próximo do real, possibilitando testes de desempenho e escalabilidade, bem como a validação de queries mais complexas e robustas.
Inicia-se o processo pela introdução de dados na tabela "Função", que contém informações sobre as funções que os funcionários podem desempenhar na _Lusium_. Adicionam-se três funções: "Operacional", "Detetive" e "Representante". Cada função tem um ID único atribuído automaticamente e uma designação correspondente.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Função com SQL.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```sql
-- Inserção de dados na tabela Função
INSERT INTO Função (Designação) VALUES
('Operacional'),
('Detetive'),
('Representante');
```
)
)
]
\
Em seguida, procedemos à inserção de dados na tabela "Funcionário", que armazena informações detalhadas sobre os funcionários, incluindo o seu ID, nome, data de nascimento, salário, NIF, fotografia e o ID da função desempenhada. Este passo é essencial para registar os dados pessoais e profissionais dos funcionários na base de dados.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Funcionário com SQL.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```sql
-- Inserção de dados na tabela Funcionário
INSERT INTO Funcionário (Nome, Data_de_nascimento, Salário, NIF, Fotografia, Função_ID) VALUES
('<NAME>', '1985-03-15', 1200, '123456789', 'foto_miguel.jpg', 1),
('<NAME>', '1990-07-21', 2800, '987654321', 'foto_ana.jpg', 2),
('<NAME>', '1982-12-10', 3000, '456789123', 'foto_pedro.jpg', 3),
('<NAME>', '1988-05-02', 1000, '789123456', 'foto_sofia.jpg', 1),
('<NAME>', '1995-09-18', 2600, '321654987', 'foto_rui.jpg', 2),
('<NAME>', '1980-11-30', 850, '654987321', 'foto_ines.jpg', 1),
('<NAME>', '1993-04-25', 2900, '987321654', 'foto_tiago.jpg', 3);
```
)
)
]
\
A tabela "Número_de_telemóvel" regista os números de telemóvel associados a cada funcionário, estabelecendo uma ligação direta entre o ID do número de telemóvel e o ID do funcionário correspondente.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Número_de_telemóvel com SQL.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```sql
-- Inserção de dados na tabela Número_de_telemóvel
INSERT INTO Número_de_telemóvel (Número_de_telemóvel_ID, Funcionário_ID) VALUES
(934678592, 1),
(966492873, 2),
(922245762, 3),
(936457856, 4),
(926486516, 5),
(964884547, 6),
(964554178, 7);
```
)
)
]
\
Na tabela "Gere", registamos a relação de gestão entre funcionários, onde um funcionário gestor é associado a outros funcionários que estão sob sua supervisão. Este relacionamento é representado pelos IDs do gestor e do funcionário.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Gere com SQL.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```sql
-- Inserção de dados na tabela Gere
INSERT INTO Gere (Funcionário_Gestor_ID, Funcionário_ID) VALUES
(3, 1),
(3, 2),
(3, 4),
(6, 5),
(6, 6),
(6, 7);
```
)
)
]
\
A tabela "Terreno" armazena informações sobre os terrenos geridos pela empresa, incluindo o ID do terreno, a quantidade de minério prevista e a quantidade de minério coletado. Esta tabela é crucial para a gestão e monitorização das operações de mineração.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Terreno com SQL.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```sql
-- Inserção de dados na tabela Terreno
INSERT INTO Terreno (Minério_previsto, Minério_coletado) VALUES
(1000, 800),
(1500, 1200),
(800, 600),
(2000, 1800),
(1200, 1000),
(1800, 1600),
(900, 700);
```
)
)
]
\
A tabela "Trabalha" regista quais funcionários estão alocados a quais terrenos, estabelecendo uma ligação direta entre o ID do funcionário e o ID do terreno.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Trabalha com SQL.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```sql
-- Inserção de dados na tabela Trabalha
INSERT INTO Trabalha (Funcionário_ID, Terreno_ID) VALUES
(1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5),
(6, 6),
(7, 7);
```
)
)
]
\
A tabela "Caso" regista os casos de investigação, incluindo informações sobre a data de abertura, estado atual, estimativa de roubo, data de encerramento e o ID do terreno associado ao caso. Estes dados são essenciais para o acompanhamento das investigações em curso.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Caso com SQL.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```sql
-- Inserção de dados na tabela Caso
INSERT INTO Caso (Data_de_abertura, Estado, Estimativa_de_roubo, Data_de_encerramento, Terreno_ID) VALUES
('2024-01-10', 'Aberto', 500, NULL, 1),
('2024-02-15', 'Fechado', 1000, '2024-05-05', 2),
('2024-03-20', 'Aberto', 700, NULL, 3),
('2024-04-25', 'Aberto', 800, NULL, 4),
('2024-05-01', 'Aberto', 300, NULL, 5),
('2024-05-08', 'Aberto', 900, NULL, 6),
('2024-05-10', 'Aberto', 600, NULL, 7);
```
)
)
]
\
Por fim, a tabela "Suspeito" regista os funcionários suspeitos em cada caso, incluindo o seu estado de envolvimento, nível de envolvimento e notas adicionais sobre a suspeita. Estes dados são fundamentais para a análise e resolução dos casos de investigação.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Suspeito com SQL.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```sql
-- Inserção de dados na tabela Suspeito
INSERT INTO Suspeito (Funcionário_ID, Caso_ID, Estado, Envolvimento, Notas) VALUES
(1, 1, 'Inocente', 1, 'Nenhuma informação adicional.'),
(2, 2, 'Culpado', 9, 'Suspeito estava presente na cena do crime.'),
(3, 3, 'Em investigação', 5, 'Algumas pistas indicam possível envolvimento.'),
(4, 4, 'Em investigação', 3, 'Não há provas concretas.'),
(5, 5, 'Inocente', 2, 'Sem evidências contra o suspeito.'),
(6, 6, 'Culpado', 8, 'Fortes indícios de participação.'),
(7, 7, 'Em investigação', 4, 'Possível conexão com outras investigações.');
```
)
)
]
\
Para iniciar o processo com Python, primeiro importamos as bibliotecas necessárias, entre elas, _mysql.connector_ para estabelecer conexão com a base de dados, _faker_ para criação de dados fictícios, _random_ de forma a induzir aleatoriedade nas informações criada e, finalmente, _datatime_ para facilitar a manipulação de datas em formatos pré-concebidos. Neste exemplo, solicita-se ao utilizador do programa que insira as suas credenciais e procede-se ao estabelecimento da ligação ao sistema e definição do cursor para execução de comandos SQL. Por último, inicializa-se o _faker_ para criar dados em "Português de Portugal".
#align(center)[
#figure(
kind: image,
caption: [Importação de bibliotecas e conexão à base de dados.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```python
import mysql.connector
from faker import Faker
import random
from datetime import timedelta
# Solicita ao utilizador o nome de utilizador e a senha para se conectar ao SQL
user = input("Insira o nome de utilizador da base de dados SQL: ")
password = input("Insira a senha da base de dados SQL: ")
# Estabelece a conexão com a base de dados SQL
conn = mysql.connector.connect(
host="localhost",
user=user,
password=<PASSWORD>,
database="Lusium"
)
# Verifica se a conexão foi bem-sucedida e imprime a versão do servidor
if conn.is_connected():
print("Conectado ao SQL Server versão ", conn.get_server_info())
# Cria um cursor para executar comandos SQL
cursor = conn.cursor()
# Instancia o Faker configurado para gerar dados em português de Portugal
fake = Faker('pt_PT')
```
)
)
]
\
Inicialmente, utiliza-se uma lista com as funções previstas e, em seguida, inserimos cada uma dessas funções na tabela "Função". Através de um ciclo _for_, itera-se sobre a lista e o método _cursor.execute()_ para executar a inserção, passando o identificador e a designação de cada função.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Função com Python.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```python
# Lista de funções para inserir na tabela Função
funcoes = ['Operacional', 'Detetive', 'Representante']
# Insere as 3 funções na tabela Função
for i, funcao in enumerate(funcoes, start=1):
cursor.execute("INSERT INTO Função (Função_ID, Designação) VALUES (%s, %s)", (i, funcao))
```
)
)
]
\
De seguida, geram-se e inserem-se dados fictícios para 100 funcionários na tabela "Funcionário". Utiliza-se a biblioteca _fake_ para gerar nomes, datas de nascimento, NIFs e URLs de fotografias, e a biblioteca _random_ para definir salários e IDs de função. Cada funcionário é inserido na tabela através de um ciclo _for_ que utiliza o método _cursor.execute()_.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Funcionário com Python.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```python
# Gera e insere dados fictícios para 100 funcionários na tabela Funcionário
for i in range(1, 101):
nome = fake.name()
data_nascimento = fake.date_of_birth(minimum_age=18, maximum_age=65)
salario = random.randint(1000, 5000)
nif = fake.random_number(digits=9)
fotografia = fake.image_url()
funcao_id = random.randint(1, len(funcoes))
cursor.execute("INSERT INTO Funcionário (Funcionário_ID, Nome, Data_de_nascimento, Salário, NIF, Fotografia, Função_ID) VALUES (%s, %s, %s, %s, %s, %s, %s)",
(i, nome, data_nascimento, salario, nif, fotografia, funcao_id))
```
)
)
]
\
O bloco de código seguinte é responsável por inserir 100 números de telemóvel na tabela "Número_de_telemóvel". Geram-se números sequenciais a partir de 900000000 e associa-se cada número a um funcionário. Utiliza-se um ciclo _for_ para a inserção sequencial dos dados na tabela com o método _cursor.execute()_.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Número_de_telemóvel com Python.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```python
# Gera e insere 100 números de telefone sequenciais na tabela Número_de_telemóvel
for i in range(1, 101):
num_telefone = 900000000 + i
funcionário_id = i
cursor.execute("INSERT INTO Número_de_telemóvel (Número_de_telemóvel_ID, Funcionário_ID) VALUES (%s, %s)", (num_telefone, funcionário_id))
```
)
)
]
\
Neste bloco de código, inserem-se 50 registos na tabela "Gere". Estes registos representam relações de gestão entre funcionários. Para cada gestor, escolhe-se aleatoriamente um funcionário que ele gere, utilizando _random.randint_ para determinar o ID do funcionário gerido. As inserções são realizadas num ciclo _for_.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Gere com Python.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```python
# Gera e insere 50 dados de gestão aleatória na tabela Gere
for i in range(1, 51):
funcionário_gestor_id = i
funcionário_id = random.randint(1, 100)
cursor.execute("INSERT INTO Gere (Funcionário_Gestor_ID, Funcionário_ID) VALUES (%s, %s)", (funcionário_gestor_id, funcionário_id))
```
)
)
]
\
Prossegue-se com a geração e inserção de dados para 20 terrenos na tabela "Terreno". Cada terreno tem um valor previsto e coletado de minério, ambos gerados aleatoriamente. Utiliza-se um ciclo _for_ e o método _cursor.execute()_ para realizar as inserções na tabela.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Terreno com Python.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```python
# Gera e insere dados fictícios para 20 terrenos na tabela Terreno
for i in range(1, 21):
minério_previsto = random.randint(1000, 10000)
minério_coletado = random.randint(0, minério_previsto)
cursor.execute("INSERT INTO Terreno (Terreno_ID, Minério_previsto, Minério_coletado) VALUES (%s, %s, %s)", (i, minério_previsto, minério_coletado))
```
)
)
]
\
Na inserção de dados de trabalho para 100 funcionários na tabela "Trabalha", cada funcionário é associado aleatoriamente a um terreno. Utiliza-se um ciclo _for_ e a função _random.randint_ para selecionar o ID do terreno. As inserções são feitas novamente com o método _cursor.execute()_.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Trabalha com Python.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```python
# Gera e insere 100 dados de trabalho na tabela Trabalha
for i in range(1, 101):
funcionário_id = i
terreno_id = random.randint(1, 20)
cursor.execute("INSERT INTO Trabalha (Funcionário_ID, Terreno_ID) VALUES (%s, %s)", (funcionário_id, terreno_id))
```
)
)
]
\
No presente bloco de código, geram-se e inserem-se dados fictícios para 50 casos na tabela "Caso". Geram-se datas de abertura e encerramento, estados dos casos, estimativas de roubo e associam-se cada caso a um terreno, aplicando as estratégias já anteriormente descritas.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Caso com Python.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```python
# Gera e insere dados fictícios para 50 casos na tabela Caso
for i in range(1, 51):
data_abertura = fake.date_between(start_date='-1y', end_date='today')
estado = random.choice(['Aberto', 'Fechado'])
estimativa_roubo = random.randint(1000, 100000)
data_encerramento = data_abertura + timedelta(days=random.randint(10, 365)) if estado == 'Fechado' else None
terreno_id = random.randint(1, 20)
cursor.execute("INSERT INTO Caso (Caso_ID, Data_de_abertura, Estado, Estimativa_de_roubo, Data_de_encerramento, Terreno_ID) VALUES (%s, %s, %s, %s, %s, %s)", (i, data_abertura, estado, estimativa_roubo, data_encerramento, terreno_id))
```
)
)
]
\
Neste bloco de código, inserem-se dados fictícios para 100 suspeitos na tabela "Suspeito". Cada suspeito é associado a um funcionário e a um caso, com estados, níveis de envolvimento e notas gerados aleatoriamente.
#align(center)[
#figure(
kind: image,
caption: [Inserção de dados na tabela Suspeito com Python.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```python
# Gera e insere dados fictícios de 100 suspeitos na tabela Suspeito
for i in range(1, 101):
funcionário_id = i
caso_id = random.randint(1, 50)
estado = random.choice(['Inocente', 'Em investigação', 'Culpado'])
envolvimento = random.randint(1, 10)
notas = fake.text()
cursor.execute("INSERT INTO Suspeito (Funcionário_ID, Caso_ID, Estado, Envolvimento, Notas) VALUES (%s, %s, %s, %s, %s)", (funcionário_id, caso_id, estado, envolvimento, notas))
```
)
)
]
\
Por fim, no último bloco de código, imprime-se uma mensagem de sucesso após a inserção correta dos dados. Em seguida, confirmam-se todas as transações pendentes na base de dados ao utilizar _conn.commit()_ e fecha-se a conexão com a base de dados ao utilizador _conn.close()_.
#align(center)[
#figure(
kind: image,
caption: [Finalização das transações e conexão com a base de dados.],
block(
fill: rgb("#f2f2eb"),
inset: 8pt,
```python
# Imprime a mensagem de sucesso
print("Dados inseridos com sucesso!")
# Confirma todas as transações e fecha a conexão com a base de dados
conn.commit()
conn.close()
```
)
)
]
\
As duas abordagens complementam-se eficazmente no povoamento da base de dados. A abordagem SQL, com menos registos, facilita a exemplificação de operações mais simples, enquanto a utilização de Python permitiu um povoamento extensivo e variado, essencial para testes avançados e validação de queries complexas. Desta forma, assegura-se um ambiente de desenvolvimento robusto e versátil.
]
}
|
|
https://github.com/dadn-dream-home/documents | https://raw.githubusercontent.com/dadn-dream-home/documents/main/contents/index.typ | typst | #include "01-mo-dau/index.typ"
#include "02-phan-tich-yeu-cau/index.typ"
#include "03-luoc-do-use-case/index.typ"
#include "04-use-case-scenarios/index.typ"
#include "05-thiet-ke-database/index.typ"
#include "06-luoc-do-deployment/index.typ"
#include "07-thiet-ke-kien-truc/index.typ"
#include "08-thiet-bi/index.typ"
#include "09-hien-thuc/index.typ"
#include "10-ket-luan/index.typ" |
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/stack-2.typ | typst | Apache License 2.0 | // Test fr units in stacks.
---
#set page(height: 3.5cm)
#stack(
dir: ltr,
spacing: 1fr,
..for c in "ABCDEFGHI" {([#c],)}
)
Hello
#v(2fr)
from #h(1fr) the #h(1fr) wonderful
#v(1fr)
World! 🌍
---
#set page(height: 2cm)
#set text(white)
#rect(fill: forest)[
#v(1fr)
#h(1fr) Hi you!
]
|
https://github.com/jamesrswift/pixel-pipeline | https://raw.githubusercontent.com/jamesrswift/pixel-pipeline/main/src/pipeline/primitives.typ | typst | The Unlicense | #import "../primitives/position.typ": position
#let assembled(
tags: (),
..data
) = {
(: tags: tags)
data.named()
}
#let positioned(
positions: arguments( root: position((0,0)) ),
name: none,
) = {
(: positions: positions,)
if name != none {(: name: name)}
}
#let stroked(
fill: none,
stroke: none,
) = {
if fill != none {(: fill: fill)}
if stroke != none {(: stroke: stroke)}
}
#let rendered(
content: none,
) = (:
content: content,
) |
https://github.com/tingerrr/masters-thesis | https://raw.githubusercontent.com/tingerrr/masters-thesis/main/src/de/chapters/6-benchmarks.typ | typst | #import "/src/util.typ": *
#import "/src/figures.typ"
#let data = json("/src/benchmarks.json")
#let benchmarks = (:)
#for entry in data.benchmarks {
let name = entry.remove("name")
if "BigO" in name or "RMS" in name {
continue
}
name = name.trim(at: start, "benchmarks::")
let (type_, method, arg) = name.split(regex("::|/"));
if type_ not in benchmarks {
benchmarks.insert(type_, (:))
}
if method not in benchmarks.at(type_) {
benchmarks.at(type_).insert(method, (:))
}
benchmarks.at(type_).at(method).insert(arg, entry)
}
Zusätzlich zur theoretischen Analyse wurden zu verschiedenen verwendeten Datenstrukturen Benchmarks durchgeführt, um zu testen, ob eine simple Implementierung die theoretischen Erwartungen bestätigen kann.
Zur Kontrolle der Ergebnisse der neuen Implementierung wurden verschiedene Benchmarks mit den bis dato in T4gl verwendeten Datenstrukturen, sowie einer naiven persistenten B-Baum-Implementierung durchgeführt.
Die Tests beschränken sich auf die für die Arbeit relevanten Szenarien.
Dazu zählen Lesezugriffe und verschiedene Szenarien, in welchen worst-case Verhalten getestet wurde.
Dadurch sollen vor allem die Vor- und Nachteile granular-persistenter Datentrukturen wie 2-3-Fingerbäumen gegenüber grob-persistenten wie QMap hervorgehoben werden.
= Umgebung & Auswertung
Die Benchmarks wurden mit #link("https://github.com/google/benchmark", `google/benchmark`) ` v1.9.0` und #link("https://github.com/qt/qtbase", `Qt`) `5.15.15` durchgeführt.
Kompilation erfolgte mit `g++` `(gcc)` `14.2.1 20240910` und C++ 20.
Für die Kompilation wurde Optimierungslevel 2 (`-O2`), sowie Link-Time-Optimization (`-lto`, `-fno-fat-lto-objects`) verwendet.
Sowohl Benchmarking und Kompilation erfolgten auf `Arch Linux 6.10.10-arch1-1` mit einem 11th Gen Intel® Core™ i7-11 auf einem Lenovo ThinkPad E15 G2 i7-1165G7 TS.
Bei der Darstellung der Zeiten wird die gemessene Systemzeit verwendet und auf 2 Kommastellen genau angezeigt.
Die Iterationen-Spalte gibt die Anzahl der getesteten Aufrufe an, jede Iteration wurde mit den gleichen Ursprungsbedingungen getestet.
Bei höheren Zeiten senkt `google/benchmark` die Anzahl der Iterationen automatisch ab, sodass pro Szenario etwa eine Sekunde lang Werte erfasst werden.
Die Werte der Zeit-Spalte ergeben sich aus dem Durchschnitt aller Iterationen.
Da es sich lediglich um Datenstrukturen im Arbeitsspeicher handelt, weicht die CPU-Zeit nicht weit von der gemessenen Systemzeit ab und wurde daher nicht mit in die Tabellen aufgenommen.
Ähnlich wie auch beim Source Code werden die Daten im archivierten Repo vollständigt mit aufgeführt und können unter `src/bechmarks.json` gefunden werden.
= Kontrollgruppen
== QMap
Zunächst werden zwei Szenarien getestet, welche das Kernproblem der QMap-Implementierung hervorheben sollen: wiederholte Schreibzugriffe bei nicht-einzigartigen Referenten.
Zusätzlich dazu wird auch ein durchschnittlicher Lesezugriff gemessen.
#let benchmarks-table(type) = table(
columns: 4,
align: (left,) + (right,) * 3,
table.header[Szenario][Größe][Zeit][Iterationen],
..type.pairs().map(((method, entries)) => {
(
table.cell(rowspan: entries.len(), raw(block: false, method)),
..entries.pairs().map(((arg, entry)) => {
(
arg,
oxifmt.strfmt("{:.2} {}", entry.real_time, entry.time_unit),
[#entry.iterations],
)
}),
table.hline(stroke: 0.5pt),
)
}).flatten(),
)
#figure(
benchmarks-table(benchmarks.qmap),
caption: [Die verschiedenen Iterationen der QMap Benchmarks.],
) <tbl:bench-qmap>
@tbl:bench-qmap zeigt die zuvorgenannten Szenarien.
Das erste Szenario `get` zeigt einen durchschnittlichen Lesezugriff auf QMaps verschiedener Größen.
Die Szenarien `insert_unique` und `insert_shared` testen das Einfügen von Werten für eine QMap mit einem Referenten (`unique`) und mehreren Referenten (`shared`).
Dabei ist ein klarer Sprung der benötigten Zeit zwischen beiden Szenarien zu sehen.
Sobald eine QMap-Instanz nicht der einzige Referent ist, muss der gesamte Speicher der QMap kopiert werden, um ein einziges Element hinzuzufügen.
== Persistenter B-Tree
Da 2-3-Fingerbäume von 2-3-Bäumen abgeleitet wurden und keine Generalisiernug der Zweigfaktoren gelungen ist, ist als Kontrolle auch eine simple B-Baum Implementierung vorhanden.
Ähnlich wie die der 2-3-Fingerbäume, ist diese Implementierung granular-persistent, die Persistenz erfolgt auf jeder Knotenebene.
#figure(
benchmarks-table(benchmarks.b_tree),
caption: [Die verschiedenen Iterationen der B-Baum Benchmarks.],
) <tbl:bench-btree>
@tbl:bench-btree zeigt zwei Szenarien.
Ähnlich wie bei QMap wird der durchschnittliche Lesezugriff sowie das Einfügen von Werten gemessen.
Da die B-Baum Implementierung generell eine Pfadkopie bei einem Schreibzugriff erzeugt, selbst wenn diese Instanz der einzige Referent ist, ist für das Einfügen nur ein Szenario vorhanden.
= 2-3-Fingerbäume
Für 2-3-Fingerbäume wurden verschiedene Szenarien getestet, aber nicht direkt Szenarien für das Einfügen von Werten in den Baum.
Da die Implementierung von 2-3-Fingerbäumen als geordnete Sequenzen `insert` durch `split`, gefolgt von `push` und dann `concat` umgesetzt, kann dabei nicht ohne Weiteres ein worst-case für alle drei Operationen erzeugt werden, da diese voneinander abhängen.
Stattdessen wird für alle drei Operationen das worst-case Szenario gemessen, um daraus Schlüsse auf die worst-case Performance von `insert` zu ziehen.
@tbl:bench-finger-tree enthält fünf Szenarien:
- `get` wie zuvor als durchschnittlicher Lesezugriff,
- `split` für das Trennen von 2-3-Fingerbäumen,
- `concat` für das Zusammenführen von 2-3-Fingerbäumen,
- `push_worst` als worst-case `push`-Szenario und
- `push_avg` als durchschnittliches `push`-Szenario.
Die Szenarien `split` und `concat` testen dabei mit Bäumen, welche gezielt aufgebaut wurden um den Worst Case zu simulieren.
Bei `split` werden zufällige Werte zwischen `INT_MIN` und `INT_MAX` durch `std::rand()` generiert und eingefügt.
Gleichermaßen werden diese Werte behalten und deren Median verwendet, um bei einem möglichst tiefen Punkt im Baum die Trennung zu erzwingen.
Das geschieht unter der Annahme, dass die gleichmäßig verteilten Werte von `std::rand()` einen relativ balancierten Baum erzeugen, in welchem der Median im tiefesten Knoten liegt.
Die Schlüssel für das Szenario `get` werden ebenfalls auf diese Weise ausgesucht, um möglichst tief in den Baum gehen zu müssen.
Im Szenario `concat` wird ein 2-3-Fingerbaum mit sich selbst verknüpft.
Dabei wird zwar zwangsläufig die Ordnungsrelation der Schlüssel ignoriert, diese hat aber keinen Einfluss auf die Implementierung von `concat` oder anderweitige Implementierungsdetails des Benchmarkszenarios.
Die Verknüpfung mit sich selbst ermögicht dabei ein Szenario, in welchem kein seichterer Baum existiert, welcher die Rekursion frühzeitig stoppen würde.
Die Szenarios `push_worst` und `push_avg` zeigen jeweils die worst-case und average-case Szenarien von `push`.
Zur Erstellung des worst-case Szenarios wurden Bäume erstellt, bei welchen ein weiterer `push` bis in die tiefste Ebene überläuft.
Das Szenario `push_avg` zeigt, warum es nicht einfach ist, direkt `insert` zu testen.
Es müssten Bäume erstellt werden, welche nach ihrer Trennung genau so aufgebaut sind, dass auch die `push`-Operation danach den Schlimmstfall zeigt, genau so wie `concat` nach dieser.
Es ist nicht trivial, die genaue Struktur der Bäume zu kontrollieren, vor allem bei hohen Datenmengen.
Bei Versuchen, die `insert`-Operation direkt zu messen, zeigte sich das vor allem in stärkerem Rauschen der erfassten Zeiten.
Daher werden zum Einordnen von `insert` die individuellen worst-case Ergebnisse von `split`, `push_worst` und `concat` verwendet, auch wenn diese möglicherweise nie zusammen auftreten können.
#figure(
benchmarks-table(benchmarks.finger_tree),
caption: [Die verschiedenen Iterationen der 2-3-Fingerbaum Benchmarks.],
) <tbl:bench-finger-tree>
Die zuvorgenannten Szenarien sind in @tbl:bench-finger-tree zu sehen.
Aufällig sind dabei direkt die Sprünge in `get` bei 65536 und 524288, es ist unklar, ob es sich um ein Implementierungsproblem handelt oder ein inherentes Problem mit 2-3-Fingerbäumen.
Mehrere Durchläufe der Benchmarks zeigten ähnliche Sprünge bei den gleichen Werten auf.
= Vergleich
Bei Lesezugriffen steigt $t$ für alle Datenstrukturen etwa logarithmisch zu $n$, jedoch mit verschiedenen Faktoren.
2-3-Fingerbäume zeigen dabei einen besonders hohen Faktor und schneiden schlechter ab.
Bei QMap gibt es allerdings bei 200.000 bis 500.000 eine Verschlechterung, dort gibt es einen linearen Sprung (zu sehen in @tbl:bench-qmap, Szenario `get`).
Das stimmt mit den theoretischen Erwartungen überein, während die zuvor erwähnten Sprünge der 2-3-Fingerbäume noch unerklärt bleiben.
#let plot-operation(type, op) = cetz.plot.add(
op.pairs().map(((arg, entry)) => (int(arg), entry.real_time)),
label: box(inset: 0.25em, raw(block: false, type)),
)
#figure(
cetz.canvas({
import cetz.draw: *
import cetz.plot
cetz.draw.set-style(axes: (bottom: (tick: (label: (angle: 45deg, anchor: "north-east")))))
plot.plot(
size: (9, 7),
x-label: $n$,
y-label: $t$,
y-unit: "ns",
{
for (type, methods) in benchmarks {
plot-operation(type, methods.get)
}
}
)
}),
caption: [Vergleich der Lesezugriffe in Abhängigkeit der Anzahl der Elemente $n$.],
) <fig:bench-get>
Für den Vergleich der `insert`-Operation werden für 2-3-Fingerbäume die Datenpunkte der `split`-, `push_worst`- und `concat`-Operationen aufsummiert.
Es ist möglich, dass selbst im realen worst-case solche Werte nie gemeinsam vorkommen.
So ist zum Beispiel nach dem worst-case `push` der Baum dort minimal auf jeder Ebene besetzt, wo dieser für den `concat` worst-case maximal besetzt sein müsste.
Die Summierung aller worst-case Werte gibt daher eine besonders pessimistische, aber sichere Aussage über die worst-case Performance von `insert`.
#figure(
cetz.canvas({
import cetz.draw: *
import cetz.plot
cetz.draw.set-style(axes: (bottom: (tick: (label: (angle: 45deg, anchor: "north-east")))))
plot.plot(
size: (9, 7),
x-label: $n$,
y-label: $t$,
y-unit: "ns",
{
for (type, methods) in benchmarks {
if type == "qmap" {
plot-operation(type, methods.insert_unique)
} else if type == "b_tree" {
plot-operation(type, methods.insert)
} else {
plot-operation(
type,
methods
.split
.pairs()
.map(((arg, entry)) => (
(arg): (
real_time: entry.real_time
+ methods.push_worst.at(arg).real_time
+ methods.concat.at(arg).real_time
)
)
)
.fold((:), (acc, it) => acc + it)
)
}
}
}
)
}),
caption: [Vergleich der Schreibzugriffe in Abhängigkeit der Anzahl der Elemente $n$.],
) <fig:bench-insert>
@fig:bench-insert zeigt für B-Baum das Senario `insert`, für QMap das Szenario `insert_unique` und für 2-3-Fingerbaum die Summe der Szenarien `spit`, `push_worst` und `concat`.
Dabei ist zu beachten, dass das worst-case QMap Szenario so hohe Werte erziehlt, dass die Werte von B-Baum und 2-3-Fingerbaum gleich aussehen (siehe @tbl:bench-qmap, Szenario `insert_shared`).
Die Abbildung zeigt, dass 2-3-Fingerbäume in ihrer jetzigen Implementierung deutlich schlechter abschließen als QMap im best-case Szenario und die B-Baum-Implementierung generell.
Allerdings schließen beide Baum-Implementierungen weitaus besser als QMap ab sobald mehr als ein Referent existiert, wie es in T4gl oft der Fall ist.
|
|
https://github.com/icpmoles/politypst | https://raw.githubusercontent.com/icpmoles/politypst/main/aside/appendix_A.typ | typst | #let app_A = [
#heading(numbering: none)[Appendix A]
If you need to include an appendix to support the research in your thesis, you can place
it at the end of the manuscript. An appendix contains supplementary material (figures,
tables, data, codes, mathematical proofs, surveys, . . . ) which supplement the main results
contained in the previous chapters.
] |
|
https://github.com/Mouwrice/resume | https://raw.githubusercontent.com/Mouwrice/resume/main/modules/skills.typ | typst | #import "../brilliant-CV/template.typ": *
#cvSection("Skills")
#cvSkill(
type: [Languages],
info: [Dutch (Native) #hBar() English (Fluent) #hBar() French (Basic)]
)
#cvSkill(
type: [Programming Languages],
info: [Rust #hBar() Kotlin #hBar() Java #hBar() C++ #hBar() C #hBar() JavaScript #hBar() TypeScript #hBar() Bash #hBar() Assembly #hBar() Haskell #hBar() Prolog #hBar() Python #hBar() HTML #hBar() CSS]
)
#cvSkill(
type: [Tech & Others],
info: [Git #hBar() GitHub Actions #hBar() Typst #hBar() Linux #hBar() REST #hBar() OpenAPI #hBar() Agile #hBar() Semantic Versioning]
)
#cvSkill(
type: [Personal Interests],
info: [Piano #hBar() DJ'ing #hBar() Exercising]
)
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/meta/outline-indent.typ | typst | Apache License 2.0 | // Tests outline 'indent' option.
---
// With heading numbering
#set page(width: 200pt)
#set heading(numbering: "1.a.")
#outline()
#outline(indent: false)
#outline(indent: true)
#outline(indent: none)
#outline(indent: auto)
#outline(indent: 2em)
#outline(indent: n => ([-], [], [==], [====]).at(n))
#outline(indent: n => "!" * calc.pow(2, n))
= About ACME Corp.
== History
#lorem(10)
== Products
#lorem(10)
=== Categories
#lorem(10)
==== General
#lorem(10)
---
// Without heading numbering
#set page(width: 200pt)
#outline()
#outline(indent: false)
#outline(indent: true)
#outline(indent: none)
#outline(indent: auto)
#outline(indent: n => 2em * n)
#outline(indent: n => ([-], [], [==], [====]).at(n))
#outline(indent: n => "!" * calc.pow(2, n))
= About ACME Corp.
== History
#lorem(10)
== Products
#lorem(10)
=== Categories
#lorem(10)
==== General
#lorem(10)
---
// Error: 2-35 expected relative length or content, found dictionary
#outline(indent: n => (a: "dict"))
= Heading
|
https://github.com/ljgago/typst-chords | https://raw.githubusercontent.com/ljgago/typst-chords/main/examples/jingle-bells.typ | typst | MIT License | #import "../lib.typ": *
#set document(date: none)
#set align(center)
#set page(
margin: (top: 2.5cm, bottom: 2.5cm),
numbering: "1 / 1",
header: locate(loc => {
set text(11pt)
let elems = query(
selector(heading).before(loc),
loc,
)
let title = smallcaps[_Jingle Bells_]
let artist = smallcaps[_Christmas Song_]
if elems != () {
let body = elems.last().body
title + h(1fr) + artist
}
})
)
#let gchord = chart-chord.with(design: "round", size: 14pt)
#let chord = single-chord.with(
font: "PT Sans",
size: 12pt,
weight: "semibold",
background: silver
)
= <NAME> / #text(weight: "regular")[_Christmas Song_]
#v(2em)
#gchord(tabs: "32ooo3", fingers: "21ooo3")[G]
#h(1fr)
#gchord(tabs: "x32o1o", fingers: "o32o1o")[C]
#h(1fr)
#gchord(tabs: "xo221o", fingers: "oo231o")[Am]
#h(1fr)
#gchord(tabs: "xxo212", fingers: "ooo213")[D7]
#h(1fr)
#gchord(tabs: "xxo232", fingers: "ooo132")[D]
#h(1fr)
#gchord(tabs: "xo2o2o", fingers: "oo1o2o")[A7]
#v(1em)
#set align(left)
#set text(14pt)
#smallcaps[[Verse]] \
#chord[Dashing][G][2] through the snow, in a one-horse open #chord[sleigh,][C][3] \
#chord[O'er][Am][2] the fields we #chord[go,][D7][] laughing all the #chord[way.][G][] \
#chord[Bells][G][2] on bob-tails ring, making spirits #chord[bright,][C][3] \
What #chord[fun][Am][2] it is to #chord[ride][D][2] and sing a #chord[sleighing][D7][3] song #chord[tonight.][G][3] #chord[Oh!][D7][]
\
#smallcaps[[Chorus]] \
#chord[Jingle][G][2] bells, jingle bells, jingle #chord[all][C][] the #chord[way!][G][] \
#chord[Oh][C][] what fun it #chord[is][G][] to ride \
In a #chord[one-horse][A7][2] open #chord[sleigh,][D7][3] hey! \
#chord[Jingle][G][2] bells, jingle bells, jingle #chord[all][C][] the #chord[way!][G][] \
#chord[Oh][C][] what fun it #chord[is][G][] to ride \
In a #chord[one-horse][D7][2] open #chord[sleigh][G][3]
\
#smallcaps[[Verse]] \
A day or two ago, I thought I'd take a ride \
And soon <NAME> was seated by my side \
The horse was lean and lank, misfortune seemed his lot \
We ran into a drifted bank and there we got upsot. Oh!
#smallcaps[[Chorus]] \
Jingle bells, jingle bells, jingle all the way! \
Oh what fun it is to ride \
In a one-horse open sleigh, hey! \
Jingle bells, jingle bells, jingle all the way! \
Oh what fun it is to ride \
In a one-horse open sleigh
\
#smallcaps[[Verse]] \
A day or two ago, the story I must tell \
I went out on the snow and on my back I fell \
A gent was riding by in a one-horse open sleigh \
He laughed at me as I there lay but quickly drove away. Oh!
\
#smallcaps[[Chorus]] \
Jingle bells, jingle bells, jingle all the way! \
Oh what fun it is to ride \
In a one-horse open sleigh, hey! \
Jingle bells, jingle bells, jingle all the way! \
Oh what fun it is to ride \
In a one-horse open sleigh
\
#smallcaps[[Verse]] \
Now the ground is white, go it while you're young \
Take the girls along and sing this sleighing song \
Just bet a bobtailed bay, two forty as his speed \
Hitch him to an open sleigh and crack! you'll take the lead. Oh! \
\
#smallcaps[[Chorus]] \
Jingle bells, jingle bells, jingle all the way! \
Oh what fun it is to ride \
In a one-horse open sleigh, hey! \
Jingle bells, jingle bells, jingle all the way! \
Oh what fun it is to ride \
In a one-horse open sleigh
|
https://github.com/Rhinemann/mage-hack | https://raw.githubusercontent.com/Rhinemann/mage-hack/main/src/chapters/Game%20Rules.typ | typst | #import "../templates/interior_template.typ": *
#show: chapter.with(chapter_name: "Game Rules")
= Game Rules
#show: columns.with(2, gutter: 1em)
The following chapter discusses the main chunk of game rules.
#block(breakable: false)[
== Traits & Dice
Each character has a few different collections of traits, called trait sets. Each trait in a set is rated with a die size: #spec_c.d4, #spec_c.d6, #spec_c.d8, #spec_c.d10, or #spec_c.d12. Generally, larger die sizes make a trait more effective, so #spec_c.d6 is better than #spec_c.d4. Examples of trait sets used in Mage are attributes (Physical, Mental, and Social groups), skills (Physical, Mental, and Social groups), Spheres and signature assets (items or other factors that provide an advantage, such as Hidden Knife or Magnifying Glass). One example trait set for a character might be the attributes Intelligence #spec_c.d8, Wits #spec_c.d8, Resolve #spec_c.d8, Strength #spec_c.d6, Dexterity #spec_c.d6, Stamina #spec_c.d6, Presence #spec_c.d6, Manipulation #spec_c.d6, and Composure #spec_c.d6.
]
When you want your character to do something, if there's nothing getting in your way, you just do it. If there is opposition (such as an opponent, a difficult environment, or a time limit), you roll the dice for certain traits to figure out if you succeed or fail.
#block(breakable: false)[
=== Your Total
After rolling, you add two of the die results together for your total. (So if my highest rolls were a 7 on a #spec_c.d8 and a 3 on a #spec_c.d6, I'd probably want to add those two together for a total of 10.)
]
#block(breakable: false)[
=== Your Effect Die
After choosing die results for your total, you pick one of the other dice you rolled to be your effect die. This choice doesn't affect whether you succeed or fail. It's kind of like how a die for damage in the most popular fantasy RPGs is separate from your attack roll to hit.
]
#block(breakable: false)[
=== Opposition
When you roll, another player (often the Storyteller, or ST) builds their own dice pool and rolls it. You compare your roll's total to theirs, and the higher roll succeeds. The player who rolls first sets the bar for how difficult the opposition's roll should be, so that player wins ties.
]
#block(breakable: false)[
=== Success
If you win, the size of your effect die (not the number it rolled) determines how big of an effect your success had. You might say, "My effect die is #spec_c.d8."
]
For example, if you roll to hit someone with a weapon, your total determines whether you hit (like comparing an attack roll to armor class in traditional fantasy RPGs), and your effect die would be how much damage you inflict. Your total tells you whether the story goes your way; your effect die tells you how far it goes.
#block(breakable: false)[
=== An Example Of Play
Lydia was going home late evening after shopping for new fabrics when she noticed a man following her. Not wanting to tip off the stalker she decides to read his aura. She grabs an amulet on her neck that looks like a burning spider, feels its warmth and whispers a spell almost silently to get a reading on the strange man.
]
The ST asks the player to roll the dice to see if the succeeds. She gathers Spider in the Web (her distinction) #spec_c.d8 Perception #spec_c.d8, Awareness #spec_c.d6, Ars Potentiae (Prime) #spec_c.d6, her Prime Perception steps up Prime to a #spec_c.d8, then she rolls, getting a 4, 3, and 2 on #spec_c.d8 and a 2 on #spec_c.d6.
She picks 4 and 3 to add together, making her total 7. She uses the leftover #spec_c.d8 as her effect die.
The man's total against her is 15, so she fails to get a clear read on the man, and starts getting more worried, gaining #spec_c.d6 Rattled stress from the failure.
#block(breakable: false)[
== The ST
As in many tabletop role-playing games, one player takes on the role of the _Game Moderator_, or GM, called a Storyteller (ST) in Mage, rather than playing their own character. The ST frames scenes, portrays supporting characters (called STCs, or _Storyteller Characters_), controls the opposition (including rolling dice), and ends scenes.
]
The characters portrayed by everybody else are called _player characters_, or _PCs_.
#block(breakable: false)[
=== Sessions, Scenes, & Beats
Games are played in _sessions_. A session is just however long you and your group gather to play at a time, whether in-person or online.
]
Each session is divided into units of story and action called _scenes_, just like a play, film, or TV show.
Player actions take place in units of time called _beats_. A beat is simply how long it takes to complete one action or one piece of a larger action (including both the die roll to do something and the roll opposing it).
#block(breakable: false)[
=== Action Order
Normally, a player can just roll a test or describe their character's actions whenever it makes sense, as part of the game's ongoing conversation. When it's helpful to organize things a bit more, the ST can move things into _action order_.
]
When the game is in action order, the scene splits into _rounds_. A round is nothing more or less than the amount of time it takes for every participant in a scene to take one beat's worth of action (often called a _turn_).
Usually, the ST chooses one player to go first. After a player takes a beat, they choose who goes next. The ST and any STCs active in the scene get to take their own beats as well. Once everyone has taken a beat to do what they want to do, the round ends. Whoever goes last in a round chooses who goes first in the next round, which can be themself!
#block(breakable: false)[
=== Stepping Up & Stepping Down
The rules sometimes tell you to _step up_ a die, changing it from a die of one size to one of the next larger size, (such as changing #spec_c.d4 to #spec_c.d6 or #spec_c.d8 to #spec_c.d10) or to _step down_ a die (the reverse, such as #spec_c.d12 to #spec_c.d10).
]
When you step up a #spec_c.d12 in your dice pool, you keep the #spec_c.d12, but add an extra #spec_c.d6 to your pool as well.
When you step down a #spec_c.d4 in your pool, you remove that die entirely.
#block(breakable: false)[
=== Doubling Dice
Sometimes, the rules tell you to _double_ a die in your pool. When you double a die, you add another die of the same size to the pool before you roll.
]
#sidebar()[
#block(breakable: false)[
==== Session Zero and Safety Tools
Playing a tabletop RPG can become a bad experience if everyone involved isn't on the same page about the topics and themes they'll be exploring in play. The best way to align those expectations is usually having a formal process, making sure everyone has a chance to be heard and set appropriate boundaries. That process can be a part of a “Session Zero”, a conversation before actual play begins that can also provide a chance to make characters together, discuss the game, build anticipation, and decide what kind of content should or shouldn't be a part of the game.
]
You should also use appropriate safety tools, such as #link("https://www.dicebreaker.com/categories/roleplaying-game/opinion/lines-and-veils-rpg-safety-tools")[Lines and Veils], the #link("https://docs.google.com/document/d/1SB0jsx34bWHZWbnNIVVuMjhDkrdFGo1_hSC2BWPlI3A")[X-Card by <NAME>oulos] or Script Change by #link("https://thoughty.itch.io/script-change")[<NAME> Sheldon]. Script Change is especially recommended, because the framework it provides can improve the experience of playing a tabletop RPG even when content concerns aren't an issue. What's important is choosing the tools that work for you and your group.
]
#block(breakable: false)[
== Conflict Resolution
When you want your character to do something, if there's nothing getting in your way, you just do it. If there is opposition (such as an opponent, a difficult environment, or a time limit), you roll the dice with certain traits to figure out if you succeed or fail.
]
#block(breakable: false)[
=== Tests
The most basic kind of die roll is a _test_. You say you want to do something, and if it requires a roll, but it isn't directly against another significant character (like another PC), the ST just grabs some dice and rolls.
]
Usually the ST sets a _difficulty_, choosing two dice depending on how hard they think the roll should be:
#{
show table.cell: it => {
if it.x == 0 {
set text(size: 20pt)
it
} else {
it
}
}
block(breakable: false, width: 100%)[
#table(
align: horizon,
columns: (auto, 40%),
[#spec_c.d4 #spec_c.d4], [Very easy],
[#spec_c.d6 #spec_c.d6], [Easy],
[#spec_c.d8 #spec_c.d8], [Challenging],
[#spec_c.d10 #spec_c.d10], [Hard],
[#spec_c.d12 #spec_c.d12], [Very hard],
)
]
}
For a test, the ST rolls first, their total sets the difficulty, and then you roll. If your total is higher than the difficulty total, you succeed; if it is equal or lower, you fail.
#block(breakable: false)[
=== Effect Dice
When you succeed on a roll, your effect die usually becomes an _asset_ (a new temporary trait that benefits you) or a _complication_ (a new temporary trait that makes things harder for your opposition).
]
Most rolls create some kind of complication or asset, but there are a couple other things you can do.
You might simply roll to change your situation, such as by opening a locked door. In this case, your effect die just measures your degree of success: a #spec_c.d4 might be getting the door open just a crack, while a #spec_c.d12 busts it wide open.
You might also roll to step down or end a complication; this is called _recovery_, and the rules for it are explained later.
#block(breakable: false)[
==== Heroic Success
When you succeed on a roll, if your total beats the opposing roll by 5 or more, you've scored a _heroic success_. This means that you not only achieve what you set out to do, but surpass your own expectations in doing so. For every 5 by which you beat the opposing roll, your effect die steps up by one size.
]
#block(breakable: false)[
==== Comparing Effect Dice
Even when you fail a roll against someone, your effect die still matters. If your roll fails, but your effect die is larger than the opposition's effect die, the opposition's effect die steps down.
]
#block(breakable: false)[
=== Plot Points
This game uses a special currency called _plot points_ (abbreviated #spec_c.pp), which you can spend to affect the story. You'll likely earn and spend plot points all the time. Every player gets at least one #spec_c.pp at the start of each session.
]
The most important uses of plot points include:
- You can spend a #spec_c.pp to instantly create a #spec_c.d6 asset.
- When you add up die results for your total, you can spend one #spec_c.pp to add in the result from one additional die, increasing your total.
- You can spend a #spec_c.pp to make an asset useful to a whole group of people instead of just one.
- When an asset would go away at the end of a scene or session, you can spend a #spec_c.pp to keep it, starting the next scene or session with the asset still in play.
Unless specified otherwise, you can spend plot points at any time, even when it isn't your beat or turn.
Any unspent plot points are lost at the end of a session, so it's best not to hoard them.
#block(breakable: false)[
==== Hitches
When you roll 1 on a die, you can't count that die towards your total or use it for your effect die.
]
A die that rolls a 1 is called a _hitch_. When you roll a hitch, the ST can grant you a plot point to give you a #spec_c.d6 complication (which may step up a complication you already have).
When the ST rolls a hitch, it's called an _opportunity_. When the ST rolls an opportunity, you can spend a #spec_c.pp to step up an existing asset or step down a complication.
#block(breakable: false)[
=== SFX
Your character gains _SFX_, special effects that give you added influence over the story. These reflect your character's extraordinary abilities or their powerful role in the narrative. Many SFX require you to spend plot points to activate them. Other SFX allow you to impose a disadvantage on your character in order to earn #spec_c.pp or another reward. For example, the _Hinder_ SFX lets you earn a #spec_c.pp by rolling a smaller die.
]
Using an SFX is always a choice; you are never compelled to activate your character's SFX, unless that SFX is a _Limit_. A Limit is an SFX which can be activated by the ST.
#block(breakable: false)[
=== Doom Pool
The doom pool serves as a combination of ambient threat level, ST resource, and pacing mechanic.
]
At the beginning of each session, the ST starts with a doom pool of at least #spec_c.d6 #spec_c.d6. If the session is of global or cosmic scale, the pool may start with 3 or 4 dice. If the session is a major breakpoint in a chronicle, the size of these starting dice might be #spec_c.d8 or even #spec_c.d10.
The doom pool sets difficulty dice for all tests. To set the difficulty, the ST picks up some or all the dice in the doom pool and rolls them, taking two of the dice results and adding them together, as normal. The ST can spend a die not used in the total and add its result to the total; this spent die is removed from the doom pool after resolving the outcome. The remaining dice, including the two that were added together for the total, remain in the doom pool.
The ST may spend a die from the doom pool to add it to a STC's dice pool, before the dice pool is rolled. This die is removed from the doom pool and doesn't go back in once the STC's roll is resolved. Doom dice may also be spent like #spec_c.pp, where a #spec_c.d6 from the doom pool is equivalent to a single #spec_c.pp. This usually happens when activating a STC SFX. If the doom pool only has larger dice in it, the next highest die must be spent in place of the #spec_c.d6.
The doom pool increases when the ST activates hitches rolled by players. The ST adds a die of the same size as the one that rolled the hitch to their doom pool. Alternatively, the ST can use a smaller die to step up an equal or larger existing die in the doom pool by one step.
#block(breakable: false)[
==== Spending Doom Pool Dice
In addition to spending a doom pool die for anything a #spec_c.pp could normally accomplish, the ST can spend a die to do a variety of special actions. These vary depending on the game.
]
Some of the most common uses are:
/ Creating a complication, asset, or scene distinction: spend a die from the doom pool and create a Complication or Asset attached to the scene equal in size to the die spent. Or, spend at least a #spec_c.d8 and add a distinction to the scene that may be used by players and STCs alike.
/ Interrupting the action order: Spend a die from the doom pool equal to or greater in size than the largest combat or senses-related trait of the PC whose turn is up next. One of the ST's own STCs gets to go instead, and the ST then picks who goes afterward (not necessarily the player who was interrupted).
/ Adding a new extra STC: Spend a die from the doom pool and create an extra with a single trait rated at the size of the doom die spent.
/ Introducing a new minor STC or major STC: If a STC who isn't present in the scene could conceivably show up, spend a die from the doom pool equal to that STC's highest rated trait and drop them into the scene, ready to act when the action order gets to them (which could be right away, if the ST is the one deciding who goes next).
/ Splitting the group: spend a #spec_c.d10 or a #spec_c.d12 from the doom pool and some environmental or narrative event takes place that divides the group into two (minimum one PC in each new group). The PCs have to spend time reuniting their group, which may lead to more problems.
/ Ending the scene immediately: spend #spec_c.d12 #spec_c.d12 from the doom pool and cut the scene off right there before it's resolved, with the ST deciding how it ends. Usually, the scenes should play out until there's a reasonable ending point, but this way the ST can just smash cut to a new scene with plot threads dangling. Or stage an auto-win by the enemies.
#block(breakable: false)[
=== Contest
Playing Mage you may sometimes find yourself facing an important STC or even another player for something important. In those cases a simple test isn't enough, that's where contests come in.
]
Examples of contests include:
- Brawling a shapeshifting witch.
- Engaging in Certamen with a Tradition mage.
- Debating an Etherite on the properties of an arcade contraption.
A contest is a series of dice rolls between opponents, each trying to beat the previous roll until one side chooses not to roll and gives in, or fails to beat the previous roll and takes a complication or is taken out.
When a PC gets into a conflict over something they want, a contest determines if any other character can intervene, thwart, or oppose the PC. Contests are almost always initiated by a player, who picks up dice and essentially says, "I'm doing this. Who's stopping me?"
If no one opposes the PC, there's no need to roll dice -- the contest's outcome is determined as if the player succeeded. If an effect die is required, use the largest die in the initiating player's dice pool.
#block(breakable: false)[
==== Engaging In A Contest
A PC initiates a contest when they state they want to do something, and another character (either another PC, or a STC) wants to stop them. The player who initiated the contest picks up the dice and rolls first, adding together two results for a total. If the opposing player decides against engaging in the contest after seeing the difficulty, the initiating character automatically succeeds in the contest. Otherwise, the opposing player assembles a dice pool and tries to beat the difficulty the initiating character set.
]
If the opposing character doesn't beat the initial difficulty, the initiating character wins the contest. If the opposing character beats the initial difficulty, the ball's back in the initiating character's court.
They can choose to give in, in which case they:
- define the failure on their own terms
- cannot immediately initiate another contest with the opponent, and
- get a #spec_c.pp
Otherwise, the opposition's total becomes the new difficulty, and the initiating character must roll again to try to beat it. Failing to beat the opposition means your opponent wins, giving them the opportunity to define how they stopped you.
Contests go back and forth until one side gives in or fails to beat the difficulty. The winner can push the story forward with an advantage by giving the opposition a complication (or stress) using the effect die from their winning result. The opposing character, or another character in the scene, might still want to stop the initiating character, but the stakes have been changed in a meaningful way.
#block(breakable: false)[
==== About Giving In
Giving in during a contest may seem counterintuitive. After all, a player or the ST is choosing to lose and give their opponent what they want. However, they get a #spec_c.pp when they do this and get to describe the terms of the loss. It's possible the opponent's goal is to knock the character out, or trap them, or seize them, or worse. A player should never be forced to hand over control of their character as a result of giving in. That's what makes it different from being taken out or being given complications (or stress) --- you have a say in how that outcome plays out.
]
#block(breakable: false)[
==== Interfering In A Contest
If a PC wants to get involved in a contest between two other characters, they can attempt to interfere—but it costs a #spec_c.pp and comes with a bit of risk. Usually this means the PC wants something neither of the other two characters wants, or maybe the same thing as one of them but on their own terms. After each side has rolled at least once, a player can spend a #spec_c.pp and describe how they're trying to get between the characters. The player rolls their dice and compares the total to the current difficulty in the contest.
]
If the PC doesn't beat the total, the characters ignore the interruption and, when the contest concludes, the winner gives the PC a complication (or stress) equal to their effect die for getting in the way. If the PC beats the total, they've stopped the contest in its tracks. No one loses, gives in, or takes any complications --- yet.
If both sides are committed to continuing the contest, their players (or the ST if a STC is one of the contestants) each hand the interfering PC a #spec_c.pp and describe how they work around, over, or through them to continue their contest. Neither can give in until both have rolled again.
An interfering PC may elect to interfere again by spending another #spec_c.pp, but if either contestant rolls higher, they can inflict a complication (or stress) on the interloper equal to the contestant's own effect die—that means the interfering character may get two complications if they don't roll high enough.
#block(breakable: false)[
==== Group Contest
Contests can be used as a way to represent all-out scrambles for some kind of object, goal, or prize. One player initiates the contest, then any other character that wants to be involved in the contest can join in, one at a time as determined by the ST. The highest roller is the successful character. After the first roll to enter the contest, any character that chooses to stay in the contest takes a complication (or stress) if they aren't the winner. They may otherwise give in as normal.
]
If a PC loses in such a contest, the player should describe how things went badly for them. The winner chooses their effect die and gives it to all of the other contestants as a complication (or stress), but they can decide to make it a different type for each character if they like, though it still uses the same effect die to determine the size of the die.
#block(breakable: false)[
=== Challenge
Challenges represent problems that are many-faceted, presenting different, smaller issues to tackle before being fully resolved, or problems that are big or take a lot of time, therefore can't be solved with a test.
]
Challenges take place over several rounds. The challenge gets to act on its own turn and can either get worse or create problems for the PCs in response.
If there's no time-sensitive element to the challenge, success becomes a matter of how long it takes the players to overcome the challenge without getting taken out of the scene. The ST may declare that something happens after a certain number of rounds; if this happens, the challenge may be a failure.
#block(breakable: false)[
==== Challenge Pool
A challenge pool is a dice pool that represents the difficulty and duration of a challenge; it's rolled by the ST to set the difficulty for each PC's turn, and for the ST to roll against the PCs on the challenge pool's turn. To create a challenge pool, the ST chooses base difficulty dice the same way as they would in a test:
]
#{
show table.cell: it => {
if it.x == 0 {
set text(size: 20pt)
it
} else {
it
}
}
block(breakable: false, width: 100%)[
#table(
align: horizon,
columns: (auto, 40%),
[#spec_c.d4 #spec_c.d4], [Very easy],
[#spec_c.d6 #spec_c.d6], [Easy],
[#spec_c.d8 #spec_c.d8], [Challenging],
[#spec_c.d10 #spec_c.d10], [Hard],
[#spec_c.d12 #spec_c.d12], [Very hard],
)
]
}
Then, they add up to 3 additional dice of the same die rating depending on how long the challenge should take to overcome:
#block(breakable: false, width: 100%)[
#table(
align: horizon,
columns: (30%, 30%),
[*+1* die], [Short],
[*+2* dice], [Medium],
[*+3* dice], [Long],
)
]
#block(breakable: false)[
==== Doom Pool & Challenge
You can use both challenges and the doom pool, spending dice directly from the doom pool to create a new challenge. Dice spent in this manner go from the doom pool to the challenge pool, thus reducing the overall doom of the session but creating specific, localized situations the players can directly affect.
]
#block(breakable: false)[
==== Taking Turns In A Challenge
Challenges use handoff initiative. The ST decides which PC goes first, but once a PC has had their turn, that player chooses which remaining PC goes next. Each player gets one turn per round. On a PC's turn, the ST rolls the challenge pool to set the difficulty, just like in a test.
]
Once every PC has had a turn, the challenge pool acts.
*The ST can choose to either:*
- Target a player with a negative effect, or
- Strengthen the challenge pool by stepping up one of its dice or adding a #spec_c.d6
- Spend challenge pool dice in the same way as doom pool dice
Once the ST has had their turn, it's back to the players. The player who went last in the previous round gets to choose who goes first, including nominating themselves.
#block(breakable: false)[
==== Challenge Outcomes
If a PC beats the challenge, they make progress, and compare their effect die to one of the dice in the challenge pool. If it's bigger, the challenge die is removed from the challenge pool. If it's equal to or smaller, the challenge die is stepped down by one step. If a challenge die would be reduced below #spec_c.d4, it's taken out of the pool.
]
If the PC doesn't beat the challenge, they fail to progress the challenge, and take stress (or a complication) of the ST's choice equal to the challenge pool's effect die.
Once the challenge pool is reduced to zero dice, the challenge is over, and the PCs have won. Alternatively, the ST may declare that something happens after a certain number of rounds. If this happens, the challenge may be a failure if players don't overcome the challenge in time.
|
|
https://github.com/GolemT/BA-Template | https://raw.githubusercontent.com/GolemT/BA-Template/main/lib/shared-lib.typ | typst | #let is-in-dict(dict-type, state, element) = {
state.display(list => {
if element not in list {
panic(element + " is not a key in the " + dict-type + " dictionary.")
return false
}
})
return true
}
#let display-link(dict-type, state, element, text) = {
if is-in-dict(dict-type, state, element) {
link(label(dict-type + "-" + element), text)
}
}
#let display(dict-type, state, element, text, link: true) = {
if link {
display-link(dict-type, state, element, text)
} else {
text
}
}
#let todo(message) = {
set text(white)
rect(
fill: red,
radius: 4pt,
[*TODO:* #message]
)
set text(black)
}
#let comment(message) = {
set text(white)
rect(
fill: blue,
radius: 4pt,
[Kommentar: #message]
)
} |
|
https://github.com/typst-community/valkyrie | https://raw.githubusercontent.com/typst-community/valkyrie/main/tests/types/gradient/test.typ | typst | Other | #import "/src/lib.typ" as z
#import "/tests/utility.typ": *
#show: show-rule.with();
#let schema = z.gradient()
= types/gradient
== Input types
#let _ = z.parse(gradient.linear(..color.map.rainbow), schema) |
https://github.com/angelcerveraroldan/notes | https://raw.githubusercontent.com/angelcerveraroldan/notes/main/abstact_algebra/abstract_algebra.typ | typst | #import "../preamble.typ" : *
#import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge
#let abstract = align(center, pad(top: 100pt, diagram(
node-defocus: 0,
spacing: (1cm, 2cm),
edge-stroke: 1pt,
crossing-thickness: 5,
mark-scale: 70%,
node-fill: luma(97%),
node-outset: 3pt,
node((0,0), "magma"),
node((-1,1), "semigroup"),
node(( 0,1), "unital magma"),
node((+1,1), "quasigroup"),
node((-1,2), "monoid"),
node(( 0,2), "inverse semigroup"),
node((+1,2), "loop"),
node(( 0,3), "group"),
{
let quad(a, b, label, paint, ..args) = {
paint = paint.darken(25%)
edge(a, b, text(paint, label), "-|>", stroke: paint, label-side: center, ..args)
}
quad((0,0), (-1,1), "Assoc", blue)
quad((0,1), (-1,2), "Assoc", blue, label-pos: 0.3)
quad((1,2), (0,3), "Assoc", blue)
quad((0,0), (0,1), "Id", red)
quad((-1,1), (-1,2), "Id", red, label-pos: 0.3)
quad((+1,1), (+1,2), "Id", red, label-pos: 0.3)
quad((0,2), (0,3), "Id", red)
quad((0,0), (1,1), "Div", yellow)
quad((-1,1), (0,2), "Div", yellow, label-pos: 0.3, "crossing")
quad((-1,2), (0,3), "Inv", green)
quad((0,1), (+1,2), "Inv", green, label-pos: 0.3)
quad((1,1), (0,2), "Assoc", blue, label-pos: 0.3, "crossing")
})))
#show: project.with(
title: "Abstract Algebra",
subtitle: "",
topright: "Abstract Algebra Notes",
abstract: abstract,
quote: "For this proof, assume that group theroy is an interesting subject.",
)
#show heading.where(
level: 1
): it => block(width: 100%)[
#set align(center)
#set text(30pt, weight: "bold")
#smallcaps(it.body)
]
#pagebreak()
#let sections = ("gruops", "rings", "fields")
#heading("Group Theory")
#vline()
#let groupsc = ( "intro", "free_groups" )
#for chapter in groupsc {
include("./notes/groups/" + chapter + ".typ")
}
#pagebreak()
#heading("Rings And Fields 1")
#vline()
#let ringsc = ( "intro", )
#for chapter in ringsc {
include("./notes/rings/" + chapter + ".typ")
}
|
|
https://github.com/pawarherschel/typst | https://raw.githubusercontent.com/pawarherschel/typst/main/template.old/README.md | markdown | Apache License 2.0 | <h1 align="center">
<img src='https://user-images.githubusercontent.com/77310871/236178717-7ce72cfb-085a-4609-863b-cfceb3d6c9f2.png'>
<br><br>
AwesomeCV-Typst Submodule
</h1>
## What is this for?
**AwesomeCV-Typst** is a [**Typst**](https://github.com/typst/typst) template for making **Résume**, **CV** or **Cover Letter** inspired by the famous LaTeX CV template [**Awesome-CV**](https://github.com/posquit0/Awesome-CV). It provides customizations and **multilingual support** beyond the original LaTeX project.
See the [Example repository](https://github.com/mintyfrankie/awesomeCV-Typst) for a complete demonstration.
## Usage
You can either clone the example repository and modify it locally to have a hands-on experience, or you might want to add this submodule repository and build up your own Typst project.
### Method 1: Clone the [example repository](https://github.com/mintyfrankie/awesomeCV-Typst)
```bash
git clone https://github.com/mintyfrankie/awesomeCV-Typst
cd awesomeCV-Typst
typst --font-path ./src/fonts compile cv.typ
```
### Method 2: Add the submodule repository to your git project
```bash
cd your/CV/project
git submodule add https://github.com/mintyfrankie/awesomeCV-Typst-Submodule awesomeCV
typst compile cv.typ
```
When the template file is updated:
```bash
git submodule update --remote
```
## Credit
- [**Typst**](https://github.com/typst/typst) is a newborn, open source and simple typesetting engine that offers a better scripting experience than [**LaTeX**](https://www.latex-project.org/).
- [**Awesome-CV**](https://github.com/posquit0/Awesome-CV) is the original LaTeX CV template from which this project is heavily inspired. Thanks [posquit0](https://github.com/posquit0) for your excellent work! |
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/highlight.typ | typst | Apache License 2.0 | #set page(width: auto)
```typ
#set hello()
#set hello()
#set hello.world()
#set hello.my.world()
#let foo(x) = x * 2
#show heading: func
#show module.func: func
#show module.func: it => {}
#foo(ident: ident)
#hello
#hello()
#box[]
#hello.world
#hello.world()
#hello().world()
#hello.my.world
#hello.my.world()
#hello.my().world
#hello.my().world()
#{ hello }
#{ hello() }
#{ hello.world() }
$ hello $
$ hello() $
$ box[] $
$ hello.world $
$ hello.world() $
$ hello.my.world() $
$ f_zeta(x), f_zeta(x)/1 $
$ emph(hello.my.world()) $
$ emph(hello.my().world) $
$ emph(hello.my().world()) $
$ #hello $
$ #hello() $
$ #hello.world $
$ #hello.world() $
$ #box[] $
#if foo []
```
|
https://github.com/binhtran432k/ungrammar-docs | https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/system-implementation/vscode.typ | typst | === Ungrammar VS Code Extension <subsec-impl-vscode>
The Ungrammar VS Code extension offers a rapid and accessible means of
introducing the Ungrammar language ecosystem to a broader user base,
capitalizing on the widespread popularity of the VS Code editor.
Key Features and Benefits:
- *Seamless Integration*: Integrates seamlessly with the VS Code environment,
providing a familiar and intuitive user experience.
- *LSP-Powered Features*: Leverages the power of the Language Server Protocol
(LSP) to deliver a comprehensive set of language features within VS Code.
- *Enhanced Productivity*: Streamlines development workflows by providing
features like code completion, syntax highlighting, diagnostics, and
navigation.
- *User-Friendly Interface*: Presents a user-friendly interface that is easy to
learn and use, even for developers new to the Ungrammar language.
Technical Implementation:
- *Client-Server Architecture*: Employs a client-server architecture, where the
VS Code extension acts as the client and communicates with the Ungrammar
Language Server (@subsec-impl-langserver).
- *LSP Communication*: Utilizes the LSP protocol for efficient data exchange and
feature implementation.
- *Customizable Settings*: Offers customizable settings to allow users to tailor
the extension's behavior to their preferences.
Overall, the Ungrammar VS Code extension serves as a valuable tool for
developers who want to leverage the power of the Ungrammar language within the
VS Code environment.
==== Implementation Detail
The Ungrammar VS Code extension leverages the power of the Ungrammar Language
Server to provide a rich set of language features within the VS Code
environment. By establishing a communication channel between the extension and
the language server, we've enabled the seamless integration of LSP
capabilities, enhancing the coding experience for users.
#figure(
raw(read("/assets/tree-vscode.txt"), block: true),
caption: [Tree of Ungrammar VS Code Extension workspace],
)
==== Writing Documentation
To ensure a seamless user experience and facilitate the effective use of our
Ungrammar VS Code extension, we have developed comprehensive documentation that
provides detailed guidance and information (See more in @apx-doc).
==== Deployment to Visual Studio Marketplace
To make our Ungrammar VS Code extension readily accessible to a wider audience,
we have successfully deployed it to the Visual Studio Marketplace under the
name "Ungrammar Language Features"
(#link("https://marketplace.visualstudio.com/items?itemName=binhtran432k.ungrammar-language-features")).
This strategic move allows users to easily discover, install, and utilize our
extension within their VS Code environment.
#figure(
image("/assets/vscode.jpg", width: 90%),
caption: [Deployed Ungrammar Language Features on Visual Studio Marketplace],
)
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/055%20-%20Murders%20at%20Karlov%20Manor/002_Episode%202%3A%20Monsters%20We%20Became.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 2: Monsters We Became",
set_name: "Murders at Karlov Manor",
story_date: datetime(day: 08, month: 01, year: 2024),
author: "<NAME>",
doc
)
Kaya ran through the manor as swiftly as her legs could carry her. Teysa still caught up quickly, moving with a speed that Kaya knew would cost her later: for Teysa to be running alongside the much younger, fitter Planeswalker, she had to be drawing deep on her magical reserves. That sort of thing always came with a price.
The pair came to a stop at a tall, ornate door, still closed despite the ring of servers and household servants standing outside it. They looked uniformly relieved when they saw Teysa and Kaya charging down the hall.
"Well?" Teysa demanded. "Why are you all just standing around?"
"The door's locked, ma'am," said one of the servers. "Larysa's gone looking for the key."
"How do you not know where the key is?"
Seeing that Teysa's temper was hanging on by a thread, Kaya set a hand on her arm. "Easy," she said. "I don't need keys, not even in Karlov Manor." She caught a flicker of something in Teysa's eyes and paused. "Unless this door is warded against ghosts?"
"Much of the manor is, as a precaution," said Teysa. "You might be able to come up through the floor, but even that would be a questionable approach."
"Great. So someone's in trouble, and we're just going to stand around."
Kaya's displeasure was radiant, and for once, Teysa had no answer to it. No one spoke.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The seconds stretched into minutes, becoming intolerable. Teysa cast an uneasy glance at the door. The scream that had drawn them had been loud and piercing: the sound of someone in genuine danger. And for all that, the locked room was silent now, without even a hint that someone was moving around inside.
They were still standing there, waiting for Larysa to return, when Ezrim came galloping down the hall, the massive archon easily filling all available space. His mount's long primary feathers swept household items and bric-a-brac off tables as he passed. "We heard the screams on the balcony," he said. "It took me a moment to find a door that could accommodate me. What has happened here?"
"My apologies, Ezrim, for the disruption," said Teysa. "We're waiting for one of my servers to return with the key."
"If someone is hurt, or a crime was committed here, waiting is not in our best interests," said Ezrim. He raised a foreleg, looking meaningfully from the door to Teysa as he waited for her acquiescence.
Teysa didn't hesitate. She could always bill him later.
"Break it," she said.
Two heavy blows and the door snapped off its hinges, breaking clean in two as it fell inward. Kaya rushed forward, faster than Teysa now that the other woman wasn't using magic to speed her steps. The servants hung back, waiting for the all-clear, while Ezrim, who would dearly love to have accompanied her if not for his size, paced in the hall outside.
All of them heard Kaya's quickly cut-off gasp, followed by frozen silence.
Teysa couldn't allow the moment to linger. "Kaya?" she called. "Kaya, are you all right?"
Kaya appeared in the doorway, face grayish with pallor. "I'm fine," she said. "Teysa, send someone to find Vannifar."
Under other circumstances, Teysa might have reminded Kaya that she was no longer in charge; allowing a former guild leader to give her orders could undermine her authority in a dangerous way. The look on Kaya's face stopped her cold.
"All of you, go," she said, looking around at the servants. "Find me Vannifar of the Simic Combine and inform her that her presence is required. If she asks why, say only that I need to speak with her immediately."
Kaya appeared satisfied with this. She turned, vanishing back into the room.
Teysa sighed before nodding politely to Ezrim. "My apologies, Ezrim, but I don't think the room is large enough for you to join us."
"I understand," Ezrim said and looked to the remaining servants. "Find me one of my detectives. The Agency should be represented here. I will wait here and watch for signs of trouble." With that, he sank to the floor, assuming a guard position.
There could be no better security than an archon. Teysa turned, taking a deep breath, and followed Kaya's path into the room.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It was one of the many small sitting rooms scattered around Karlov Manor, intended for entertaining guests or conducting business negotiations. With the celebration making such gatherings impractical and unlikely, this one had been pressed into use as a cloakroom of sorts, filled with the coats and cloaks of the attendees. Kaya had stopped just inside, eyes locked on the pile of coats at the center of the floor. No—not the coats.
What was arrayed atop the coats.
Teysa stepped up next to her and froze, hand tightening on the handle of her cane until it looked like her fingers were going to break.
Zegana of the Simic Combine was artfully arranged at the center of the pile. While there were signs of a struggle around the edges, there were none around her body; she was posed as prettily as a doll, her left hand raised to the level of her face, which was turned slightly to the side. If not for the fact that she so clearly wasn't breathing, it would have looked like she was posing for a portrait of herself in repose, fins and hair arranged to their best possible advantage.
#figure(image("002_Episode 2: Monsters We Became/01.png.jpg", width: 100%), caption: [Art by: Isis], supplement: none, numbering: none)
"She's dead," said Teysa needlessly, and Kaya nodded in silent agreement. There were no visible wounds or signs of foul play, but they were of the Orzhov; they knew death when it was presented to them.
The coats around Zegana's body were a seeming mismatch, expensive fabrics and cheap linens overlapping with a carelessness that looked almost strange, given the precision of Zegana's posing. Kaya took a step back, not averting her eyes. Zegana had died alone, with only time for a single scream. She deserved to be witnessed now.
From her new angle, Kaya saw the edges of a flower petal protruding from between Zegana's fingers. Frowning, Kaya stepped closer again, bending to see.
"What is it?" asked Teysa, voice sharp with worry.
"A flower …" said Kaya, bending farther down. "A black iris. Did you use black irises in any of the floral arrangements downstairs?" If Zegana had grabbed hold of a bouquet as she was falling, maybe that could tell them where she'd been killed.
But no: the scream had come from this room. This small, unremarkable, locked room. There hadn't been #emph[time] for Zegana to be killed elsewhere in the manor and then moved, especially not with the way she'd been arranged. Kaya realized how foolish her question was even before she saw Teysa shaking her head.
"I tried to avoid arrangements that would strike people outside the guild as funereal or remind them of the Golgari in any way," said Teysa. "It meant I lost one of our signature colors, but it was worth it for the reactions to the décor. No lilies, no black irises, no mourner's stars."
"Well, Zegana found one somewhere." Kaya straightened and was preparing to say more when a commotion from the hall caught her attention. "That will be Vannifar," she said, and turned, leaving Teysa alone with the corpse as she walked away.
Kaya stepped into the hall, where she found not Vannifar but a cluster of Agency detectives and Ezrim. The archon was standing, wings half-mantled, as he glared at Aurelia. Aurelia saw Kaya and turned away from him, waving one hand in a dismissive gesture.
"#emph[There] you are," she said. "Vannifar is coming, and Ezrim's people are locking down the building. They say Teysa has forbidden anyone to leave the manor grounds. Something has happened."
"Yes," said Kaya. There was no point in lying.
"It was inappropriate not to summon the ranking legionnaire immediately."
Teysa, stepping up beside Kaya, lifted an eyebrow. Kaya glanced at her. The expected explosion, however, did not materialize.
"I've been encouraging the house staff to show initiative," said Teysa. "I'll have to find out who looked at the situation and correctly intuited a lockdown as my next order. They deserve a bonus for their excellent predictive skills, and a scolding for their arrogance."
"So there #emph[is] a reason to lock down the building?" asked Aurelia. "My people are helping with the lockdown, but they," she waved a dismissive hand at Ezrim and the detectives, "have no business being involved. They need to let the professionals handle whatever's happening. What #emph[is] happening, Teysa?"
"I would prefer to wait for Vannifar before saying anything; you know as well as I do that the walls have ears." Teysa folded both hands over the top of her cane, and Kaya realized the other woman had positioned herself such that between the two of them, they completely blocked off access to the room behind them. Clever, and easily done.
Footsteps approached down the hall, accompanied by the soft swishing sound of protoplasm brushing against the floor. Everyone assembled turned, watching the approach of Vannifar of the Simic. Three lower-ranked members of the Combine accompanied their leader, who was frowning, looking distinctly unamused.
"Teysa, what is the meaning of this?" she asked. "Why did you summon me like a common criminal? Why are the Azorius and the Boros telling my people that we're not allowed to leave?"
"I was hoping to do this in a less open location," said Teysa. "Would you be willing to step into the library?"
"No. You summon me without explanation, and then you try to delay offering up the same? I'm sorry, but whatever you have to say, you say it here and now."
Teysa frowned, hands tightening again atop her cane. "Then Vannifar, it is with the deepest of regrets that I inform you that Zegana of the Simic Combine has been killed."
The effect on the gathering crowd, all of whom had known that #emph[something] terrible had happened, was nothing short of electric. Vannifar swayed, expression one of pure shock. Ezrim turned to start snapping orders at his agents as Aurelia snapped her wings fully open, preventing them from getting past her.
"There's a dangerous killer on the loose!" Aurelia shouted. "This is not a time for amateur detective work. The Legion will take over from here. The guilds will handle this, as we always have."
The Agency detectives immediately began to argue. Kaya exchanged a look with Teysa, who looked almost as disgusted as she did by the brewing dispute.
"If you'll excuse me," said Kaya, voice low and mild when what she wanted to do was scream. Teysa nodded, staying where she was as Kaya turned and stalked away, vanishing down the hall, leaving the squabbling parties to their fight.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The ballroom was largely deserted when Kaya arrived, save for a few servers still milling near the walls. It had never been intended as a center point of the gathering, more a retreat for those who wearied of the celebration and needed a moment away from the crowd. If she hadn't been escaping certain conversations by retreating to the private balcony, she would have been here when Zegana's body was discovered.
The grand balcony where the guests of honor had been acknowledged ran all the way along one wall of the ballroom, tall glass doors standing open. The sky outside no longer lit up with colored fire, and the sounds drifting from below were very different from the unfettered celebration that had been going on when first she went inside. Walking to the edge, she looked down to see the partygoers standing in long, looping lines, each one ending at a member of the Senate and a glowing verity circle. They had cast their spells with admirable speed, making Kaya wonder if they hadn't been preparing for something to go wrong tonight. Boros legionnaires stood near the casting mages, protecting them from interference.
#figure(image("002_Episode 2: Monsters We Became/02.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
It would be just like the Azorius and the Boros to come to a party intended to honor the Agency prepared to step in and prevent, as Aurelia put it, "amateur detective work." She didn't believe the Senate would have started a problem if one hadn't presented itself, but now that they had the chance, they were eager to prove that they were still the law on Ravnica. Nothing ever really changed. The whole plane could have fallen, and the guilds were still desperate to hold onto their authority.
And it didn't take a genius to look at the guest list for tonight's celebration and see that trouble was all but guaranteed. With eight of the ten guilds represented—she hadn't seen anyone from House Dimir, and the Golgari Swarm was similarly absent—the chances of rough edges scraping against one another were incredibly high. She frowned, scanning the crowd again. Eight of the ten … but she hadn't seen many Rakdos tonight, had she? Only Judith, glaringly visible in her black and red leathers.
Judith, who had vanished before the killing.
Troubled, Kaya turned away from the crowd, heading back toward the people she'd left behind in the hall. Whether the Azorius had orchestrated their role in this or not, their verity circles would prove the guilt or innocence of the attendees in short order. Some of the Boros legionnaires supporting the lawmages had been holding sheets of paper she assumed were the official guest lists. They wouldn't miss anyone.
When she reached the hall, only Ezrim remained, his front talons folded in front of him and his narrowed eyes fixed on the coatroom door. He huffed frustrated amusement at Kaya's return.
"Everyone in there?" she asked.
"Teysa led Vannifar to a private room to take a glass of kasarda and compose herself," he said. "One of my people accompanied them, to be sure they're never left alone. The other servants have gone to assist with securing the property and rounding up the guests for questioning. My people are investigating the scene."
"I'll let you know what's going on," Kaya said and slipped into the room.
Barrier wards had been deployed inside the scene, forming lines of protective magic impenetrable to anyone but an authorized investigator. The Agency detectives who were already inside were clustered in one corner, all of them looking frustrated and annoyed. Kellan was virtually vibrating with the desire to help the various Azorius members as they tore the room apart, searching every crack and crevice for clues of what had happened here. Kaya winced. Teysa was going to kill them for what they'd done to her wallpaper.
Only Zegana's corpse, still in orchestrated repose on her bed of coats, remained untouched, the black iris caged in her palm, her hair spread out around her head like a fanned-out fin.
"While your willingness to help is appreciated, we don't need Orzhov assistance," said Aurelia, snapping Kaya out of her brief study of the corpse. "We'll find the killer."
"I saw the verity circles lighting up in the courtyard below," said Kaya. "With that sort of speed and efficacy, it might seem like the Azorius were planning for trouble."
"A party at <NAME>or, with all the guilds invited to celebrate the Agency and a Planeswalker?" Aurelia's lip curled. "The invitations might as well have said 'trouble guaranteed.' Guilds Azorius and Boros both came ready for something to need our attentions."
A woman with the Azorius crest on her sleeve pushed past Kaya to Aurelia, bowing her head as she waited for acknowledgment from her superior.
"What is it?" asked Aurelia.
"Warleader, with the exception of the people in this room, guildmasters Teysa and Vannifar, and Chief Ezrim, everyone has been questioned," said the Azorius, anxiously. "Even Grand Arbiter Lavinia has allowed herself to be interrogated. She sent me to ask you to agree to the same. We must all be above reproach."
"Can you cast a verity circle?" asked Aurelia.
Swallowing hard, the young Azorius nodded.
"Good. Then question us, and leave us to our investigation."
The woman stepped back, almost stumbling, and lifted her hands, murmuring the incantation to call her circle into existence. It snapped up around both Kaya and Aurelia, something for which Kaya was obscurely grateful. With a guildmaster inside the circle, hopefully the questions would be restricted to ones that were relevant to the situation. It would have been all too easy for a lawmage who had suffered personal losses in the invasion to ask a few more … personal questions before allowing the circle to dispel. The verity circle couldn't compel speech, but someone who was caught off guard might say more than they intended.
The young guildmage seemed determined to demonstrate the evenhanded fairness that was the hallmark of the Senate. Her questions were quick, precise, and calm. Had either of them done harm to Zegana, either directly or indirectly? No. Had either of them killed her? No. Did either of them know who had? No. Did either of them have suspicion of who might have done so?
Kaya managed to swallow Judith's name, telling herself that her curiosity didn't rise to the level of suspicion.
The Azorius dropped the circle. "With your permission, Legionnaire, I'll speak to the investigators?"
"Yes, yes," said Aurelia, waving her off to begin casting her verity circles on the other occupants of the room.
Kaya, meanwhile, was staring at Aurelia. "All that noise about letting the professionals handle things, and you don't have #emph[any] suspicions?"
Aurelia turned away. "Azorius is handling the investigation, not Boros. I'm just here to keep order, at Lavinia's request, since she can't be in two places at once, and would much rather be searching for answers than supervising someone else."
"Your guilds #emph[did] plan this," said Kaya, suspicions confirmed by Aurelia's easy acceptance of her role here.
"Were you away from Ravnica so long that you forgot how things work?" asked Aurelia, looking back to her with one eyebrow raised. "There have been changes, yes, but the core of the city remains as it has always been, as it will always be. The Azorius keep the law; the Boros enforce it. A group of amateurs playing at protection will never displace us."
Kaya glared. "The guilds aren't everything."
"Did you feel that way when you led the Orzhov? If you did, it's no wonder they replaced you at the first opportunity. The guilds #emph[are] Ravnica."
"Well, then, Ravnica, do you have any idea what happened here? Or are you as clueless as the rest of us?"
Before Aurelia could answer, someone behind the pair cleared their throat. Both women turned. A human man stood in the doorway, skin a few shades lighter than Kaya's, hair dark on top but graying at the temples, dressed in a long azure coat. A few of the Azorius who had already been released from the verity circles shot him sour looks. He paid them no mind, attention fixed on Kaya and Aurelia.
"I believe I may have some idea of what happened here," he said, as calmly as if he were requesting a cup of tea.
"You would be …?" asked Kaya.
"Ah. Yes. I see how that might sound." He stepped into the room, studying Zegana's remains. "Fear not. I have already allowed myself to be interviewed via verity circle. I'm not your killer. I may, however, be your savior."
#figure(image("002_Episode 2: Monsters We Became/03.png.jpg", width: 100%), caption: [Art by: <NAME>awan], supplement: none, numbering: none)
"#emph[He] didn't have an invitation," said the Azorius mage who had been casting the verity circles, her tone tight and unhappy. "I would have noticed his name on the list."
"And what name is that?" asked Kaya. She was getting frustrated. This was no time for games.
"I'm sorry. Did I not say? I'm Alquist Proft. Some people call me 'the great detective Proft,' and I have some skill in this arena." He moved closer to Zegana's body and crouched low to the floor, his eyes flicking rapidly from one aspect of the scene to the next. For all their apparent discomfort, none of the Azorius members in the room objected, while the Agency detectives who had been waiting for the opportunity to assist visibly relaxed, clearly trusting the man. Kaya looked at him with new interest.
"Has anyone touched the body or its surroundings?" he asked.
"No," said Aurelia.
"In that case … including the flower in her hand, which we can interpret as being representative of the Simic in this specific instance, she has been arranged such that the sign of each guild is visible on the coats beneath her, and a pattern has been formed."
"What do you mean?" asked Kaya.
"Come here," he said, beckoning her closer without rising from his position. Kaya obliged, too intrigued to object to his high-handed summons.
Once she had stopped beside him, Proft straightened, indicating the body and its surroundings with a sweep of one hand. "Look closely. What do you see?"
"Zegana, and coats," said Kaya dutifully, searching for the pattern Proft had mentioned. Then she blinked, shifting to the side to get a different angle. No matter how she stood, the Dimir logo failed to appear. "I don't see Dimir," she said. "But there aren't any Dimir in attendance, so that makes sense."
"This design incorporates all ten guild seals," said Proft, indicating a panel pattern which occurred, in various degrees of folded-over, on several of the coats. "The Golgari are likewise absent from the invite list, but their seal is visible several times—see the way these buckles form the mandibles? I would wager that, if you move her hand, a folded pattern greatly resembling the Dimir seal will have been covered by the position of her arm."
Kaya shook her head. "That's a lot of trouble to go through. I can't believe I didn't see that," she said.
"You've also failed to spot the one member of House Dimir in attendance."
Kaya startled, ready to object, only to find Proft already looking at her with an earnest lack of judgment. He wasn't criticizing: he was describing the situation as he saw it.
"Who?" she asked.
Proft smiled.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Convincing Aurelia to stay behind hadn't been difficult, especially not once Ezrim rose and reminded her that she had been the one who wanted to take ownership of the scene. At least now she was allowing the other Agency detectives to do their jobs, Proft's revelation having shamed her into accepting their usefulness, however grudgingly. Teysa and Vannifar had yet to put in a return appearance, and while all the guests knew that #emph[something] was happening by this point, there was no reason for them to suspect murder.
Although Proft had somehow suspected and followed his suspicions back to their source. Kaya eyed him speculatively as they descended the stairs to the main floor. He didn't seem to notice. She wasn't fooled. Only a few minutes with him had been enough to illustrate that he noticed everything, however small or inconsequential it might seem.
"The verity circles were cast and checked according to the guest list," said Proft, abruptly. "If someone failed to appear on the list and evaded the circles with care, they could easily escape questioning. If it were someone who had good reason not to want to be questioned under conditions of absolute truth—say, a Dimir spy and known assassin—it would be simple to exploit the gaps in our investigation until the gates are unlocked. Honestly, the only thing I don't understand is why the individual in question lingered long enough to be caught by the lockdown. She's far too skilled for that."
"Where is she?" asked Kaya. "I didn't see anyone wearing Dimir colors."
"Did you really think a Dimir agent would make their presence so apparent? I might not have seen her, had she not been taking such exquisite care to avoid interaction with members of the Selesnya Conclave. Given that she was wearing the colors of their guild, they should have been her closest companions, not a reason to step aside."
"Oh," said Kaya, scanning the crowd with new eyes. She had fallen so quickly back into the Ravnican way of thinking, where no one would wear the colors of a guild they weren't affiliated with unless they were looking for trouble. Members of the Conclave were scattered through the crowd, milling as purposelessly as the other guests who had been questioned but not released.
At the base of the stairs, Proft looked around, nodded to himself, and struck out across the party, heading for the fringes, where the lowest-ranking guild members had naturally assembled. Kaya followed closely, watching the crowd as she tried to see whatever it was that he saw, whatever intangible trail he was so intent on following.
As they reached the edge of the crowd, Proft motioned for Kaya to step back, then continued onward on his own, moving until a dark-skinned woman in Selesnya green and white was standing almost exactly between them. Her gown was perfectly tailored, fitted precisely to her form, and a beautiful exemplar of the season's fashions; there was no reason for her to have caught anyone's eye apart from admiration or envy.
No reason, save for the lack of any guild logo visible on her person. It was a jarring omission, given the precision of the rest of her attire. #emph[Makes sense] , Kaya thought. There were no laws against wearing another guild's colors. Wearing their shield, on the other hand, could come with consequences.
"Miss Etrata," said Proft, taking a step toward the woman. "I'm afraid we need to speak with you. Please come with me now."
#figure(image("002_Episode 2: Monsters We Became/04.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
The woman whipped around, lips drawing back in a hiss which revealed her impressive vampiric incisors. Her entire demeanor changed in that instant, going from bored socialite to cornered predator. Casting a glance at Kaya, she clearly marked the Planeswalker as the greater threat. Charging straight for Proft, she knocked the investigator to the ground and began to cut a straight line through the crowd, heading for the hedge maze.
"If she gets in there, we'll never find her!" shouted Kaya, already turning to give chase.
"Try not to lose sight of her—I'll do what I can to help from here," said Proft, pushing himself into a sitting position without rising from the ground.
Kaya was fast. Etrata, however, was faster, and that, in addition to her head start, put her more than halfway to the hedge maze when Kaya began gaining ground, largely by dint of turning herself intangible to avoid dodging around partygoers. Charging straight through them was more efficient.
Still, Etrata was going to beat her to the maze, no question—at least until the world abruptly inverted itself around her, gray cobblestone and gathered revelers being replaced by columns of towering blue light. They were no longer racing toward the hedge maze: instead, Etrata was running down an alleyway that Kaya knew all too well, deep in the heart of Orzhov territory.
The magic, wherever it was coming from, didn't feel malicious or like an elaborate attempt to trick her. In fact, based on the way Etrata was slowing and looking frantically around, scanning the surrounding buildings for a way out, this was helping Kaya more than anything else. She put on another burst of speed, pushing herself to her physical limits. In the sudden silence, her footsteps echoed like rocks dropped into still water. Etrata glanced backward over her shoulder before making an abrupt left turn into what Kaya knew was a dead-end alley.
#figure(image("002_Episode 2: Monsters We Became/05.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
She was within ten feet of the vampire when the white landscape collapsed around them and Etrata plowed directly into Kellan. The young Agency investigator looked surprised, even with clasped arms around the runaway Dimir. She struggled and snarled, but he shook his head, not letting go. He was still holding her when Kaya ran up to the pair of them.
"What was #emph[that] ?" she asked.
"That was me," said a winded voice, from behind her. She turned. Proft, clearly exhausted but back up on his feet, was staggering through the semi-dispersed crowd to join them. A further look told her he wasn't injured, just exhausted.
"What kind of magic is that?"
"I make what's in here become out there, and I can recreate anything I've ever seen,'" he said, tapping his temple as he looked past her to where Etrata struggled to escape from Kellan. "Everything all right, young man?"
"Absolutely, sir," said Kellan. "Thank you for helping us apprehend this miscreant."
Members of the Azorius guild were already beginning to converge on their position, with Lavinia at the lead of the largest cluster. Kellan tightened his grip, jaw jutting out briefly in stubborn determination. Proft stepped forward, setting a hand gently on his arm.
"This is not the time to stand our ground," he said. "They found nothing; we found a possible culprit. They didn't assist in the chase; you captured her. The Agency doesn't need the glory if we can have the satisfaction of knowing that without us, none of this would have been possible."
Kellan nodded, grudgingly. Lavinia drew close enough to speak.
"Remand the suspect to Azorius custody at once," she said, voice ringing over the courtyard.
Kellan released Etrata, standing next to Kaya and Proft as she was swiftly apprehended again by the waiting Azorius. The three of them remained where they were, watching as Etrata was hauled away.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.