repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/pascalguttmann/typst-template-report-lab
https://raw.githubusercontent.com/pascalguttmann/typst-template-report-lab/main/template/main.typ
typst
MIT License
#import "template-report-lab.typ": conf, date #show: doc => conf( title: [ The Title ], authors: ( ( name: "<NAME>", affiliation: "276035", ), ( name: "<NAME>", affiliation: "275358", ), ), group: 1.1, course: "Smart Systems", lecture: "Optical Systems Laboratory", semester: 2, date: date, appendix: include("./chapter/appendix.typ"), doc, ) #include("./chapter/introduction.typ") #include("./chapter/theory.typ") #include("./chapter/instruments.typ") #include("./chapter/results.typ") #include("./chapter/evaluation.typ") #include("./chapter/summary.typ")
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fauve-cdb/0.1.0/README.md
markdown
Apache License 2.0
# PhD manuscript template - Collège doctoral de Bretagne Typst template for doctoral dissertations of the French [Collège doctoral de Bretagne (CdB)](https://www.doctorat-bretagne.fr/). The original LaTeX template can be found [here](https://gitlab.com/ed-matisse/latex-template). # Usage You can use this template in the Typst web app by clicking "Start from template" on the dashboard and searching for `fauve-cdb`. Alternatively, you can use the CLI to kick this project off using the command ``` typst init @preview/fauve-cdb ``` Typst will create a new directory with all the files needed to get you started. # Note The original LaTeX template allows selecting different themes corresponding to different schools of the CdB. For now, we only implemented the [MATISSE](https://ed-matisse.doctorat-bretagne.fr) theme. > Fauve is an artistic movement of which French painter [Henri Matisse](https://en.wikipedia.org/wiki/Henri_Matisse) was a leader.
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/intermediate/content-stateful.typ
typst
Apache License 2.0
#import "mod.typ": * #show: book.page.with(title: "维护和查询文档状态") 在上一节中我们理解了作用域,也知道如何简单把「`show`」规则应用于文档中的部分内容。 它看起来似乎已经足够强大。但还有一种可能,Typst可以给你更强大的原语。 我是说有一种可能,Typst对文档内容的理解至少是二维的。这二维,有一维可以比作空间,另一维可以比作时间。你可以从文档的任意位置, + 空间维度(From Space to Space):查询文档任意部分的状态(这里的内容和那里的内容)。 + 时间维度(From TimeLoc to TimeLoc):查询文档任意脚本位置的状态(过去的状态和未来的状态)。 这里有一个示意图,红色线段表示Typst脚本的执行方向。最后我们形成了一个由S1到S4的“时间线”。 你可以选择文档中的任意位置,例如你可以在文档的某个位置(蓝色弧线的起始位置),从该处开始查询文档过去某处或未来某处(蓝色弧线的终止位置)。 // I mean, Typst maintains states with at least two dimensions. The one resembles a space dimension, and the other one resembles a time dimension. You can create a state that spans: // 1. From space to space: You can locate content at here and there by selectors. // 2. From time to time: You can query a state in past or future by locations. // The following figure shows how a state is arranged. First, Typst executes the document with scripting from S1 to S4, as #text(fill: red, "red lines") shown. Then, you can locate some content in the document (at the _start position_ of #text(fill: blue, "blue arcs")) and query the past state or future state (at the _end position_ of #text(fill: blue, "blue arcs")). #import "./figure-time-travel.typ": figure-time-travel #align(center + horizon, figure-time-travel()) // This section mainly talks about `selector` and `state` step by step, to teach how to locate content, create and manipulate states. 本节教你使用选择器(selector)定位到文档的任意部分;也教你创建与查询二维文档状态(state)。 == 自定义标题样式 本节讲解的程序是如何在Typst中设置标题样式。我们的目标是: + 为每级标题单独设置样式。 + 设置标题为内容的页眉: + 如果当前页眉有二级标题,则是当前页面的第一个二级标题。 + 否则是之前所有页面的最后一个二级标题。 效果如下: #frames-cjk( read("./stateful/s1.typ"), code-as: ```typ #show: set-heading == 雨滴书v0.1.2 === KiraKira 样式改进 feat: 改进了样式。 === FuwaFuwa 脚本改进 feat: 改进了脚本。 == 雨滴书v0.1.1 refactor: 移除了LaTeX。 feat: 删除了一个多余的文件夹。 == 雨滴书v0.1.0 feat: 新建了两个文件夹。 ```, ) == 「样式化」内容 当我们有一个`repr`玩具的时候,总想着对着各种各样的对象使用`repr`。我们在上一节讲解了「`set`」和「`show`」语法。现在让我们稍微深挖一些。 「`set`」是什么,`repr`一下: #code(```typ #repr({ [a] set text(fill: blue) [b] }) ```) 「`show`」是什么,`repr`一下: #code(```typ #repr({ [d] show raw: content => { [c] set text(fill: red) content } [a] `b` }) ```) 我们知道`set text(fill: blue)`是`show: set text(fill: blue)`的简写,因此「`set`」语法和「`show`」语法都可以统合到第二个例子来理解。 对于第二个例子,我们发现`show`语句之后的内容都被重新包裹在`styled`元素中。虽然我们不知道`styled`做了什么事情,但是简单的事实是: #code(```typ 该元素的类型是:#type({show: set text(fill: blue)}) \ 该元素的构造函数是:#({show: set text(fill: blue)}).func() ```) 原来,你也是内容。从图中,我们可以看到被`show`过的内容会被封装成「样式化」内容,即图中构造函数为`styled`的内容。 关于`styled`的知识便涉及到Typst的核心架构。 == 「`eval`阶段」与「`typeset`阶段」 现在我们介绍Typst的完整架构。 当Typst接受到一个编译请求时,他会使用「解析器」(Parser)从`main`文件开始解析整个项目;对于每个文件,Typst使用「评估器」(Evaluator)执行脚本并得到「内容」;对于每个「内容」,Typst使用「排版引擎」(Typesetting Engine)计算布局与合成样式。 当一切布局与样式都计算好后,Typst将最终结果导出为各种格式的文件,例如PDF格式。 如下图所示,Typst大致上分为四个执行阶段。这四个执行阶段并不完全相互独立,但有明显的先后顺序: #import "../figures.typ": figure-typst-arch #align(center + horizon, figure-typst-arch()) 这里,我们着重讲解“内容评估”阶段与“内容排版”阶段。 事实上,Typst直接在脚本中提供了对应“内容评估”阶段的函数,它就是我们之前已经介绍过的函数`eval`。你可以使用`eval`函数,将一个字符串对象「评估」为「内容」: #code(```typ 以代码模式评估:#eval("repr(str(1 + 1))") \ 以标记模式评估:#eval("repr(str(1 + 1))", mode: "markup") \ 以标记模式评估2:#eval("#show: it => [c] + it + [t];a", mode: "markup") ```) 由于技术原因,Typst并不提供对应“内容排版”阶段的函数,如果有的话这个函数的名称应该为`typeset`。已经有很多迹象表明`typeset`可能产生: + #link("https://github.com/andreasKroepelin/polylux")[Polylux], #link("https://github.com/touying-typ/touying")[Touying]等演示文档(PPT)框架需要将一部分内容固定为特定结果的能力。 + Typst的作者在其博客中提及#link("https://laurmaedje.github.io/posts/frozen-state/")[Frozen State ]的可能性。 + 他提及数学公式的编号在演示文档框架。 + 即便不涉及用户需求,Typst的排版引擎已经自然存在Frozen State的需求。 + 本文档也需要`typeset`的能力为你展示特定页面的最终结果而不影响全局状态。 在Typst的源代码中,有一个Rust函数直接对应整个编译流程,其内容非常简短,便是调用了两个阶段对应的函数。“内容评估”阶段(`eval`阶段)对应执行一个Rust函数,它的名称为`typst::eval`;“内容排版”阶段(`typeset`阶段)对应执行另一个Rust函数,它的名称为`typst::typeset`。 ```rs pub fn compile(world: &dyn World) -> SourceResult<Document> { // Try to evaluate the source file into a module. let module = crate::eval::eval(world, &world.main())?; // Typeset the module's content, relayouting until convergence. typeset(world, &module.content()) } ``` 从代码逻辑上来看,它有明显的先后顺序,似乎与我们所展示的架构略有不同。其`typst::eval`的输出为一个文件模块`module`;其`typst::typeset`仅接受文件的内容`module.content()`并产生一个已经排版好的文档对象`typst::Document`。 与架构图对比来看,架构图中还有两个关键的反向箭头,疑问顿生:这两个反向箭头是如何产生的? 我们首先关注与本节直接相关的「样式化」内容。当`eval`阶段结束时,「`show`」语法将会对应产生一个`styled`元素,其包含了被设置样式的内容,以及设置样式的「回调」: #code(```typ 内容是:#repr({show: set text(fill: blue); [abc]}) \ 样式无法描述,但它在这里:#repr({show: set text(fill: blue); [abc]}.styles) ```) 也就是说`eval`并不具备任何排版能力,它只能为排版准备好各种“素材”,并把素材交给排版引擎完成排版。 这里的「回调」术语很关键:它是一个计算机术语。所谓「回调函数」就是一个临时的函数,它会在后续执行过程的合适时机“回过头来被调用”。例如,我们写了一个这样的「`show`」规则: #code(```typ #repr({ show raw: content => layout(parent => if parent.width > 100pt { set text(fill: red); content } else { content }) `a` }) ```) 这里`parent.width > 100pt`是说当且仅当父元素的宽度大于`100pt`时,才为该代码片段设置红色字体样式。其中,`parent.width`与排版相关。那么,自然`eval`也不知道该如何评估该条件的真正结果。*计算因此被停滞*。 于是,`eval`干脆将整个`show`右侧的函数都作为“素材”交给了排版引擎。当排版引擎计算好了相关内容,才回到评估阶段,执行这一小部分“素材”函数中的脚本,得到为正确的内容。我们可以看出,`show`右侧的函数*被延后执行*可。 这种被延后执行零次、一次或多次的函数便被称为「回调函数」。相关的计算方法也有对应的术语,被称为「延迟执行」。 我们对每个术语咬文嚼字一番,它们都很准确: 1. *「内容评估」*阶段仅仅“评估”出*「内容排版」*阶段所需的素材.*「评估器」*并不具备排版能力。 2. 对于依赖排版产生的内容,「内容评估」产生包含*「回调函数」*的内容,让「排版引擎」在合适的时机“回过头来调用”。 3. 相关的计算方法又被称为*「延迟执行」*。因为现在不具备执行条件,所以延迟到条件满足时才继续执行。 现在我们可以理解两个反向箭头是如何产生的了。它们是下一阶段的回调,用于完成阶段之间复杂的协作。评估阶段可能会`import`或`include`文件,这时候会重新让解析器解析文件的字符串内容。排版阶段也可能会继续根据`styled`等元素产生复杂的内容,这时候依靠评估器执行脚本并产生或改变内容。 我们来手动描述一遍上述示例的执行过程,以加深理解: #code(```typ #show raw: content => layout(parent => if parent.width < 100pt { set text(fill: red); content } else { content }) #box(width: 50pt, `a`) `b` ```) 首先进行内容评估得到: ```typ #styled((box(width: 50pt, `a`), `b`), styles: content => ..) ``` 排版引擎遇到``` `a` ```。由于``` `a` ```是`raw`元素,它「回调」了对应`show`规则右侧的函数。待执行的代码如下: ```typc layout(parent => if parent.width < 100pt { set text(fill: red); `a` } else { `a` }) ``` 此时`parent`即为`box(width: 50pt)`。排版引擎将这个`parent`的具体内容交给「评估器」,待执行的代码如下: ```typc if box(width: 50pt).width < 100pt { set text(fill: red); `a` } else { `a` } ``` 由于此时父元素(`box`元素)宽度只有`50pt`,评估器进入了`then`分支,其为代码片段设置了红色样式。内容变为: ```typ #(box(width: 50pt, {set text(fill: red); `a`}), styled((`b`, ), styles: content => ..)) ``` 待执行的代码如下: ```typc set text(fill: red); text("a", font: "monospace") ``` 排版引擎遇到``` `a` ```中的`text`元素。由于其是`text`元素,「回调」了`text`元素的「`show`」规则。记得我们之前说过`set`是一种特殊的`show`,于是排版器执行了`set text(fill: red)`。 ```typ #(box(width: 50pt, text(fill: red, "a", ..)), styled((`b`, ), styles: content => ..)) ``` 排版引擎离开了`show`规则右侧的函数,该函数调用由``` `a` ```触发。同时`set text(fill: red)`规则也被解除,因为离开了相关作用域。 回到文档顶层,待执行的代码如下: ```typc #show raw: ... `b` ``` 排版引擎遇到``` `b` ```,再度「回调」了对应`show`规则右侧的函数。由于此时父元素(`page`元素,即整个页面)宽度有`500pt`,我们没有为代码片段设置样式。 ```typ #(box(width: 50pt, text(fill: red, "a", ..)), text("b", ..)) ``` 至此,文档的内容已经准备好「导出」(Export)了。 == 「样式化」内容的补充 有时候`show`规则会原地执行,这属于一种细节上的优化,例如: #code(```typ #repr({ show: it => it; [a] }) \ #repr({ show: it => [c] + it + [d]; [a] }) ```) 这个时候`show`规则不会对应一个`styled`元素。 这种优化告诉你前面手动描述的过程仅作理解。一旦涉及更复杂的环境,Typst的实际执行过程就会产生诸多变化。因此,你不应该依赖以上某步中排版引擎的瞬间状态。这些瞬间状态将产生「未注明特性」(undocumented details),并随时有可能在未来被打破。 == 「可定位」的内容 在过去的章节中,我们了解了评估结果的具体结构,也大致了解了排版引擎的工作方式。 接下来,我们介绍一类内容的「可定位」(Locatable)特征。你可以与前文中的「可折叠」(Foldable)特征对照理解。 一个内容是可定位的,如果它可以以某种方式被索引得到。 如果一个内容在代码块中,并未被使用,那么显然这种内容是不可定位的。 ```typ #{ let unused-content = [一段不可定位的内容]; } ``` 理论上文档中所有内容都是可定位的,但由于*性能限制*,Typst无法允许你定位文档中的所有内容。 我们已经学习过元素函数可以用来定位内容。如下: #code(````typ #show heading: set text(fill: blue) = 蓝色标题 段落中的内容保持为原色。 ````) 接下来我们继续学习更多选择器。 == 文本选择器 <grammar-text-selector> 你可以使用「字符串」或「正则表达式」(`regex`)匹配文本中的特定内容,例如为`c++`文本特别设置样式: #code(````typ #show "cpp": strong(emph(box("C++"))) 在古代,cpp是一门常用语言。 ````) 这与使用正则表达式的效果相同:<grammar-regex-selector> #code(````typ #show regex("cp{2}"): strong(emph(box("C++"))) 在古代,cpp是一门常用语言。 ````) 关于正则表达式的知识,推荐在#link("https://regex101.com")[Regex 101]中继续学习。 这里讲述一个关于`regex`选择器的重要知识。当文本被元素选中时,会创建一个不可见的分界,导致分界之间无法继续被正则匹配: #code(````typ #show "ab": set text(fill: blue) #show "a": set text(fill: red) ababababababa ````) 因为`"a"`规则比`"ab"`规则更早应用,每个`a`都被单独分隔,所以`"ab"`规则无法匹配到任何本文。 #code(````typ #show "a": set text(fill: red) #show "ab": set text(fill: blue) ababababababa ````) 虽然每个`ab`都被单独分隔,但是`"a"`规则可以继续在分界内继续匹配文本。 这个特征在设置文本的字体时需要特别注意: 为引号单独设置字体会导致错误的排版结果。因为句号与双引号之间产生了分界,使得Typst无法应用标点挤压规则: #code(````typ #show "”": it => { set text(font: "KaiTi") highlight(it, fill: yellow) } “无名,万物之始也;有名,万物之母也。” ````) 以下正则匹配也会导致句号与双引号之间产生分界,因为没有对两个标点进行贪婪匹配: #code(````typ #show regex("[”。]"): it => { set text(font: "KaiTi") highlight(it, fill: yellow) } “无名,万物之始也;有名,万物之母也。” ````) 以下正则匹配没有在句号与双引号之间创建分界。考虑两个标点的字体设置规则,Typst能排版出这句话的正确结果: #code(````typ #show regex("[”。]+"): it => { set text(font: "KaiTi") highlight(it, fill: yellow) } “无名,万物之始也;有名,万物之母也。” ````) == 标签选择器 <grammar-label-selector> 基本上,任何元素都包含文本。这使得你很难对一段话针对性排版应用排版规则。「标签」有助于改善这一点。标签是「内容」,由一对「尖括号」(`<`和`>`)包裹: #code(````typ 一句话 <some-label> ````) 「标签」可以选中恰好在它*之前*的一个内容。示例中,`<some-label>`选中了文本内容`一句话`。 也就是说,「标签」无法选中在它*之前*的多个内容。以下选择器选中了`#[]`后的一句话: #code(````typ #show <一句话>: set text(fill: blue) #[一句话。]还是一句话。 <一句话> 另一句话。 ````) 这是因为`#[一句话。]`被分隔为了单独的内容。 我们很难判断一段话中有多少个内容。因此为了可控性,我们可以使用内容块将一段话括起来,然后使用标签准确选中这一整段话: #code(````typ #show <一整段话>: set text(fill: blue) #[ $lambda$语言是世界上最好的语言。#[]还是一句话。 ] <一整段话> 另一段话。 ````) == 选择器表达式 <grammar-selector-exp> 任意「内容」可以使用「`where`」方法创建选中满足条件的选择器。 例如我们可以选中二级标题: #code(````typ #show heading.where(level: 2): set text(fill: blue) = 一级标题 == 二级标题 ````) 这里`heading`是一个元素,`heading.where`创建一个选择器: #code(````typ 选择器是:#repr(heading.where(level: 2)) \ 类型是:#type(heading.where(level: 2)) ````) 同理我们可以选中行内的代码片段而不选中代码块: #code(````typ #show raw.where(block:false): set text(fill: blue) `php`是世界上最好的语言。 ``` typst也是。 ``` ````) // == 「`numbering`」函数 // 略 == 回顾其一 针对特定的`feat`和`refactor`文本,我们使用`emph`修饰: #frames-cjk( read("./stateful/s2.typ"), code-as: ```typ #show regex("feat|refactor"): emph ```, ) 对于三级标题,我们将中文文本用下划线标记,同时将特定文本替换成emoji: #frames-cjk( read("./stateful/s3.typ"), code-as: ```typ #let set-heading(content) = { show heading.where(level: 3): it => { show regex("[\p{hani}\s]+"): underline it } show heading: it => { show regex("KiraKira"): box("★", baseline: -20%) show regex("FuwaFuwa"): box(text("🪄", size: 0.5em), baseline: -50%) it } content } #show: set-heading ```, ) == 制作页眉标题的两种方法 制作页眉标题至少有两种方法。一是直接查询文档内容;二是创建状态,利用布局迭代收敛的特性获得每个页面的首标题。 在接下来的两节中我们将分别介绍这两种方法。
https://github.com/qujihan/toydb-book
https://raw.githubusercontent.com/qujihan/toydb-book/main/src/chapter2.typ
typst
#import "../typst-book-template/book.typ": * #let path-prefix = figure-root-path + "src/pics/" = 存储引擎 #include "chapter2/intro.typ" #include "chapter2/engine.typ" #include "chapter2/bitcask.typ" #include "chapter2/memory.typ" #include "chapter2/mvcc.typ" #include "chapter2/summary.typ"
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/valkyrie/0.2.0/src/types/array.typ
typst
Apache License 2.0
#import "../base-type.typ": base-type #import "../assertions-util.typ": assert-base-type #import "../ctx.typ": z-ctx #let array-type = type(()) #let array( name: "array", ..args, ) = { let descendents-schema = args.pos().at(0, default: base-type(name: "any")) assert-base-type(descendents-schema, scope: ("arguments",)) base-type( name: "array[" + (descendents-schema.name) + "]", default: (), types: (array-type,), ..args.named(), ) + ( descendents-schema: descendents-schema, handle-descendents: (self, it, ctx: z-ctx(), scope: ()) => { for (key, value) in it.enumerate() { it.at(key) = (descendents-schema.validate)( descendents-schema, value, ctx: ctx, scope: (..scope, str(key)), ) } it }, ) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-17000.typ
typst
Apache License 2.0
#let data = ( "0": ("<Tangut Ideograph, First>", "Lo", 0), "17f7": ("<Tangut Ideograph, Last>", "Lo", 0), )
https://github.com/sebmestrallet/typst-simple-siam
https://raw.githubusercontent.com/sebmestrallet/typst-simple-siam/main/src/lib.typ
typst
MIT No Attribution
#import "@preview/ctheorems:1.1.2": * #let theorem = thmbox( "theorem", "Theorem", supplement: "Thm.", inset: 0pt, titlefmt: title => [#smallcaps(title)], bodyfmt: body => [_ #body _], ) #let definition = thmbox( "definition", "Definition", supplement: "Def.", inset: 0pt, titlefmt: title => [#smallcaps(title)], bodyfmt: body => [#body], ) #let lemma = thmbox( "lemma", "Lemma", supplement: "Lem.", inset: 0pt, titlefmt: title => [#smallcaps(title)], bodyfmt: body => [_ #body _], ) #let proof(body) = block[ _Proof._ #body #h(2em) #sym.rect.v ] // Reference figures with just "Fig."... #set figure(numbering: "1", supplement: "Fig.") // ...but display the full word "Figure" in the figure caption // (`Figure` instead of `#it.supplement` below) #show figure.caption : it => [Figure #it.counter.display(it.numbering)#it.separator#it.body] #import "@preview/lovelace:0.3.0": * // Thanks @Julian-Wassmann https://github.com/typst/typst/discussions/2280#discussioncomment-7612699 // Use (2.3) for the global 3rd algorithm, in the 2nd section #let customAlgoNumbering(n, loc) = { let level1HeadingNumber = counter(heading).at(loc).at(0) let headingNumbering = numbering("1", level1HeadingNumber) let algorithmNumbering = numbering("1", n) text(weight: "thin")[#headingNumbering.#algorithmNumbering] // "thin" seems to cancel out a hard-coded bold formatting somewhere... } #let ALGO_SUPPLEMENT = smallcaps(text(weight: "thin")[Algorithm]) // "thin" seems to cancel out a hard-coded bold formatting somewhere... // outside conf() to be imported in main.typ #let algorithm(body) = figure( kind: "algorithm", supplement: ALGO_SUPPLEMENT, numbering: n => locate(loc => { customAlgoNumbering(n, loc) }), box[ #body ] ) #let conf( title: none, authors: none, abstract: none, doc ) = { set page( paper: "us-letter", margin: 0.85in, footer: align( right + top, text(size: 7pt)[ // https://www.sascha-frank.com/latex-font-size.html for `\scriptsize` & the `article` documentclass Copyright © 2025 by SIAM\ Unauthorized reproduction of this article is prohibited ] ) ) set par(justify: true) // sadly, `par` does not have a `all-but-first-line-indent` parameter set text( font: "New Computer Modern", size: 9pt, ) set footnote(numbering: "*") set footnote.entry( separator: line(length: 3em, stroke: 0.5pt) ) align(center)[ #v(0.7in) // increase top margin on the first page #text( size: 14pt, // https://www.sascha-frank.com/latex-font-size.html for `\Large` & the `article` documentclass title ) #text( size: 11pt, )[ #if type(authors) == str or type(authors) == content { authors } else if type(authors) == array { // from https://typst.app/docs/tutorial/making-a-template/ let count = authors.len() let ncols = calc.min(count, 3) grid( columns: ncols, column-gutter: 50pt, row-gutter: 24pt, ..authors.map(author => [ #author.name#footnote(author.affiliation) ]), ) } else { panic(str(type(authors)) + " is not a valid type for authors") } ] #v(1em) ] set footnote(numbering: "1") set heading(numbering: "1.1") let SPACE_BETWEEN_HEADING_AND_ITS_NUMBER = 0.7em show heading.where(level: 1): header => { set text(size: 9pt, weight: "bold") block(breakable: false)[ // No number in front of "References" // thanks @laurmaedje https://github.com/typst/typst/discussions/1055#discussioncomment-5770540 #if header.numbering != none [ #counter(heading).display() #h(SPACE_BETWEEN_HEADING_AND_ITS_NUMBER) ] #header.body #v(0.5em) ] } show heading.where(level: 2): header => { set text(size: 9pt, weight: "bold") let number = context counter(heading).display() box[ #number #h(SPACE_BETWEEN_HEADING_AND_ITS_NUMBER) #header.body ] // a box and not a block, to be able to write text on the same line } show heading.where(level: 3): header => { set text(size: 9pt, weight: "bold") let number = context counter(heading).display() box[ #number #h(SPACE_BETWEEN_HEADING_AND_ITS_NUMBER) #header.body ] // a box and not a block, to be able to write text on the same line } // Thanks @Julian-Wassmann https://github.com/typst/typst/discussions/2280#discussioncomment-7612699 // Use (2.3) for the global 3rd equation, in the 2nd section let customEqNumbering(n, loc) = { let level1HeadingNumber = counter(heading).at(loc).at(0) let headingNumbering = numbering("1", level1HeadingNumber) let equationNumbering = numbering("1", n) [(#headingNumbering.#equationNumbering)] } set math.equation( numbering: n => locate(loc => { customEqNumbering(n, loc) }), supplement: "Eq.", number-align: left ) show: thmrules show ref: it => { let el = it.element if el != none and el.func() == math.equation { // Override equation references. let loc = el.location() let n = counter(math.equation).at(loc).first() customEqNumbering(n, loc) } else if el != none and el.func() == figure { let fig = el.func() // strangely, fig.kind is auto, not "figure" or "algorithm" if el.supplement == ALGO_SUPPLEMENT { // Override algorithm references. let loc = el.location() let n = counter(figure.where(kind: algorithm)).at(loc).first()+1 "Algorithm " + customAlgoNumbering(n, loc) } else { // Reference of other kinds of figures as usual. it } } else { // Other references as usual. it } } columns( 2, gutter: 10pt )[ #block(breakable: false)[ #text(weight: "bold")[Abstract] ] #abstract #doc ] }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/matrix_04.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test alternative math delimiter directly in call. #set align(center) #grid( columns: 3, gutter: 10pt, $ mat(1, 2, delim: "[") $, $ mat(1, 2; delim: "[") $, $ mat(delim: "[", 1, 2) $, $ mat(1; 2; delim: "[") $, $ mat(1; delim: "[", 2) $, $ mat(delim: "[", 1; 2) $, $ mat(1, 2; delim: "[", 3, 4) $, $ mat(delim: "[", 1, 2; 3, 4) $, $ mat(1, 2; 3, 4; delim: "[") $, )
https://github.com/Vortezz/fiches-mp2i-physique
https://raw.githubusercontent.com/Vortezz/fiches-mp2i-physique/main/tp/linear_regression.typ
typst
#import "@preview/cetz:0.0.1" #set page(header: box(width: 100%, grid( columns: (100%), rows: (20pt, 8pt), align(right, text("FICHE TP - RÉGRESSION LINÉAIRE")), line(length: 100%), )), footer: box(width: 100%, grid( columns: (50%, 50%), rows: (8pt, 20pt), line(length: 100%), line(length: 100%), align(left, text("<NAME> - MP2I")), align(right, text("<NAME> - 2023/2024")), ))) #set heading(numbering: "I.1.a") #let titleBox(title) = align(center, block(below: 20pt, box(height: auto, fill: rgb("#eeeeee"), width: auto, inset: 40pt, text(title, size: 20pt, weight: "bold")))) #let proof(content) = text("Preuve", weight: "semibold", fill: rgb("#666666")) + h(1em) + text(content, size: 10pt, fill: rgb("#888888")) #titleBox("Régression linéaire") = Explication La régression linéaire consiste à établir une relation linéaire entre une variable dépendante $y$ et une ou plusieurs variables indépendantes $x_1, dots, x_n$. Pour cela, on utilise Python et les bibliothèques `numpy` et `matplotlib`. = Comment faire? == Importer les bibliothèques Pour importer les bibliothèques, on utilise la commande `import`. ```python import numpy as np import matplotlib.pyplot as plt ``` == Créer les données On considère les listes $X$ et $Y$ suivantes (ces données sont fictives et sont normalement issues d'une expérience réelle) : ```python X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Y = [1, 2.4, 3.6, 4.8, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5] ``` == Tracer le nuage de points En physique on ne relie jamais des points expérimentaux par des segments, mais on trace un nuage de points. Pour cela, on utilise la commande `plt.plot` avec `o` comme forme. ```python plt.plot(X, Y, "o") plt.label("X (unité)") plt.ylabel("Y (unité)") plt.show() ``` == Réaliser la régression linéaire Pour réaliser la régression linéaire, on utilise la commande `np.polyfit` qui prend en argument les listes $X$ et $Y$ ainsi que le degré du polynôme (ici 1 car on veut une droite). ```python a, b = np.polyfit(X, Y, 1) ``` == Tracer la droite de régression Pour tracer la droite de régression, on utilise la commande `plt.plot` avec `--` comme forme. Pour avoir des valeurs régulières en abscisse, on utilise la commande `np.linspace` qui prend en argument la valeur minimale, la valeur maximale et le nombre de valeurs voulues dans l'intervalle. ```python # Si on veut laisser les points expérimentaux on utilise la commande suivante plt.plot(X, Y, "o") # Tracé de la droite de régression list_x = np.linspace(min(X), max(X), 100) # 100 valeurs entre min(X) et max(X) plt.plot(list_x, a * np.array(X) + b, "--") plt.xlabel("X (unité)") plt.ylabel("Y (unité)") plt.show() ``` Il est ensuite possible de récupérer les coefficients de la droite de régression avec `a` et `b` et de les afficher. ```python print("a = ", a) print("b = ", b) ``` Il est bien sûr aussi possible de les récupérer de manière géométrique avec une règle.
https://github.com/dismint/docmint
https://raw.githubusercontent.com/dismint/docmint/main/biology/lec2.typ
typst
#import "template.typ": * #show: template.with( title: "Lecture 2", subtitle: "7.016" ) = Introduction Most of chemistry happens in an aqueous environment since 75% of cells are water. #define( title: "Biomolecular Interactions" )[ / Specificity: One on one interactions / Diversity: Many possible interactions that can combine in many ways ] For the most part, Sulfur copies Oxygen. However, it is not the case that Phosphorus behaves the same as Nitrogen, in fact it can form five bonds which makes it unique. #define( title: "Ester" )[ An ester bond is when you have an element that is double bonded to one Oxygen and single bonded to another. If we have two of these, for example an element double bonded to one Oxygen, then single bonded to two different Oxygens, then it is called a phosphodiester. ] = Bonds Bond polarity refers to the difference in electronegativity between the two bonding elements. In order from weakest to strongest we have $"H ", "P ", "C ", "S ", "N ", "O "$ #define( title: "Hydrogen Bonds" )[ Hydrogen bonds happen between an exposed Hydrogen molecule and a lone pair on an element such as Oxygen. ] #define( title: "Hydrophobic Bonds" )[ Happens when molecules that are detracted from water group together in order to stay away. ] Ionic bonds are also classified under electrostatic interactions. Within water, the bond strength go $"Covalent" -> "Ionic" -> "Hydrogen" -> "Hydrophobic" -> "Van Der Waals"$ = Line Angle Drawing This is a shorthand way of drawing organic molecules. Every bend or end is a carbon, and each carbon should have four connections, so we need to fill the missing ones with hydrogen bonds. = Functional Groups / Hydroxyl: $"OH"$, can lose the $"H "$ to become negatively charged. / Carboxyl: Carbon double bonded to an Oxygen with a $"OH"$, same as above, it can lose the hydrogen to be negatively charged. / Amino: $"NH"_2$, can *gain* a Hydrogen to become positively charged. / Sulfhydrl: Sulfur bound to a Hydrogen, it can lose the Hydrogen to become negatively charged. / Amide: Results from condensation between a Carboxyl and Amino group. The $"OH"$ from the Carboxyl bonds with one of the $"H "$ from the Amino to form a water. The Carbon then bonds to the Nitrogen. / Ester: Any element that has a double bond to one Oxygen and a single bond to another. = Phospholipids In a phospholipids, the tail is hydrophobic and non-polar, while the head is hydrophilic and polar. This is because the tail contains mostly Carbons and is non-polar, while the head contains Nitrogen, Oxygen, and other electronegative elements meaning that it is polar. #define( title: "Amphipathic" )[ A molecule that is two sided, having a hydrophobic and hydrophilic side. ] Thus the way that the phospholipid bilayer works is by having the heads face outward while the tails are inside, allowing for cells to compartmentalize. Prokaryotic cells have a single phospholipid bilayer, while eukaryotic cells have more internal structures which also have a phospholipid bilayer around them.
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Valorant_Notes_DATA.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: "Valorant Notes DATA", authors: ( "<NAME>", ), date: "30 Octobre, 2023", ) #set heading(numbering: "1.1.") == what i need to improve on <what-i-need-to-improve-on> - watch vod and see what i could have done better 🚧 - aim past the enemy if they are moving so that they walk into the crosshair 🚧 - hold angles in a way that i can fall back to cover and it’s unlikely that they go past my crosshair 🚧 - hold tightly if you have angle advantage and you’re going slow ✅ - don’t unswing if they don’t peek at you - improve my movement : jiggle peek 🚧 | wide peek ✅ | shoulder peek ✅ | deadzoning 🚧 | burst strafing ✅ \ - spray at low ✅|mid range and burst at long range 🚧 (and tap at very long range ✅) make some movement between bursts \ - when i have the angle advantage shift walk and hold tightly ✅ - peek by pre aiming the corner cleaning block by block ✅ == VOD NOTES <vod-notes> === 14/10/2023 <section> - don’t start the fight with spray but burst more === 29/08/2023 <section-1> - don’t reload when you don’t need to - hold spyke until mid === 28/08/2023 <section-2> - be more confident in my shots - don’t hyperfocus and forget to check the minimap - always target the most dangerous enemy first - be aware of off angles - correct microadjustments == SOURCES OF INFORMATION <sources-of-information> - https:\/\/youtube.com/clip/Ugkx3VyjVc\_MUORcB16ILJ72oJ18I42lr0Y3?si\=s6bvmqs60CYLIiVC - https:\/\/youtu.be/nm\_n2lvHbsM?si\=W-kEw34c-XMjLD5F crunch off angle spots \ #align(center)[#table( columns: 2, align: (col, row) => (auto,auto,).at(col), inset: 6pt, [✅], [❌], [IIII], [II], ) ] #align(center)[#table( columns: 2, align: (col, row) => (auto,auto,).at(col), inset: 6pt, [✅], [❌], [], [], [], [], [], [], ) ]
https://github.com/sitandr/typst-examples-book
https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/snippets/math/vecs.md
markdown
MIT License
# Vectors & Matrices You can easily note that the gap isn't necessarily even or the same in different vectors and matrices: ```typ $ mat(0, 1, -1; -1, 0, 1; 1, -1, 0) vec(a/b, a/b, a/b) = vec(c, d, e) $ ``` That happens because `gap` refers to _spacing between_ elements, not the distance between their centers. To fix this, you can use this snippet: ```typ // Fixed height vector #let fvec(..children, delim: "(", gap: 1.5em) = { // change default gap there context math.vec( delim: delim, gap: 0em, ..for el in children.pos() { ({ box( width: measure(el).width, height: gap, place(horizon, el) ) },) // this is an array // `for` merges all these arrays, then we pass it to arguments } ) } // fixed hight matrix // accepts also row-gap, column-gap and gap #let fmat(..rows, delim: "(", augment: none) = { let args = rows.named() let (gap, row-gap, column-gap) = (none,)*3; if "gap" in args { gap = args.at("gap") row-gap = args.at("row-gap", default: gap) column-gap = args.at("row-gap", default: gap) } else { // change default vertical there row-gap = args.at("row-gap", default: 1.5em) // and horizontal there column-gap = rows.named().at("column-gap", default: 0.5em) } context math.mat( delim: delim, row-gap: 0em, column-gap: column-gap, ..for row in rows.pos() { (for el in row { ({ box( width: measure(el).width, height: row-gap, place(horizon, el) ) },) }, ) } ) } $ "Before:"& vec(((a/b))/c, a/b, c) = vec(1, 1, 1)\ "After:"& fvec(((a/b))/c, a/b, c) = fvec(1, 1, 1)\ "Before:"& mat(a, b; c, d) vec(e, dot) = vec(c/d, e/f)\ "After:"& fmat(a, b; c, d) fvec(e, dot) = fvec(c/d, e/f) $ ```
https://github.com/sitandr/conchord
https://raw.githubusercontent.com/sitandr/conchord/main/examples/compare.typ
typst
MIT License
#import "@preview/chordx:0.2.0": * #import "../lib.typ": new-chordgen, overchord #set page(height: auto, margin: 1em) #set align(center) #show raw: set block(fill: gray.lighten(90%), inset: 3pt) #table( columns: 3, inset: 1em, fill: (_, row) => if not calc.odd(row) { luma(220) } else { white }, [Library], [Code], [Result], [conchord], [ ```typst #let chord = new-chordgen() #chord("x, 6, 10, 7, 9, 6", name: "D#maj7sus4add13") ``` ], [ // Chordx chords are smaller, so for better // comparison need to make it smaller #let chord = new-chordgen()//scale-length: 0.6pt) #chord("x, 6, 10, 7, 9, 6", name: "D#maj7sus4add13") ], [chordx], [ ```typst #let chord = new-chart-chords() #chord( capos: (("115"),), fret-number: 6, tabs: "xn524n" )[D\#maj7sus4add13] ``` ], [ #let chord = new-chart-chords() #chord( capos: ("115"), fret-number: 6, tabs: "xn524n" )[D\#maj7sus4add13] ], [conchord], [ ```typst #let chord(name) = overchord(strong(name)) #chord[G] Jingle bells, jingle bells, jingle #chord[C] all the #chord[G] way! \ #chord[C] Oh what fun it #chord[G] is to ride ``` ], [ #let chord(name) = overchord(strong(name)) #chord[G] Jingle bells, jingle bells, jingle #chord[C] all the #chord[G] way! \ #chord[C] Oh what fun it #chord[G] is to ride ], [chordx], [ ```typst #let chord = new-single-chords(weight: "semibold") #chord[Jingle][G][2] bells, jingle bells, jingle #chord[all][C][2] the #chord[way!][G][2] \ #chord[Oh][C][] what fun it #chord[is][G][] to ride ``` ], [ #let chord = new-single-chords(weight: "semibold") #chord[Jingle][G][2] bells, jingle bells, jingle #chord[all][C][2] the #chord[way!][G][2] \ #chord[Oh][C][] what fun it #chord[is][G][] to ride ] )
https://github.com/jujimeizuo/ZJSU-typst-template
https://raw.githubusercontent.com/jujimeizuo/ZJSU-typst-template/master/template/abstract.typ
typst
Apache License 2.0
#import "font.typ": * #import "../contents/info.typ": * #import "../contents/abstract.typ": * #show heading : it => { set align(center) set text(font:heiti, size: font_size.sanhao) it par(leading: 1.5em)[#text(size:0.0em)[#h(0.0em)]] } // 页脚格式 #set page(footer: [ #set align(center) #set text(size: 10pt, baseline: -3pt) #counter(page).display( "I", ) ] ) #pagebreak() // 中文摘要页 #heading(level: 1, outlined: false)[摘要] #v(2em) #v(2em) #par( justify: true, leading: 1.5em, first-line-indent: 2em)[#text(font: songti, size: font_size.xiaosi)[#abstract_zh]] #v(2em) #par(first-line-indent: 0em)[ #text(weight: "bold", font: songti, size: font_size.xiaosi)[ 关键词: ] #text(font: songti, size: font_size.xiaosi)[#keywords_zh.join(";") ] ] #pagebreak() //英文摘要页 #heading(level: 1, outlined: false)[ABSTRACT] #v(2em) #v(2em) #par(justify: true, leading: 1.5em, first-line-indent: 2em)[#text(font: songti, size: font_size.xiaosi)[#abstract_en]] #v(2em) #par(first-line-indent: 0em)[ #text(font: "Times New Roman", size: font_size.xiaosi, weight: "bold")[ Keywords: ] #text(font: "Times New Roman", size: font_size.xiaosi)[#keywords_en.join("; ") ] ]
https://github.com/spidersouris/touying-unistra-pristine
https://raw.githubusercontent.com/spidersouris/touying-unistra-pristine/main/src/colors.typ
typst
MIT License
// Colors from the official palette of the University of Strasbourg // https://langagevisuel.unistra.fr/index.php?id=396 #let white = rgb("#ffffff") #let black = rgb("#000000") #let link-color = rgb(118, 50, 55) #let grey = ( "A": rgb("#333332"), "B": rgb("#929292"), "C": rgb("#CACACA"), "D": rgb("#F6F6F6"), "E": rgb("#696260"), ) #let maroon = ( "A": rgb("#522122"), "B": rgb("#96716A"), "C": rgb("#CDB6B3"), "D": rgb("#F3F0EF"), "E": rgb("#B0685F"), ) #let brown = ( "A": rgb("#512414"), "B": rgb("#AF745B"), "C": rgb("#D6BAAB"), "D": rgb("#F4EAE7"), "E": rgb("#BD6244"), ) #let orange = ( "A": rgb("#7D340D"), "B": rgb("#E94E1B"), "C": rgb("#FAC294"), "D": rgb("#FEF0E7"), "E": rgb("#FF4600"), ) #let red = ( "A": rgb("#8A200D"), "B": rgb("#E42313"), "C": rgb("#F6AF8F"), "D": rgb("#FDEDE8"), "E": rgb("#FF2015"), ) #let pink = ( "A": rgb("#921428"), "B": rgb("#E40136"), "C": rgb("#F4A5AA"), "D": rgb("#FDEDED"), "E": rgb("#FF1D44"), ) #let purple = ( "A": rgb("#7E0F44"), "B": rgb("#BF1C66"), "C": rgb("#F3A3C1"), "D": rgb("#FCEAF4"), "E": rgb("#FA186E"), ) #let violet = ( "A": rgb("#3B2983"), "B": rgb("#584495"), "C": rgb("#AAA5D2"), "D": rgb("#EDE7F4"), "E": rgb("#4C2ED6"), ) #let nblue = ( "A": rgb("#22398E"), "B": rgb("#4458A3"), "C": rgb("#95B5E0"), "D": rgb("#E7EDF9"), "E": rgb("#315CDD"), ) #let blue = ( "A": rgb("#003F75"), "B": rgb("#0070B9"), "C": rgb("#8CD3F6"), "D": rgb("#E2F3FC"), "E": rgb("#0095FF"), ) #let cyan = ( "A": rgb("#004C4C"), "B": rgb("#009194"), "C": rgb("#85CCD3"), "D": rgb("#DCEFF4"), "E": rgb("#00C1C1"), ) #let ngreen = ( "A": rgb("#00462E"), "B": rgb("#008A57"), "C": rgb("#73C09B"), "D": rgb("#E7F3EC"), "E": rgb("#29D49D"), ) #let green = ( "A": rgb("#004818"), "B": rgb("#009A3A"), "C": rgb("#A6D2A7"), "D": rgb("#EBF4E9"), "E": rgb("#61F275"), ) #let camo = ( "A": rgb("#3B471A"), "B": rgb("#89A12A"), "C": rgb("#D8E08E"), "D": rgb("#F0F5E2"), "E": rgb("#96D400"), ) #let yellow = ( "A": rgb("#E28E00"), "B": rgb("#FFCD00"), "C": rgb("#FFF594"), "D": rgb("#FFFDE8"), "E": rgb("#FFF028"), ) // ---- #let colorthemes = ( lblue: (blue.E, cyan.E), blue: (nblue.E, cyan.E), dblue: (nblue.E, blue.E), yellow: (yellow.B, yellow.C, black), pink: (pink.E, pink.B), neon: (violet.E, pink.E), mandarine: (orange.E, brown.E), hazy: (maroon.E, grey.E), smoke: (grey.E, black), forest: (green.A, camo.E), berry: (pink.A, purple.A), ocean: (cyan.A, blue.B, blue.D), lavender: (purple.C, violet.C, black), moss: (ngreen.C, grey.B, black), clay: (brown.B, maroon.C), mint: (ngreen.E, cyan.C, black), lemon: (yellow.A, camo.E, black), wine: (maroon.A, brown.A, maroon.D), )
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/011%20-%20Journey%20into%20Nyx/003_Dreams%20of%20the%20City.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Dreams of the City", set_name: "Journey into Nyx", story_date: datetime(day: 23, month: 04, year: 2014), author: "<NAME>", doc ) === Somewhere in Meletis #emph[Euneas dreams.] Euneas walked among the azure columns of the white marble plaza at the heart of the city. Golden lions patrolled the outer edge of the plaza, their metal feet ringing a tinkling melody against the spotless marble floor. Frothing water jetted from crystal fountains, the running streams a constant murmuring backdrop to important conversations. Groups of scholars and philosophers debated in the open plaza, their hands weaving arcane symbols of blue energy into the air. The equations were beautiful, each one describing answers to questions Euneas could not quite remember, but were of monumental importance. The finest minds of Meletis gathered, a convocation of intellect and power unmatched. #figure(image("003_Dreams of the City/01.jpg", width: 100%), caption: [Plea for Guidance | Art by <NAME>], supplement: none, numbering: none) Workmen arrived in spotless white uniforms, erecting scaffolding and harnesses in silence. Up they climbed to the tops of the columns, and Euneas saw bigger and newer azure columns being lowered from the distant sky slowly, carefully, by the workmen above. There was a brief pause, and clang the columns from the sky crashed down into the columns in the plaza. The lions stopped their patrolling, their golden feet still; the fountains stopped their flow and the scholars ceased their conversation. Each of the original columns had sunk a foot into the ground, and a web of cracks appeared in the marble floor. There was another clang and the columns sunk another foot, and the lions resumed their patrol, the water its arc, the scholars their debates. There were more clangs as the first azure columns were crushed by the new arrivals of their identical replacements. The only remnant of the originals were blackened compressed stumps, surrounded by dark fissures in the marble. New columns were lowered from the sky on top of the replacements, clanging into the second wave of columns with increasing frequency until there was stump upon stump, and Euneas could see a fourth wave of columns being directed with urgency by the workmen above. The cracks and fissures were spreading, black tendrils of dirt and grime connecting through the once-pristine marble. The scholars and philosophers waved their hands in the air, screaming at each other, but now their equations were made of grimy dust describing banal trivialities, and as soon as they appeared they fell lifeless to the ground, adding to the dirt below. The frothing water in the fountains sputtered, and ceased, replaced by an oily sludge spewing to the pace of an ill-beat heart. A golden lion struck its gleaming foot into the sludge, and the lion slipped and crashed to the ground, its foot shearing off at the impact. The metal lion staggered up, limping along on three feet, its broken limb hemorrhaging an endless gush of blood. The blood mixed with the dirt and the grime and the oil, as still more columns were lowered from above, and every column delivered to this point packed down to the space of a small unmarked grave. Hundreds of years, thousands, were compressed into those beaten columns, along with the lives and blood and dirt those years had created and churned through. Nowhere was a pristine spot left, all was tainted by the advancement of the city, the continued push to build anew on top of corruption and death. #figure(image("003_Dreams of the City/02.jpg", width: 100%), caption: [Tormented Thoughts | Art by <NAME>], supplement: none, numbering: none) Euneas looked up to see the workmen descending in a scrabble, their white uniforms now a dark, oily mess of tatters, their faces desiccated and without skin, their gaping mouths captured in an eternal scream of no sound. When Euneas looked down again he saw the oily darkness surrounding him, threatening to pull him under. He tried to flee, and a lick of oily taint caressed his ankle. The tendrils of darkness crept up his legs, his skin fissured and bubbling with its touch. Euneas screamed a song with no words and scratched and tore to keep himself clean. Skin sloughed away as he scrubbed and scrubbed to remove the oily taint, but even as he tore all the skin off his body, the taint remained, calcifying, locking him in place. His eyes were the last things that were free, searching for escape, and when they looked up they saw new columns descending. The city had claimed him whole, another piece of sediment for the streets future inhabitants would trod upon in their brief doomed hours. #emph[Euneas woke screaming.] === Somewhere in Akros #emph[Pollio dreams.] The streets thronged with people. Pollio had never seen the dusty streets of Akros so full. Soldiers, bakers, old women, gladiators, farmers, little boys, slaves, Pollio's children, priests, his children, his children, where were his children? There, in front of him, the press of the crowd keeping them hemmed in. Pollio took two long strands of twine, blue twine, and tied one end around his wrist, and the other end of each twine around the wrists of his children. Pollio took a deep, contented breath. His children would be safe, the blue twine keeping them close and protected. He took some more twine, green this time, and tied it the same way he had tied the blue twine. Now his children would be fed. Red twine went around his wife's wrist and his own, the sign of their matrimony. #figure(image("003_Dreams of the City/03.jpg", width: 100%), caption: [Market Festival | Art by <NAME>], supplement: none, numbering: none) As he found his customers in the street, and there were many who valued Pollio's metalcraft, they were connected by yellow twine. Pollio's left wrist was adorned with many tens of bracelets of different hues, each thread a relationship, a connection to the many faces of the city. And on his right wrist were more bracelets, connecting him to several soldiers who protected Akros; Tomakri the baker, who made the sweet cinnamon rolls his wife loved so much; Kopaknios the ingot-deliverer, who supplied the precious metals Pollio transformed into blades and armor; and others, so many others. Pollio had been able to move with ease with the first connections, but now each new connection was difficult. The twine could stretch, stretch long, but it not could not stretch forever. Everyone went their own way in the city; the hundreds of people Pollio was connected to had hundreds of connection of their own, and as people crossed paths in the city new connections formed all the time. Pollio's movement slowed, and then became labored as he struggled against the brightly colored threads in all directions. He sought to break the twine, but could not, no matter how his formidable muscles groaned and strained. The more he struggled, the stronger and larger the twine became until it was thick, corded rope. Soon, all movement stopped on the street, each person fighting against the constricting bonds. Pollio could not see his children or wife anymore, as the rope chafed against his head and neck and he could not turn an inch. All he could do to stay standing was fight against the weight of all the people around him. The ropes became tighter and tighter, and everyone was brought closer and closer. Flesh pressed into flesh, and still the ropes grew stronger and tighter. Someone's cheek pressed up against Pollio's and the rank smell of desperate humanity filled Pollio's nostrils. He could not move, imprisoned as he was by bodies, and the ropes, those connections the city demanded in a world without freedom and space. He felt a scratching where the next man's cheek joined his, and he realized their cheeks were joining, their flesh knitting together as the ropes pulled tighter and tighter. Pollio tried to scream, but his mouth was covered with ropes and other people's flesh, and the only sound that emerged was the absence of hope. #figure(image("003_Dreams of the City/04.jpg", width: 100%), caption: [Cast into Darkness | Art by <NAME>ley], supplement: none, numbering: none) Then, Pollio was part of one amorphous mass of stinking flesh and burning rope, a mass beholden to the rotting cesspool they called home. This was the destiny of those who dwelled in the city. #emph[Pollio woke screaming.] === Somewhere in Meletis #emph[Melantha dreams.] She sat at the head of the temple dinner table. #emph[This is not my place.] The cloth was impeccably white, and torchlight flickering and dancing along the white-and-blue-tiled walls illuminated two settings at the long table—hers, and one next to hers at her left. Steps echoed from down the hall, but in the gloom beyond she could not immediately make out their source. The footsteps approached and there was a face in front of her, a face she had not seen in twenty years. "Melantha! May I join you?" Xenocrates had been one of her first mentors at Ephara's temple when Melantha had arrived so many years before. To the outside world, the priesthood of Ephara was kind and welcoming. Inside, the truth revealed was darker. Melantha had struggled to find her place, to balance the demands of serving her god with finding acceptance among her peers. Xenocrates had protected her, had championed her, had provided a shoulder to cry on. There had been much crying in those first few years. She looked at his round, clean-shaven face, this face she had not seen for so long, and it did not surprise her she was crying again. If she looked over her shoulder, if her heart beat a bit faster, what of it? She was with her friend again. #figure(image("003_Dreams of the City/05.jpg", width: 100%), caption: [Ephara's Radiance | Art by <NAME>], supplement: none, numbering: none) "Melantha, do not be sad. Let us eat and drink. I am quite hungry." Food and drink appeared in front of them, and Xenocrates tore into the meal with vigor. #emph[Don't drink!] Melantha was not hungry, and so she studied her friend instead. While his face looked hale, the rest of Xenocrates was gaunt and far removed from the round-bellied, cheerful man she had known so many years before. Xenocrates picked up the goblet in front of him, and Melantha wanted to cry out, to warn him, but she was silent as he put the goblet to his lips and drank deeply. "Have I told you, Melantha, about my new theory on the gods?" Xenocrates looked up at her and smiled, and there was an unsightly bluish stain on his lips and teeth. #emph[From the wine] , Melantha thought. #emph[Probably.] "I don't think we should talk about that, Xenocrates. It's not... correct. Tell me about you, instead. How are you? How have you been?" Xenocrates took another deep drain of his wine and Melantha winced. Xenocrates coughed before answering. "It feels good to eat. To really eat. To feel the food in your mouth crumble and change and decay, to hold it all in, the flavor and the chaos, the death of life to give you life. Yes, it feels good to eat. But I was talking about the gods, Melantha. What they are, what they really are." "We're not allowed to discuss this. It is forbidden." There was more coughing, longer and sustained, before Xenocrates spoke again. "Forbidden? I hear you are on the high council now. I am proud of you, Melantha, to see how far you have come. You can determine what is forbidden, yes? What is acceptable? We have spent many hours debating the nature of the gods. What is one more hour among friends?" Another fierce cough, and Xenocrates raised his hands to wipe away his mouth. There was a small smear of blood on his lips and cheek. "You're hurt. Let me..." "No, I'm fine, Melantha. I'm fine. A little cough won't hurt. Now, I'm not eternal. We both know the truth of that. Only the gods are eternal, we say. Only the gods are constant. And yet it is odd, surely, to read the earliest extant writings on Heliod and Thassa and the rest, to see how differently those versions of our gods acted compared to now. "Koblios, in #emph[Meditations] , said, 'The gods are simply patterns personified,' before he was stoned for his heresy. Sad that, despite the price he paid, he was still wrong. Gods are the #emph[patterns we recognize] , personified. The difference is in the creator. Through the power of Nyx, we are responsible for our gods. Perhaps we are even responsible for Nyx..." "You will be quiet!" Melantha stood, furious. She would not permit this blasphemy in her temple. Even after all these years, Xenocrates insisted on believing these awful untruths. Xenocrates coughed and coughed and a large clot of bloody substance landed on the white tablecloth, staining it red and pink. When Xenocrates looked up, he smiled a ghastly smile, his teeth stained a dark indigo, and blood leaking from his mouth. "What will you do, Melantha? Kill me?" The anger fled Melantha and, with it, her ability to stand. She crumpled to the bench. "I did not... I did not kill you, Xenocrates." #emph[I saw them put it in the goblet. I could have warned you. I could have told you.] #figure(image("003_Dreams of the City/06.jpg", width: 100%), caption: [Claim of Erebos | Art by <NAME>], supplement: none, numbering: none) Blood started to leak out of his eyes. "Perhaps you didn't, Melantha." #emph[You said such horrible things. Such untrue things. What else could they do? What else could I do?] "Did you know, Melantha, there are so many states of decay before you die? So many ways to degrade and be degraded, so many injuries and debilitations to experience before the final dissolution. Eventually, you become so compromised you cannot remember what innocence was. So many ways to decay. And you've known only a few. You have so much more to experience before you die." Xenocrates opened his mouth wide as blood flowed freely out between his teeth, gushing and pouring... #emph[Melantha woke screaming.] === Somewhere in Nyx #emph[The city dreams.] The city enjoyed its peaceful rest. Its long white avenues were clean and gleaming, made of strong stone that absorbed the warm sunlight. It had many wonderful buildings full of beautiful columns and intricate, crafted stonework. For a long time, the city knew nothing but resting in the sun, and it was happy. Eventually, a small and hairy creature entered the city. It walked around on two legs, and it was very tiny, and the city thought the animal amusing. The animal seemed to enjoy playing in the city, and the city was pleased to have the animal explore. Soon, the animal was joined by a second small and hairy animal, and as they ambled throughout the city, the city created small parks and lakes for the animals to play in, and it made small buildings for the animals to sleep in, and provided trees for the animals to pick fruit from, and the city was happy. #figure(image("003_Dreams of the City/07.jpg", width: 100%), caption: [Temple of Enlightenment | Art by <NAME>], supplement: none, numbering: none) The next day, the city awoke to find many of the small, hairy creatures in its streets and buildings. There were hundreds of them, and the city wanted to make sure they were fed and sheltered and provided for, and never had the city felt so needed and wanted and busy. The city's streets were no longer glistening and clean, but as the city went to sleep that night it thought about all the creatures it had provided for and it was happy. The next day, the city awoke to an uncomfortable scratching. The creatures were everywhere. There were thousands of them, many thousands of them, and they walked and crawled and climbed in and out and through and over all of the city. Everywhere, the creatures left hair and stains, and the city's once-beautiful streets were clogged with dirt and grime and mud. The vermin continued to spread, and their little ape-mouths nipped at the city's trees and lapped the city's water, and their ravenous hunger even led them to bite at the city's stone buildings and streets. Every avenue and structure of the city was covered with the hairy pests, biting at the city's body, and the city started to tremble and shake to rid itself of the pestilent horde. #emph[YOU MUST ARISE.] The city did not recognize the voice, nor could it see where it came from. #emph[YOU MUST AWAKEN.] The city realized it had never heard another voice before, but the truth of the words became apparent. The city must arise. The city must awaken. There was another world to grasp. Cacophony, the god of cities, arose. It looked around at the little apes clinging to its body. It saw their hunger and their fear, and it was happy. Cacophony reached out with its newly formed hands and grabbed thousands of the hairy ape-creatures, crushing them and flinging their corpses to the ground below. It would not destroy all of the apes, just some, just enough for the survivors to live their little ape lives in agony and fear, and then it would... "#emph[What monstrosity is this?] " It was the second voice the newly awakened god heard that day, although unlike the first, this voice was one Cacophony had heard before—although it could not remember from where. A tall, dark-skinned woman strode into the city god's view, her skin covered with the stars of Nyx, and underneath that skin, for those with the senses to see, pulses of blue and white energy blared like the sun. The woman's eyes, star-filled orbs, dimmed and turned red as she looked at Cacophony. "#emph[You dare exist? And who dares to create you? Where are you, mortal? I will find you. You cannot hope to hide from such as I.] " As she spoke, the woman extended her hands, plunging them into Cacophony. "#emph[I am Ephara, and you should no more exist than a finger separated from its hand. Goodbye, Little One.] " Her voice sounded almost kind, at the end. #figure(image("003_Dreams of the City/08.jpg", width: 100%), caption: [Ephara's Enlightenment | Art by Wesley Burt], supplement: none, numbering: none) Cacophony did not know what was happening, could not understand why its life was draining, its awareness slumbering. As it fell back into non-existence, the city-dream once known as Cacophony never had a moment with enough coherence to know regret. #emph[Cacophony, the god of cities dark, never woke again.] === Somewhere in Theros The earth's rumbles faded to stillness as the last remnant of Phenax's glamour dissolved around Ashiok. Ashiok hovered in midair, silent and still, before extending senses out into the surrounding area to make sure Ashiok was alone and no vengeful god was in pursuit. Ashiok had specifically chosen the abandoned temple to Ephara in a deserted city on the outskirts of civilized Theros. Numerous small deserted cities could be found like that one, a testament to the futility of permanence in a world controlled by the whims of gods. One of those whims had allowed Ashiok to be unseen and undetected by any force on Theros, save one. "So what boon do you wish of me?" the god Phenax had asked Ashiok, not so long before, to repay a favor the Planeswalker had done for the god. That Ashiok had enjoyed performing the favor immensely had no bearing on the need for repayment. Gods do not suffer being in debt to mortals for long. #emph[I wish to hide from the gods.] Ashiok relied on Phenax being amused by the thought of deceiving all the other gods, and Phenax had proved Ashiok right. The boon was a temporary one, and Phenax had been very explicit about Ashiok's fate if Ashiok used the boon to attempt to injure or murder a god. But Phenax had never said anything about attempting to create a new god. The attempt was never going to be #emph[successful] . But it was #emph[beautiful] . Beauty mattered a great deal—not Ashiok's most #emph[important] value, but still something to cherish. Besides, success in this field seemed problematic anyway. Xenagos's apparent fascination with being a deity mystified Ashiok—one of the few things opaque to Ashiok. Xenagos was a #emph[Planeswalker] . What better opportunity for creation and beauty was there? #figure(image("003_Dreams of the City/09.jpg", width: 100%), caption: [Ashiok, Nightmare Weaver | Art by <NAME>], supplement: none, numbering: none) Xenagos had proven turning a mortal into a god was difficult, but possible. But turning an idea into a god was much easier. And for those who had the ability to control dreams, it was simpler still. Ashiok suspected ideas took shape and became proto-deities in Nyx all the time, but were probably subsumed into the existing deities without anyone, including the gods, aware it was happening. But if that process was shaped, was #emph[sculpted] , if the humans' connection to their gods was attacked, if their connection to their #emph[patterns] was attacked, while a new path for that pattern was prepared... well, Cacophony could rise again. How the artist would escape detection from the gods while allowing the created god enough time to survive and grow strong would be difficult. But those were details for some technician in the future to execute. As for the consequences of that day... let Ephara wonder what machinations had led to the display. Let other gods inquire and worry and investigate what it presaged. Mortals were not the only creatures prone to seeing patterns where none existed. Ashiok had already moved on to contemplating the next symphony. There were always more wonderful displays to create, here in the fertile world of Theros. Tiny bits of Ashiok's cheek dissolved into smoke. New dreams were born.
https://github.com/marcothms/clean-polylux-typst
https://raw.githubusercontent.com/marcothms/clean-polylux-typst/main/README.md
markdown
# Clean Polylux Template This is a clean and dynamic presentation template for [Polylux](https://github.com/andreasKroepelin/polylux), a package for [Typst](https://typst.app/) to create nice looking presentations. Initial work was already done, but I added lots of neat features, so now this template features: - An easy to use templating interface, which just requires some meta information - A footer with arbitrary text and a slide counter - A slide counter, that does not suck! (as it only counts real slides and shows a total amount) - Dynamic logos on the title slide - Dynamic coloring via variables - Automatic creation of a contents slide - Dynamic header on each slide showing the slide's name and current section - Focus slides ## Screenshots | Light Theme with Green Accent | Light Theme with Orange Accent | Dark Theme with Purple Accent | |:--:|:--:|:--:| |![light1](./screenshots/light1.png)|![light2](./screenshots/light2.png)|![dark1](./screenshots/dark1.png)| ![titlepage](./screenshots/titlepage.png) ![contents](./screenshots/contents.png) ## How to use See [presentation.typ](./presentation.typ) for a sample presentation. Make sure you have `typst` installed, otherwise you could use the provided Nix Flake with `nix develop .` To just compile the presentation, run: ```sh $ typst compile presentation.typ --open ``` To have a live preview, run: ```sh $ typst watch presentation.typ --open ``` ## Configure The entire templating part is done in [theme.typ](./theme.typ). Every major variable can be found towards the top of the file, marked with `CONFIG:` comments. Here you can configure the font and the color of the slides, the rest will be adjusted automatically. ## Contribution Feel free to fork this repository and make adjustments as you wish, but I would appreciate a small notice somewhere. If you find visual bugs or have feature ideas, feel free to upstream them to this repository. ## Inspirations - [matze/mtheme](https://github.com/matze/mtheme) - [Enive](https://github.com/Enivex) - [hargoniX](https://github.com/hargoniX/)
https://github.com/Anastasia-Labs/project-close-out-reports
https://raw.githubusercontent.com/Anastasia-Labs/project-close-out-reports/main/f10-smart-handles-closeout-report/video-transcript/smart-handles-video-transcript.typ
typst
#let image-background = image("../images/Background-Carbon-Anastasia-Labs-01.jpg", height: 100%, fit: "cover") #let image-foreground = image("../images/Logo-Anastasia-Labs-V-Color02.png", width: 100%, fit: "contain") #let image-header = image("../images/Logo-Anastasia-Labs-V-Color01.png", height: 75%, fit: "contain") #let fund-link = link("https://projectcatalyst.io/funds/10/f10-osde-open-source-dev-ecosystem/anastasia-labs-smart-beacons-router-nfts")[Catalyst Proposal] #let git-link = link("https://github.com/Anastasia-Labs/smart-handles")[Main Github Repo] #set page( background: image-background, paper :"a4", margin: (left : 20mm,right : 20mm,top : 40mm,bottom : 30mm) ) #set text(15pt, font: "Barlow") #v(3cm) #align(center)[ #box( width: 60%, stroke: none, image-foreground, ) ] #v(1cm) #set text(20pt, fill: white) #align(center)[#strong[Smart Handles]] #align(center)[Project Closeout Video Transcript] #v(5cm) #set text(13pt, fill: white) #table( columns: 2, stroke: none, [*Project Number*], [1000011], [*Project manager*], [<NAME>], [*Date Started*], [2023-10-08], [*Date Completed*], [2024-10-07], ) #set text(fill: luma(0%)) #show link: underline #set terms(separator:[: ],hanging-indent: 18mm) #set par(justify: true) #set page( paper: "a4", margin: (left: 20mm, right: 20mm, top: 40mm, bottom: 35mm), background: none, header: [ #align(right)[ #image("../images/Logo-Anastasia-Labs-V-Color01.png", width: 25%, fit: "contain") ] #v(-0.5cm) #line(length: 100%, stroke: 0.5pt) ], ) #v(20mm) #show link: underline #show outline.entry.where(level: 1): it => { v(6mm, weak: true) strong(it) } // Initialize page counter #counter(page).update(0) #outline(depth:2, indent: 1em) #pagebreak() #set text(size: 11pt) // Reset text size to 10pt #set page( footer: [ #set text(size: 11pt, fill: gray) #line(length: 100%, stroke: 0.5pt) #v(-3mm) #align(center)[ *Anastasia Labs – Smart Handles* #v(-3mm) Project Closeout Video Transcript #v(-3mm) // Copyright © // #set text(fill: black) // Anastasia Labs ] #v(-6mm) #align(right)[ #counter(page).display( // Page numbering "1/1", both: true, ) ] ] ) // Display project details #set terms(separator:[: ],hanging-indent: 18mm) #align(center)[ #set text(size: 16pt) #strong[Smart Handles] ] = Slide 1 Hello Cardano, this is Mladen from Anastasia Labs, and today I'd like to present our closeout report for Smart Handles, which we initially called Smart Beacons. = Slide 2 OK let's start by getting a better understanding of what Smart Handles is. In a nutshell, Smart Handles is a framework for generating contracts that users will be able to send funds to, in order to interact with the underlying DApp. This enhances decentralization as it enables users to not be constrained by the websites of these DApps. = Slide 3 The framework itself makes minimal constrains, while also providing enough flexibility so that developers can have as much freedom as possible to implement instances for their users. A common and useful example of this, is the idea of swapping tokens by simply sending some ADA to an address via a wallet, rather than using a DEX's interface. Since each instance of Smart Handles will have a unique addresses, these addresses can be enhanced by locking ADA Handles in them, which will increase the convenience for end users. Our framework is also a full-fledged suite: from on-chain framework, to a CLI application generator. This will give developers all the tools they needs to deploy their instances quickly and efficiently. Finally, we've also opened a PR to GameChanger wallet, which can be used as a guideline for other wallet developers to support interactions with Smart Handles instances. = Slide 4 Now let's take a look at what one of these instance can look like in practice. = Slide 5 Imagine we have a swap Smart Handles instance for ADA to MIN via Minswap, and we store `$ada-to-min` ADA Handle in its address. Users then can send some ADA to this handle, knowing 1 ADA will be sent to the routing agent. A routing agent that's monitoring the address picks up the swap request and sends the funds to the Minswap address. Finally, Minswap batchers handle the order and the original user gets MIN at market price. You can see that this only required the user's wallet to support Smart Handles, and there was no need for the user to open up Minswap's platform. = Slide 6 In order to deliver this product, we had to meet some concrete goals. = Slide 7 First and foremost, the contract needed to be abstract enough to offer a reasonable flexibility for developers. Of course the contract needed to be accompanied by an off-chain package. On top of that, we also wanted further convenience, specifically for the routing agents, so that they could support this initiative more easily. = Slide 8 To simplify the learning curve for developers, we also wanted to have extensive examples to be used as references. Having sample transactions on testnet was also something we considered a reliable proof of accomplishment. Finally, a concrete guide for wallet developers to support Smart Handles was essential. = Slide 9 So we divided the road map into 5 phases. = Slide 10 First, designing the protocol and the overal interface provided by the suite. This gave us a clear path for development. = Slide 11 Developing the on-chain contracts was the second step. Knowing it's generally inevitable for abstractions to introduce overheads, we employed Plutarch to minimize this performance cost. = Slide 12 Following our other off-chain SDKs, we used the same interface for all the endpoints. This resulted in a consistent API, not only between all the endpoints of this project, but also accross our other off-chain SDKs. = Slide 13 In order to easily reuse the infrastructure laid out in our off-chain SDK, we opted to implement the CLI application in Typescript. The package we implemented, requires the users to provide a set of configuration values and functions, and it'll generate a CLI application for their instances with a robust and familiar argument interface. = Slide 14 We found GameChanger wallet to be the most flexible open-source wallet in order to open a PR for integration. = Slide 15 Now let's take a closer look at each of the components. = Slide 16 First the on-chain contract. = Slide 17 First two primary validations are agent imbursement, and guaranteed route destination. For simple Smart Handles, we hardcoded 1 ADA as the fee. But advanced instances allow custom fees for each request UTxO. The route destination is also specified as a parameter. This ensures its correctness for instances. We wrote the contracts for two "targets:" single and batch. Single target means only one route can be performed per transaction, while batch allows routing of multiple requests in one transaction. There is also a chance for requests to get stuck at an instance. So we also implemented a reclaim mechanism. This is quite simple for the... well the simple case! It only requires the signature of its owner. However, it allows for a much more involved validation for advanced reclaims, which we won't delve into here. Similarly, routing of advanced datums also provides instances' logics with much more data and flexibility. We'll briefly take a deeper look later. = Slide 18 Let's see all the off-chain endpoints for interacting with a Smart Handles instance. All endpoints support both single and batch targets, and also simple and advanced datums. = Slide 19 We refer to sending funds to a Smart Handles instance as "requests," since they are "route requests" to be processed by routing agents. Common for all variants, some ADA and assets have to be specified to get locked. However, for the advanced datum, a few more values must be provided: - The owner here is optional. Since advanced reclaims are primarily meant to be carried out by router agents, we needed to allow instances the option of preventing reclaims. So if no owner is specified, the request won't be reclaimable. - As mentioned earlier, each advanced datum can have a custom router fee. - To allow adjustment of incentives, it was reasonable to offer a separate field for the rewards agents could accrue when invoking the reclaim endpoint of advanced requests. So that's why we also have a "reclaim router fee." - Two mint configurations, one for routing and the other for advanced reclaims. - Finally, advanced datums offer a field for providing arbitrary data. = Slide 20 Since routes, whether simple or advanced, are primarily meant to be produced at another script address, both configurations need to specify how the output datum must be built. Additionally, if the advanced datum has any mint requirements, they too need to be provided. Both simple and advanced datums also allow any additional tweaks to the transaction. = Slide 21 For reclaiming of simple requests, no values are required to be provided. Because only owners themselves can reclaim their requests. For the advanced case however, it is very similar to routing. So the configuration must specify: - How the output datum must be built, - If there are any mint requirements, they too should be specified, - Any additional tweaks to the transaction can also be provided. = Slide 22 Now let's take a look at the CLI endpoints. = Slide 23 `monitor` is the primary endpoint for agent. It'll keep polling the instance's address, looking for requests to route. Whenever it finds one, it tries to perform the route and grab its fee. This endpoint also offers an optional flag for switching to advanced reclaims. = Slide 24 As its name suggest, `submit-simple` is for producing simple requests at the instance's address. It only requires the amount of Lovelaces that should be locked, and optionally any additional assets. = Slide 25 For `submit-advanced`, on top of funds to lock, advanced datum fields must also be specified. The generated application supports provision of additional information via an extra JSON file. = Slide 26 So we can summarize what we built in 3 main components. = Slide 27 - The on-chain framework contract - A complete off-chain suite, both the SDK and its corresponding CLI generator - Simple and advanced examples to server as a reference for easier familiarity with the suite = Slide 28 This was a relatively involved project and took us a while to reach the finish line. But we learnt a lot along the way. = Slide 29 First and foremost, we gained a better understanding of what it means to support a wide range of flexibility in a framework. While this gives much more freedom for instance developers, it also meant that for each feature we added, we had to propagate its support throughout all the components of our software suite. Consequently, tests, both emulated and on-chain, proved of utmost importance. They were our firt line of assurance whenever we introduced a new feature. = Slide 30 At the time of our proposal, Cardano contracts were incapable of spending UTxOs that had no datums attached to them. But now, with Plutus V3, this is no longer the case and makes the main vision of this solution attainable. Meaning, users will be able to send funds to deployed Smart Handles without any configurations required, that is, using any wallet whatsoever. = Slide 31 These are the 3 repositories of Smart Handles, please consider giving them starts! And with that, I thank you for your time, and wish you a great day! #v(10mm)
https://github.com/heinrichti/tiacv
https://raw.githubusercontent.com/heinrichti/tiacv/main/example.typ
typst
#import "tiacv.typ": * #show: tiacv #page_header("<NAME>", "Doing my job", "Living somewhere", quote: "Been there, done that", information: ( link("tel:+4917645857458")[#fa("phone") (+49) 123 456 78 443], link("mailto:<EMAIL>")[#fa("envelope") <EMAIL>], link("https://github.com/heinrichti")[#fa-brands([github]) heinrichti]), ) = Summary asdf #lorem(30) #lorem(30) // === Skills #skills(("Typst","C#","GitHub")) = Work Experience #cventry(location: [My Home], timespan: [April 2022 -- September 2022])[== Some Company Inc][Job title][ This is what I did: - Something - Something else #skills(("Typst","C#","GitHub")) ] #cventry(location: [My Home], timespan: [April 2022 -- September 2022])[== Just Another Company][Typst Writer][ This is what I did: - Drink Coffee - Do some actual work #skills(("Typst","C#","GitHub")) ] = Education #cventry(location: [My Home], timespan: [April 2022 -- September 2022])[== Some University][Master of Typing][ This is what I did: - Something - Something else #skills(("Typst","C#","GitHub")) ]
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/test.typ
typst
Apache License 2.0
#import "/src/lib.typ": unit, metro-setup, num #set page(width: auto, height: auto) #num("-123.456e12^2")
https://github.com/Doublonmousse/pandoc-typst-reproducer
https://raw.githubusercontent.com/Doublonmousse/pandoc-typst-reproducer/main/color_issues/oklch.typ
typst
#square( fill: oklch(40%, 0.2, 160deg, 50%) )
https://github.com/zxn64/UESTC_Snow_Halation_Template
https://raw.githubusercontent.com/zxn64/UESTC_Snow_Halation_Template/main/typst/Template.typ
typst
#align(center + horizon, text(size: 32pt, heading(level: 1, outlined: false, `UESTC_SNOW_HALATION's TEMPLATE`))) #set heading(numbering: (..args) => { let nums = args.pos() let level = nums.len() - 1 let i = 0 let num = while i < level { i = i + 1 [#nums.at(i).] } [#h((level - 1) * 2em)#num] }) #pagebreak() #outline() #pagebreak() #counter(page).update(1) #set page(numbering: "1 / 1") == 数学 === exgcd ```cpp int X,Y; int _exgcd(int A,int B) { if(!B) { X = Y = 0; return A; } int res = _exgcd(B,A%B); X = Y; Y = (res - A*X) / B; return res; } int exgcd(int A,int B) { if(!B) { X=1; Y=0; return A; } int res = exgcd(B,A%B); int t = X; X = Y; Y = t-A/B*Y; return res; } int main() { int a,b; cin>>a>>b; int d = exgcd(a,b); cout<<a<<"*"<<X<<" + "<<b<<"*"<<Y<<" = "<<d<<"\n"; return 0; } ``` === 组合数 ```cpp ll f[N],ni[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } inline ll C(ll aa,ll bb) { return f[aa] * ni[bb] %p * ni[aa-bb] %p; } void qiu() { f[0] = ni[0] = 1; for(ll i=1;i<=N-10;i++) f[i] = f[i-1] * i %p; ni[N-10] = ksm(f[N-10],p-2); for(ll i=N-11;i>=1;i--) ni[i] = ni[i+1] * (i+1) %p; }``` === 线性求逆元 ```cpp #include<cstdio> #define ll long long using namespace std; const int maxn=3e6+5; ll inv[maxn]={0,1}; int main(){ int n,p; scanf("%d%d",&n,&p); printf("1\n"); for(int i=2;i<=n;i++) inv[i]=(ll)p-(p/i)*inv[p%i]%p,printf("%d\n",inv[i]); return 0; }``` === 杜教筛(廖) ```cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 2123456; ll prime[maxn],mu[maxn],sum[maxn],vis[maxn],cnt; map<ll,ll> mp; void init() { mu[1] = 1; for(int i=2;i<maxn;++i){ if(!vis[i])prime[++cnt] = i,mu[i] = -1; for(int j=1;j<=cnt&&i*prime[j]<maxn;++j){ vis[i*prime[j]] = 1; if(i%prime[j]) mu[i*prime[j]] = - mu[i]; else{ mu[i * prime[j]] = 0; break; } } } for(int i=1;i<maxn;++i)sum[i] = sum[i-1] + mu[i]; } ll S_mu(ll x) { if(x < maxn) return sum[x]; if(mp.find(x) != mp.end()) return mp[x]; ll res = 1ll; for(ll l=2,r;l<=x;l=r+1){ r = x/(x/l); res -= S_mu(x/l) * (r - l + 1); } return mp[x] = res; } ll S_phi(ll x) { ll res = 0; for(ll l=1,r;l<=x;l=r+1){ r = x/(x/l); res += (S_mu(r) - S_mu(l-1)) * (x / l) * (x / l); } return (res - 1) / 2 + 1; } int main() { ios::sync_with_stdio(false); init(); ll T,x; cin>>T; while(T--){ cin>>x; cout<<S_phi(x)<<" "<<S_mu(x)<<'\n'; } return 0; }``` === <NAME> (lyy) ```cpp #define ll long long #define lll __int128 const ll N=501010; const ll qwq=303030; const ll inf=0x3f3f3f3f; ll T; ll n,m; map <ll,ll> f; ll zz[] = {2,3,5,7,11,13,17,19,23}; ll gcd(ll aa,ll bb) { return !bb ? aa : gcd(bb,aa%bb); } inline ll gsc(ll aa,ll bb,ll p) { return (lll)aa*bb %p; // ll sum = 0; // while(bb) { // if(bb&1) sum = (sum+aa) %p; // bb >>= 1; aa = (aa+aa) %p; // } // return sum; } inline ll ksm(ll aa,ll bb,ll p) { ll sum = 1; while(bb) { if(bb&1) sum = gsc(sum,aa,p); bb >>= 1; aa = gsc(aa,aa,p); } return sum; } inline bool miller_rabin(ll h,ll b) { ll k = h-1; while(k) { ll now = ksm(b,k,h); if(now!=1 && now!=h-1) return 0; if(k&1 || now==h-1) return 1; k >>= 1; } return 1; } inline bool prime(ll h) { if(h==1) return 0; if(h==2 || h==3 || h==5 || h==7 || h==11 || h==13 || h==17 || h==19 || h==23) return 1; for(ll i=0;i<9;i++) if(!miller_rabin(h,zz[i])) return 0; return 1; } ll pollard_rho(ll h) { //h cannot be prime ll c = 1919810; if(h==4) return 2; while(1) { auto F = [=](ll x) { return (gsc(x,x,h) + c) % h; }; c--; ll t=0, r=0, p=1, q; do { for(int i=0;i<128;i++) { t = F(t); r = F(F(r)); if(t==r || (q = gsc(p,abs(t-r),h)) == 0) break; p = q; } ll d = gcd(p,h); if(d>1) return d; } while(t!=r); } } void divide(ll h) { if(h==1) return; if(prime(h)) { f[h]++; return ; } ll d = pollard_rho(h); // cout<<"h = "<<h<<" d = "<<d<<endl; // system("pause"); divide(d); divide(h/d); } void chushihua() { f.clear(); } int main() { srand(time(NULL)); T = read(); while(T--) { chushihua(); n = read(); if(prime(n)) { cout<<"Prime\n"; continue; } divide(n); // for(auto it=f.begin();it!=f.end();it++) cout<< it->first <<" ^ "<< it->second <<"\n"; auto it = --f.end(); cout<< it->first <<endl; } return 0; } ``` === Lucas ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const ll N=301010; const ll inf=0x3f3f3f3f; ll T; ll n,m,p; ll f[N]; ll ksm(ll a,ll b) { ll sum = 1; while(b) { if(b&1) sum = (sum*a) % p; b >>= 1; a = (a*a) % p; } return sum; } ll C(ll a,ll b) { if(b>a) return 0; return f[a] * ksm(f[b],p-2) % p * ksm(f[a-b],p-2) % p; } ll Lucas(ll a,ll b) { if(!b) return 1; return C(a%p,b%p) * Lucas(a/p,b/p) % p; } inline void qiu() { f[0] = 1; for(ll i=1;i<=n+m;i++) f[i] = f[i-1] * i % p; } int main() { cin>>T; while(T--) { cin>>n>>m>>p; qiu(); cout<<Lucas(n+m,m)<<"\n"; } return 0; } ``` === 数论分块(廖) ```cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; ll G(ll n,ll k) { ll res = n * k; for(ll l=1,r;l<=n;l=r+1) { if(k/l>0)r=min(n,k/(k/l)); else r = n; res -= (l + r) * (r - l + 1) / 2ll * (k / l); } return res; } int main() { ios::sync_with_stdio(false); ll x,y; cin>>x>>y; cout<<G(x,y)<<endl; return 0; }``` === 线性筛 ```cpp // p[] for(int i=2; i<=h; i++) { if(!vis[i]) p[++cnt] = i; for(int j=1; j<=cnt && i*p[j]<=h; j++) { vis[ i*p[j] ] = 1; if(i%p[j]==0) break; } } // phi[] for(int i=2; i<=h; i++) { if(!vis[i]) { p[++cnt] = i; phi[i] = i-1; } for(int j=1; j<=cnt && i*p[j]<=h; j++) { vis[ i*p[j] ] = 1; if(i%p[j]==0) { phi[ i*p[j] ] = phi[i] * p[j]; break; } phi[ i*p[j] ] = phi[i] * (p[j]-1); } } // d[] number of factors d[1] = 1; for(int i=2; i<=n; i++) { if(!vis[i]) { p[++cnt] = i; d[i] = 2; g[i] = 1; } for(int j=1; j<=cnt && i*p[j]<=n; j++) { vis[ i*p[j] ] = 1; if(i%p[j]==0) { d[ i*p[j] ] = d[i] / (g[i]+1) * (g[i]+2); g[ i*p[j] ] = g[i] + 1; break; } d[ i*p[j] ] = d[i] * 2; g[ i*p[j] ] = 1; } } // f[] sum of factors f[1] = 1; for(int i=2; i<=n; i++) { if(!vis[i]) { p[++cnt] = i; f[i] = i+1; g[i] = 1; } for(int j=1; j<=cnt && i*p[j]<=n; j++) { vis[ i*p[j] ] = 1; if(i%p[j]==0) { f[ i*p[j] ] = f[i] * p[j] + g[i]; g[ i*p[j] ] = g[i]; break; } f[ i*p[j] ] = f[i] * (p[j]+1); g[ i*p[j] ] = f[i]; } } // mu[] mu[1] = 1; for(int i=2; i<=n; i++) { if(!vis[i]) { p[++cnt] = i; mu[i] = -1; } for(int j=1; j<=cnt && i*p[j]<=n; j++) { vis[ i*p[j] ] = 1; if(i%p[j]==0) break; //mu[i*p[j]]=0;就没必要写了。 mu[ i*p[j] ] = -mu[i]; } }``` === Poly ```cpp #include <iostream> #include <algorithm> #include <vector> #include <cstdio> using namespace std; typedef long long ll; const int N = 1 << 22; const int M = 3e6 + 7; const int Mod = 998244353; int rk[N]; inline ll ModRead() { ll x = 0, flag = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') flag = 0; c = getchar(); } while (c >= '0' && c <= '9') { x = ((x << 1) + (x << 3) + c - 48) % Mod; c = getchar(); } return flag ? x : -x; } ll qpow(ll x, ll y = Mod - 2) { ll ret = 1; while (y) { if (y & 1) ret = ret * x % Mod; x = x * x % Mod, y >>= 1; } return ret; } const ll G = 3ll; const ll Gi = qpow(3ll); const ll inv2 = qpow(2ll); void NTT(const bool &op, const int &n, vector<ll> &F) { for (int i = 0; i < n; i++) if (i < rk[i]) swap(F[i], F[rk[i]]); for (int p = 2; p <= n; p <<= 1) { int len = p >> 1; ll w = qpow(op ? G : Gi, (Mod - 1) / p); for (int k = 0; k < n; k += p) { ll now = 1; for (int l = k; l < k + len; l++) { ll t = F[l + len] * now % Mod; F[l + len] = (F[l] - t + Mod) % Mod; F[l] = (F[l] + t) % Mod; now = now * w % Mod; } } } } inline void Rk(const int &n) { for (int i = 0; i < n; i++) rk[i] = (rk[i >> 1] >> 1) | (i & 1 ? n >> 1 : 0); } void print(const vector<ll> &X) { for (const ll &v : X) cout << v << " "; cout << "!!!\n"; } void Mul(vector<ll> &X, vector<ll> &a, vector<ll> &b) { static vector<ll> x, y; int n = a.size() - 1, m = b.size() - 1; x = a, y = b; for (m += n, n = 1; n <= m; n <<= 1) ; Rk(n); x.resize(n), y.resize(n); NTT(1, n, x), NTT(1, n, y); for (int i = 0; i < n; i++) x[i] = x[i] * y[i] % Mod; NTT(0, n, x); ll inv = qpow(n); X.resize(m + 1); for (int i = 0; i <= m; i++) X[i] = x[i] * inv % Mod; } void Inv(int n, vector<ll> &a, vector<ll> &b) { static vector<ll> x; if (n == 1) { b.resize(1); b[0] = qpow(a[0]); return; } Inv((n + 1) >> 1, a, b); const int m = n; for (n = 1; n < (m << 1); n <<= 1) ; Rk(n); x = a; x.resize(n), b.resize(n); for (int i = m; i < n; i++) x[i] = 0; NTT(1, n, x), NTT(1, n, b); for (int i = 0; i < n; i++) b[i] = b[i] * (2ll - x[i] * b[i] % Mod + Mod) % Mod; NTT(0, n, b); ll inv = qpow(n); b.resize(m); for (int i = 0; i < m; i++) b[i] = b[i] * inv % Mod; } void Ln(vector<ll> &a, vector<ll> &b) { static vector<ll> x; const int n = a.size(); Inv(n, a, x); b.resize(n); for (int i = 0; i < n - 1; i++) b[i] = a[i + 1] * (i + 1) % Mod; b[n - 1] = 0; Mul(x, b, x); for (int i = 1; i < n; i++) b[i] = x[i - 1] * qpow(i) % Mod; b[0] = 0; } void Exp(int n, vector<ll> &a, vector<ll> &b) { static vector<ll> x, y; if (n == 1) { b.resize(1); b[0] = 1; return; } Exp((n + 1) >> 1, a, b); int m = n; for (n = 1; n < (m << 1); n <<= 1) ; y = a; y.resize(n); for (int i = m; i < n; i++) y[i] = 0; b.resize(m), Ln(b, x); b.resize(n), x.resize(n); NTT(1, n, x), NTT(1, n, y), NTT(1, n, b); for (int i = 0; i < n; i++) b[i] = (1ll - x[i] + y[i] + Mod) % Mod * b[i] % Mod; NTT(0, n, b); ll inv = qpow(n); b.resize(m); for (int i = 0; i < m; i++) b[i] = b[i] * inv % Mod; } void Sqrt(int n, vector<ll> &a, vector<ll> &b) { static vector<ll> x, y; if (n == 1) { b.resize(1); b[0] = 1; return; } Sqrt((n + 1) >> 1, a, b); int m = n; for (n = 1; n < (m << 1); n <<= 1) ; b.resize(m), Inv(m, b, x); y = a, y.resize(m); Mul(y, x, y); for (int i = 0; i < m; i++) b[i] = (b[i] + y[i]) % Mod * inv2 % Mod; } void Kpow(vector<ll> &a, const ll &k) { static vector<ll> x; const int n = a.size(); Ln(a, x); x.resize(n + 1); for (int i = 0; i <= n; i++) x[i] = x[i] * k % Mod; Exp(n + 1, x, a); }``` === Catalan ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const ll N=101010; const ll p=998244353; ll T; ll n; ll f[N],ni[N]; ll ksm(ll a,ll b) { ll sum = 1; while(b) { if(b&1) sum = (sum*a) % p; b >>= 1; a = (a*a) % p; } return sum; } void qiu(ll h) { f[0] = ni[0] = 1; for(ll i=1;i<=h;i++) f[i] = f[i-1] * i %p; ni[h] = ksm(f[h],p-2); for(ll i=h-1;i;i--) ni[i] = ni[i+1] * (i+1) %p; } ll catalan(ll a) { return f[a<<1] * ni[a+1] %p * ni[a] %p; } ll catalan(ll a) { return C(2*a,a) - C(2*a,a-1); } ll catalan(ll a) { if(!a) return 1; ll res = 0; for(int i=0;i<=a-1;i++) res += catalan(i) * catalan(a-1-i); return res; } int main() { qiu(N-10); cin>>T; while(T--) { cin>>n; cout<<catalan(n)<<endl; } return 0; }``` === Min_25 ```cpp #include <iostream> #include <algorithm> #include <cmath> using namespace std; typedef long long ll; typedef double db; const int N = 2e5 + 7; const ll M = 1e10; const int Mod = 1e9 + 7; ll Lim, lim; ll lis[N]; int mp[N][2], cnt = 0, lpf[N], pcnt = 0, pri[N]; ll G[N][2], Fprime[N]; ll qpow(ll x, ll y) { ll ret = 1; while (y) { if (y & 1) ret = ret * x % Mod; x = x * x % Mod, y >>= 1; } return ret; } inline const int Id(const ll &x) { return x <= lim ? mp[x][0] : mp[Lim / x][1]; } inline const ll f(const ll &x) { return x % Mod * ((x - 1ll) % Mod) % Mod; } const ll inv2 = qpow(2ll, Mod - 2); const ll inv6 = qpow(6ll, Mod - 2); ll F(const ll n, const int k) { if (n < pri[k] || n <= 1) return 0; ll ans = (Fprime[Id(n)] - Fprime[Id(pri[k - 1])] + Mod) % Mod; for (int i = k; i <= pcnt && 1ll * pri[i] * pri[i] <= n; i++) for (ll pw = pri[i]; pw <= n / pri[i]; pw *= pri[i]) ans = (ans + f(pw) * F(n / pw, i + 1) % Mod + f(pw * pri[i])) % Mod; return ans; } int main() { ios::sync_with_stdio(false); cin.tie(0); int T; cin >> T; while(T--) { cin >> Lim; pri[0] = 1; lim = sqrtl(Lim); cnt = pcnt = 0; for (int i = 2; i <= lim; i++) lpf[i] = 0; for (int i = 2; i <= lim; i++) { if (!lpf[i]) { lpf[i] = ++pcnt; pri[pcnt] = i; } for (int j = 1; j <= lpf[i] && 1ll * i * pri[j] <= lim; j++) lpf[i * pri[j]] = j; } for (ll l = 1, r = 0, v; l <= Lim; l = r + 1) { r = Lim / (Lim / l); lis[++cnt] = v = Lim / l; (v <= lim ? mp[v][0] : mp[Lim / v][1]) = cnt; G[cnt][0] = (v + 2ll) % Mod * ((v - 1ll) % Mod) % Mod * inv2 % Mod; G[cnt][1] = v % Mod * ((v + 1) % Mod) % Mod * ((2ll * v + 1ll) % Mod) % Mod * inv6 % Mod; G[cnt][1] = (G[cnt][1] + Mod - 1ll) % Mod; } ll v; for (int k = 1; k <= pcnt; k++) { const ll pw = (ll)pri[k] * pri[k]; for (int i = 1; pw <= lis[i]; i++) { const int id1 = Id(lis[i] / pri[k]); const int id2 = Id(pri[k - 1]); G[i][0] = (G[i][0] - pri[k] * ((G[id1][0] - G[id2][0] + Mod) % Mod) % Mod + Mod) % Mod; G[i][1] = (G[i][1] - 1ll * pri[k] * pri[k] % Mod * ((G[id1][1] - G[id2][1] + Mod) % Mod) % Mod + Mod) % Mod; } } for (int i = 1; i <= cnt; i++) Fprime[i] = (G[i][1] - G[i][0] + Mod) % Mod; cout << (F(Lim, 1) + 1ll) % Mod << "\n"; } }``` === 求原根 ```cpp const ll N=501010; const ll qwq=3030303; const ll inf=0x3f3f3f3f; ll T; ll n,m; ll visp[qwq],pi[N],cntp; ll st[N],cnt1; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %n; bb >>= 1; aa = aa * aa %n; } return sum; } void shai(ll h) { for(ll i=2;i<=h;i++) { if(!visp[i]) pi[++cntp] = i; for(ll j=1;j<=cntp && i*pi[j]<=h;j++) { visp[ i*pi[j] ] = 1; if(i%pi[j]==0) break; } } } void chushihua() { cnt1 = 0; } int get_root(int P) { ll now = P-1; for(ll i=1;i<=cntp;i++) { if(now%pi[i]==0) st[++cnt1] = pi[i]; while(now%pi[i]==0) now /= pi[i]; } if(now!=1) st[++cnt1] = now; // for(ll i=1;i<=cnt1;i++) cout<<st[i]<<" "; for(ll i=2;;i++) { bool you = 0; for(ll j=1;j<=cnt1;j++) if(ksm(i,(P-1)/st[j])==1) { you = 1; break; } if(!you) return i; } } int main() { shai(qwq-100); while(1) { chushihua(); cin>>n; cout<<get_root(n)<<"\n"; } return 0; } // n has r when n=1,2,4,p^a,2p^a // 7 -> 3 1,3,2,6,4,5``` === excrt ```cpp ll T; ll n,m; ll a[N],b[N]; ll x,y; ll gsc(ll a,ll b,ll p) { ll sum = 0; while(b) { if(b&1) sum = (sum+a) %p; b >>= 1; a = (a<<1) %p; } return sum; } ll exgcd(ll A,ll B) { if(!B) { x = y = 0; return A; } ll res = exgcd(B,A%B); x = y; y = (res - A*x) / B; return res; } ll excrt() { ll M=a[1], res=b[1]; for(ll i=2;i<=n;i++) { ll A = M, B = a[i], C = ((b[i]-res)%B+B)%B; //Ax=C (mod B) ll d = exgcd(A,B); if(C%d) return -1; B /= d; C /= d; x = gsc(x,C,B); res += x * M; M *= B; res = (res%M+M) %M; } return res; } int main() { n = read(); for(ll i=1;i<=n;i++) { a[i] = read(); b[i] = read(); } cout<<excrt(); return 0; } /* 5 998244353 469904850 998244389 856550978 998244391 656199240 998244407 51629743 998244431 642142204 99999999999000019 //this case cannot pass */ ``` === BSGS ```cpp map <ll,ll> f; inline ll BSGS(ll a,ll b,ll p) { // a ^ res = b (mod p) f.clear(); ll now = b % p; ll sq = sqrt(p) + 1; ll at = ksm(a,sq,p); f[now] = 0; for(ll i=1;i<=sq;i++) { now = now * a %p; f[now] = i; } now = 1; for(ll i=1;i<=sq;i++) { now = now * at %p; if(f[now]) return (i * sq %p - f[now] + p) %p; } return -1; }``` == 其他 === 区间加等差数列 ```cpp void add(int l,int r,db a0,db d) { if(l>r) return ; db mo = a0 + (r-l) * d; cha2[l] += a0; cha2[l+1] -= a0-d; cha2[r+1] -= mo+d; cha2[r+2] += mo; }``` === make ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const ll N=201010; ll rrand(ll L,ll R) { return (rand() * rand() + rand()) % (R-L+1) + L; } ll T = 10, n ; int main() { freopen("data.in","w",stdout); srand(time(NULL)^getpid()); mt19937_64 rng(random_device{}()); // val[i] = rng(); cout<<T<<"\n"; while(T--) { } return 0; }``` === 子集FWT ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const ll N=501010; const ll inf=0x3f3f3f3f; const ll p=998244353, inv2=499122177; inline ll read() { ll sum = 0, ff = 1; char c = getchar(); while(c<'0' || c>'9') { if(c=='-') ff = -1; c = getchar(); } while(c>='0'&&c<='9') { sum = (sum * 10 + c - '0') %p; c = getchar(); } return sum * ff; } ll K, da; ll a[N],b[N],c[N]; ll A[N],B[N]; inline void OR(ll *F,ll cl) { for(ll o=2;o<=da;o<<=1) { for(ll i=0,k=o>>1;i<da;i+=o) { for(ll j=0;j<k;j++) { F[i+j+k] = (F[i+j+k] + F[i+j]*cl + p) %p; } } } } inline void AND(ll *F,ll cl) { for(ll o=2;o<=da;o<<=1) { for(ll i=0,k=o>>1;i<da;i+=o) { for(ll j=0;j<k;j++) { F[i+j] = (F[i+j] + F[i+j+k]*cl + p) %p; } } } } inline void XOR(ll *F,ll cl) { for(ll o=2;o<=da;o<<=1) { for(ll i=0,k=o>>1;i<da;i+=o) { for(ll j=0;j<k;j++) { ll X = F[i+j], Y = F[i+j+k]; F[i+j] = (X+Y) * (cl==1?1:inv2) %p; F[i+j+k] = (X-Y+p) * (cl==1?1:inv2) %p; } } } } void juan(ll *H,ll *F,ll *G) { for(int i=0;i<da;i++) A[i] = F[i], B[i] = G[i]; OR(A, 1); OR(B, 1); for(int i=0;i<da;i++) A[i] = A[i] * B[i] %p; OR(A, -1); for(int i=0;i<da;i++) H[i] = A[i]; } int main() { K = read(); da = 1<<K; for(ll i=0;i<da;i++) a[i] = read(); for(ll i=0;i<da;i++) b[i] = read(); juan(c, a, b); for(ll i=0;i<da;i++) cout<<c[i]<<" "; return 0; }``` === 取模优化 ```cpp double dp; inline ll mod(ll A) { return A - (ll)(A / dp) * p; }``` === 二维hash ```cpp struct Hash { ll p=998244353, m1=2333, m2=13331; ll f1[N], f2[N]; ll h[N][N], a[N][N]; void init() { f1[0] = f2[0] = 1; for(int i=1;i<=n;i++) f1[i] = f1[i-1] * m1 %p; for(int i=1;i<=m;i++) f2[i] = f2[i-1] * m2 %p; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { h[i][j] = (h[i-1][j]*m1%p + h[i][j-1]*m2%p - h[i-1][j-1]*m1%p*m2%p + a[i][j] + p) %p; } } } ll calc(ll i,ll j,ll I,ll J) { i--; j--; ll X = f1[I-i], Y = f2[J-j]; return (h[I][J] - h[i][J]*X%p - h[I][j]*Y%p + h[i][j]*X%p*Y%p + 2*p) %p; } }; ``` === 树上莫队 ```cpp ll f[N][24]; ll dep[N],siz[N]; ll st[N],ed[N],ob[N],cnt; struct Q{ ll id,l,r,lca; } q[N]; inline bool cmp(Q A,Q B) { if(A.l/K != B.l/K) return A.l < B.l; if((A.l/K)&1) return A.r < B.r; else return A.r > B.r; } void DFS(ll u) { dep[u] = dep[f[u][0]] + 1; siz[u] = 1; st[u] = ++cnt; ob[cnt] = u; for(ll v : e[u]) { DFS(v); siz[u] += siz[v]; } ed[u] = ++cnt; ob[cnt] = u; } inline void add(ll u) { // cout<<"add("<<u<<")\n"; ll c = num[u]; num[u] ^= 1; if(c) (res -= dp[u]-p) %= p; else (res += dp[u]) %= p; } int main() { n = read(); m = read(); for(ll i=1;i<=m;i++) { x = read(); y = read(); if(st[x]>st[y]) swap(x,y); ll lca = LCA(x,y); if(lca==x) q[i] = {i,st[x],st[y],0}; else q[i] = {i,ed[x],st[y],lca}; } sort(q+1,q+m+1,cmp); ll L = q[1].l, R = q[1].l; res = dp[ ob[L] ]; num[ ob[L] ] = 1; for(ll i=1;i<=m;i++) { // cout<<q[i].l<<" "<<q[i].r<<" i = "<<i<<"\n"; while(L>q[i].l) add(ob[--L]); while(R<q[i].r) add(ob[++R]); while(L<q[i].l) add(ob[L++]); while(R>q[i].r) add(ob[R--]); // cout<<"res = "<<res<<"\n"; if(q[i].lca) add(q[i].lca); ans[ q[i].id ] = res; if(q[i].lca) add(q[i].lca); } return 0; }``` === 子集卷积 ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const ll N=2020202; const ll inf=0x3f3f3f3f; const ll p=1000000009; ll K, da; ll a[N],b[N],c[N]; ll A[22][N], B[22][N], C[22][N], wei[N]; inline void OR(ll *F,ll cl) { for(ll o=2;o<=da;o<<=1) { for(ll i=0,k=o>>1;i<da;i+=o) { for(ll j=0;j<k;j++) { F[i+j+k] = (F[i+j+k] + F[i+j]*cl + p) %p; } } } } void juan(ll *H,ll *F,ll *G) { for(ll i=0;i<da;i++) A[wei[i]][i] = F[i]; for(ll i=0;i<da;i++) B[wei[i]][i] = G[i]; for(ll i=0;i<=K;i++) { OR(A[i], 1); OR(B[i], 1); } for(ll i=0;i<=K;i++) { for(ll j=0;j<=i;j++) { for(ll k=0;k<da;k++) { (C[i][k] += A[j][k]*B[i-j][k] %p) %= p; } } } for(ll i=0;i<=K;i++) OR(C[i], -1); for(ll i=0;i<da;i++) H[i] = C[wei[i]][i]; } int main() { for(ll i=1;i<=N-10;i++) wei[i] = wei[i^(i&-i)] + 1; K = read(); da = 1<<K; for(ll i=0;i<da;i++) a[i] = read(); for(ll i=0;i<da;i++) b[i] = read(); juan(c, a, b); for(ll i=0;i<da;i++) cout<<c[i]<<" "; return 0; }``` === 前缀线性基PLB ```cpp using namespace std; const ll N=505050; const ll qwq=303030; const ll inf=0x3f3f3f3f; int n,Q; struct PLB{ int d[22], pos[22]; void insert(int x,int wei) { for(int i=21;i>=0;i--) { if(!((x>>i)&1)) continue; if(!d[i]) { d[i] = x; pos[i] = wei; return ; } if(pos[i]<wei) { swap(pos[i],wei); swap(d[i],x); } x ^= d[i]; } } int query_max(int l) { int ans = 0; for(int i=21;i>=0;i--) if(d[i] && pos[i]>=l) ans = max(ans,ans^d[i]); return ans; } bool query(int k,int l) { for(int i=21;i>=0;i--) { if(!(k>>i)) continue; if(!d[i] || pos[i]<l) return 0; k ^= d[i]; } return 1; } }B[N]; int main() { int l,r; n = read(); for(int i=1;i<=n;i++) { B[i] = B[i-1]; B[i].insert(read(),i); } Q = read(); while(Q--) { l = read(); r = read(); cout<<B[r].query(l)<<"\n"; } return 0; } ``` === 售货员 ```cpp #define ls now<<1 #define rs now<<1|1 using namespace std; const int N=1044*1044; const int qwq=2003030; const int inf=0x3f3f3f3f; int n,tot; int w[23][23]; int f[N][21]; int ans=inf; int main() { n = read(); tot = (1<<n)-1; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) w[i][j] = read(); memset(f,0x3f,sizeof(f)); f[1][1] = 0; for(int i=3;i<=tot;i++) { for(int j=1;j<=n;j++) { if((i>>j-1)&1) for(int k=1;k<=n;k++) if((i>>k-1)&1) f[i][j] = min(f[i][j], f[i^(1<<j-1)][k]+w[j][k]); } } // cout<<f[tot][n]; 终点n结束 // cout<<MIN{ f[tot][i] }; 任意点结束 // cout<<MIN{ w[1][i]+f[tot][i] }; 返回 1 结束 return 0; } /* */ ``` === 线性基 ```cpp ll n; ll a[N]; ll d[N]; ll ans; int main() { n = read(); for(ll i=1;i<=n;i++) a[i] = read(); for(ll i=1;i<=n;i++) { ll x = a[i]; for(ll j=60;j>=0;j--) { if(!(x>>j)) continue; if(!d[j]) { d[j] = x; break; } x ^= d[j]; } } for(ll j=60;j>=0;j--) { if((ans^d[j])>ans) ans ^= d[j]; } cout<<ans; return 0; }``` === 子集dp ```cpp for(int i=u; i; i=(i-1)&u) f[u] += f[i]; // 枚举子集 // 高维前缀和: for(int k=0;k<=19;k++) for(int i=0;i<=maxn;i++) if((i>>k)&1) g[i] += g[i^(1<<k)]; // i 是超集,有第 k 位 // 高维后缀和: for(int k=0;k<=19;k++) for(int i=0;i<=maxn;i++) if(!((i>>k)&1)) g[i] += g[i^(1<<k)]; // i 是子集,无第 k 位 // 前缀差分: for(int k=0;k<=19;k++) for(int i=0;i<=maxn;i++) if((i>>k)&1) f[i] -= f[i^(1<<k)]; // i 的前缀和减去 i 的子集,就是 i 本身。 // 后缀差分: for(int k=0;k<=19;k++) for(int i=0;i<=maxn;i++) if(!((i>>k)&1)) f[i] -= f[i^(1<<k)]; // i 的后缀和减去 i 的超集,就是 i 本身。``` === ksc ```cpp IL int qmul(int x,int y,int mod) { return (x*y-(long long)((long double)x/mod*y)*mod+mod)%mod; }``` === duipai ```cpp #include <bits/stdc++.h> using namespace std; int main() { int Case = 1; while(1) { printf("The result of No. %d Case is: ", ++Case); system("make"); //windows不加"./",linux下需要在可执行文件的文件名前加"./" system("A"); system("A2"); if(system("fc A.out A2.out")) { //linux 环境用 system("diff *** ***"); printf("qwq"); return 0; } else printf("No different\n"); } return 0; }``` === 异或分段 ```cpp ll T; ll m,P; struct D{ ll l,r; }d[N]; inline bool cmp(D A,D B) { return A.l < B.l; } ll cnt; void get_fen(ll R,ll X) { // [0, R] ^= X ---> [ d[i].l, d[i].r ] ll da = 1ll << 60ll; d[cnt=1] = {0,R}; for(ll i=60;i>=0;i--,da>>=1) { if(d[1].l+da<=d[1].r) { if((X>>i)&1) { d[++cnt] = {d[1].l+da,d[1].l+2*da-1}; d[1].r -= da; } else { d[++cnt] = {d[1].l,d[1].l+da-1}; d[1].l += da; } } else if((X>>i)&1) d[1].l += da, d[1].r += da; } sort(d+1,d+cnt+1,cmp); // for(ll i=1;i<=cnt;i++) cout<<d[i].l<<" "<<d[i].r<<"\n"; }``` === 火车头 ```cpp #pragma GCC optimize("Ofast") #pragma GCC optimize("inline") #pragma GCC optimize("-fgcse") #pragma GCC optimize("-fgcse-lm") #pragma GCC optimize("-fipa-sra") #pragma GCC optimize("-ftree-pre") #pragma GCC optimize("-ftree-vrp") #pragma GCC optimize("-fpeephole2") #pragma GCC optimize("-ffast-math") #pragma GCC optimize("-fsched-spec") #pragma GCC optimize("unroll-loops") #pragma GCC optimize("-falign-jumps") #pragma GCC optimize("-falign-loops") #pragma GCC optimize("-falign-labels") #pragma GCC optimize("-fdevirtualize") #pragma GCC optimize("-fcaller-saves") #pragma GCC optimize("-fcrossjumping") #pragma GCC optimize("-fthread-jumps") #pragma GCC optimize("-funroll-loops") #pragma GCC optimize("-fwhole-program") #pragma GCC optimize("-freorder-blocks") #pragma GCC optimize("-fschedule-insns") #pragma GCC optimize("inline-functions") #pragma GCC optimize("-ftree-tail-merge") #pragma GCC optimize("-fschedule-insns2") #pragma GCC optimize("-fstrict-aliasing") #pragma GCC optimize("-fstrict-overflow") #pragma GCC optimize("-falign-functions") #pragma GCC optimize("-fcse-skip-blocks") #pragma GCC optimize("-fcse-follow-jumps") #pragma GCC optimize("-fsched-interblock") #pragma GCC optimize("-fpartial-inlining") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("-freorder-functions") #pragma GCC optimize("-findirect-inlining") #pragma GCC optimize("-frerun-cse-after-loop") #pragma GCC optimize("inline-small-functions") #pragma GCC optimize("-finline-small-functions") #pragma GCC optimize("-ftree-switch-conversion") #pragma GCC optimize("-foptimize-sibling-calls") #pragma GCC optimize("-fexpensive-optimizations") #pragma GCC optimize("-funsafe-loop-optimizations") #pragma GCC optimize("inline-functions-called-once") #pragma GCC optimize("-fdelete-null-pointer-checks")``` == 几何 === cjj ```cpp #include <bits/stdc++.h> using namespace std; using point_t = long double; //全局数据类型,可修改为 long long 等 constexpr point_t eps = 1e-8; constexpr long double PI = 3.1415926535897932384l; // 点与向量 template<typename T> struct point { T x, y; point() = default; point(T x, T y) : x(x), y(y) {} bool operator==(const point &a) const { return (abs(x - a.x) <= eps && abs(y - a.y) <= eps); } bool operator<(const point &a) const { if (abs(x - a.x) <= eps) return y < a.y - eps; return x < a.x - eps; } bool operator>(const point &a) const { return !(*this < a || *this == a); } point operator+(const point &a) const { return {x + a.x, y + a.y}; } point operator-(const point &a) const { return {x - a.x, y - a.y}; } point operator-() const { return {-x, -y}; } point operator*(const T k) const { return {k * x, k * y}; } point operator/(const T k) const { return {x / k, y / k}; } T operator*(const point &a) const { return x * a.x + y * a.y; } // 点积 T operator^(const point &a) const { return x * a.y - y * a.x; } // 叉积,注意优先级 int toleft(const point &a) const { const auto t = (*this) ^ a; return (t > eps) - (t < -eps); } // to-left 测试 T len2() const { return (*this) * (*this); } // 向量长度的平方 T dis2(const point &a) const { return (a - (*this)).len2(); } // 两点距离的平方 // 涉及浮点数 long double len() const { return hypotl(x, y); } // 向量长度 long double dis(const point &a) const { return ((*this) - a).len(); } // 两点距离 long double ang(const point &a) const { return acosl(max(-1.0l, min(1.0l, ((*this) * a) / (len() * a.len())))); } // 向量夹角 point rot(const long double rad) const { return {x * cos(rad) - y * sin(rad), x * sin(rad) + y * cos(rad)}; } // 逆时针旋转(给定角度) point rot(const long double cosr, const long double sinr) const { return {x * cosr - y * sinr, x * sinr + y * cosr}; } // 逆时针旋转(给定角度的正弦与余弦) }; using Point = point<point_t>; // 极角排序 struct argcmp { bool operator()(const Point &a, const Point &b) const { const auto quad = [](const Point &a) { if (a.y < -eps) return 1; if (a.y > eps) return 4; if (a.x < -eps) return 5; if (a.x > eps) return 3; return 2; }; const int qa = quad(a), qb = quad(b); if (qa != qb) return qa < qb; const auto t = a ^ b; if (abs(t) <= eps) return a.len2() < b.len2() - eps; // 不同长度的向量需要分开 return t > eps; } }; // 直线 template<typename T> struct line { point<T> p, v; // p 为直线上一点,v 为方向向量 bool operator==(const line &a) const { return v.toleft(a.v) == 0 && v.toleft(p - a.p) == 0; } int toleft(const point<T> &a) const { return v.toleft(a - p); } // to-left 测试 bool operator<(const line &a) const // 半平面交算法定义的排序 { if (abs(v ^ a.v) <= eps && v * a.v >= -eps) return toleft(a.p) == -1; return argcmp()(v, a.v); } // 涉及浮点数 point<T> inter(const line &a) const { return p + v * ((a.v ^ (p - a.p)) / (v ^ a.v)); } // 直线交点 long double dis(const point<T> &a) const { return abs(v ^ (a - p)) / v.len(); } // 点到直线距离 point<T> proj(const point<T> &a) const { return p + v * ((v * (a - p)) / (v * v)); } // 点在直线上的投影 }; using Line = line<point_t>; //线段 template<typename T> struct segment { point<T> a, b; bool operator<(const segment &s) const { return make_pair(a, b) < make_pair(s.a, s.b); } // 判定性函数建议在整数域使用 // 判断点是否在线段上 // -1 点在线段端点 | 0 点不在线段上 | 1 点严格在线段上 int is_on(const point<T> &p) const { if (p == a || p == b) return -1; return (p - a).toleft(p - b) == 0 && (p - a) * (p - b) < -eps; } // 判断线段直线是否相交 // -1 直线经过线段端点 | 0 线段和直线不相交 | 1 线段和直线严格相交 int is_inter(const line<T> &l) const { if (l.toleft(a) == 0 || l.toleft(b) == 0) return -1; return l.toleft(a) != l.toleft(b); } // 判断两线段是否相交 // -1 在某一线段端点处相交 | 0 两线段不相交 | 1 两线段严格相交 int is_inter(const segment<T> &s) const { if (is_on(s.a) || is_on(s.b) || s.is_on(a) || s.is_on(b)) return -1; const line<T> l{a, b - a}, ls{s.a, s.b - s.a}; return l.toleft(s.a) * l.toleft(s.b) == -1 && ls.toleft(a) * ls.toleft(b) == -1; } // 点到线段距离 long double dis(const point<T> &p) const { if ((p - a) * (b - a) < -eps || (p - b) * (a - b) < -eps) return min(p.dis(a), p.dis(b)); const line<T> l{a, b - a}; return l.dis(p); } // 两线段间距离 long double dis(const segment<T> &s) const { if (is_inter(s)) return 0; return min({dis(s.a), dis(s.b), s.dis(a), s.dis(b)}); } }; using Segment = segment<point_t>; // 多边形 template<typename T> struct polygon { vector<point<T>> p; // 以逆时针顺序存储 size_t nxt(const size_t i) const { return i == p.size() - 1 ? 0 : i + 1; } size_t pre(const size_t i) const { return i == 0 ? p.size() - 1 : i - 1; } // 回转数 // 返回值第一项表示点是否在多边形边上 // 对于狭义多边形,回转数为 0 表示点在多边形外,否则点在多边形内 pair<bool, int> winding(const point<T> &a) const { int cnt = 0; for (size_t i = 0; i < p.size(); i++) { const point<T> u = p[i], v = p[nxt(i)]; if (abs((a - u) ^ (a - v)) <= eps && (a - u) * (a - v) <= eps) return {true, 0}; if (abs(u.y - v.y) <= eps) continue; const Line uv = {u, v - u}; if (u.y < v.y - eps && uv.toleft(a) <= 0) continue; if (u.y > v.y + eps && uv.toleft(a) >= 0) continue; if (u.y < a.y - eps && v.y >= a.y - eps) cnt++; if (u.y >= a.y - eps && v.y < a.y - eps) cnt--; } return {false, cnt}; } // 多边形面积的两倍 // 可用于判断点的存储顺序是顺时针或逆时针 T area() const { T sum = 0; for (size_t i = 0; i < p.size(); i++) sum += p[i] ^ p[nxt(i)]; return sum; } // 多边形的周长 long double circ() const { long double sum = 0; for (size_t i = 0; i < p.size(); i++) sum += p[i].dis(p[nxt(i)]); return sum; } }; using Polygon = polygon<point_t>; //凸多边形 template<typename T> struct convex : polygon<T> { // 闵可夫斯基和 convex operator+(const convex &c) const { const auto &p = this->p; vector<Segment> e1(p.size()), e2(c.p.size()), edge(p.size() + c.p.size()); vector<point<T>> res; res.reserve(p.size() + c.p.size()); const auto cmp = [](const Segment &u, const Segment &v) { return argcmp()(u.b - u.a, v.b - v.a); }; for (size_t i = 0; i < p.size(); i++) e1[i] = {p[i], p[this->nxt(i)]}; for (size_t i = 0; i < c.p.size(); i++) e2[i] = {c.p[i], c.p[c.nxt(i)]}; rotate(e1.begin(), min_element(e1.begin(), e1.end(), cmp), e1.end()); rotate(e2.begin(), min_element(e2.begin(), e2.end(), cmp), e2.end()); merge(e1.begin(), e1.end(), e2.begin(), e2.end(), edge.begin(), cmp); const auto check = [](const vector<point<T>> &res, const point<T> &u) { const auto back1 = res.back(), back2 = *prev(res.end(), 2); return (back1 - back2).toleft(u - back1) == 0 && (back1 - back2) * (u - back1) >= -eps; }; auto u = e1[0].a + e2[0].a; for (const auto &v: edge) { while (res.size() > 1 && check(res, u)) res.pop_back(); res.push_back(u); u = u + v.b - v.a; } if (res.size() > 1 && check(res, res[0])) res.pop_back(); return {res}; } // 旋转卡壳 // func 为更新答案的函数,可以根据题目调整位置 template<typename F> void rotcaliper(const F &func) const { const auto &p = this->p; const auto area = [](const point<T> &u, const point<T> &v, const point<T> &w) { return (w - u) ^ (w - v); }; for (size_t i = 0, j = 1; i < p.size(); i++) { const auto nxti = this->nxt(i); func(p[i], p[nxti], p[j]); while (area(p[this->nxt(j)], p[i], p[nxti]) >= area(p[j], p[i], p[nxti])) { j = this->nxt(j); func(p[i], p[nxti], p[j]); } } } // 凸多边形的直径的平方 T diameter2() const { const auto &p = this->p; if (p.size() == 1) return 0; if (p.size() == 2) return p[0].dis2(p[1]); T ans = 0; auto func = [&](const point<T> &u, const point<T> &v, const point<T> &w) { ans = max({ans, w.dis2(u), w.dis2(v)}); }; rotcaliper(func); return ans; } // 面积前缀和 vector<T> sum; void get_sum() { const auto &p = this->p; vector <T> a(p.size()); for (size_t i = 0; i < p.size(); i++) a[i] = p[this->pre(i)] ^ p[i]; sum.resize(p.size()); partial_sum(a.begin(), a.end(), sum.begin()); } T query_sum(const size_t l, const size_t r) const { const auto &p = this->p; if (l <= r) return sum[r] - sum[l] + (p[r] ^ p[l]); return sum[p.size() - 1] - sum[l] + sum[r] + (p[r] ^ p[l]); } T query_sum() const { return sum.back(); } // 判断点是否在凸多边形内 // 复杂度 O(logn) // -1 点在多边形边上 | 0 点在多边形外 | 1 点在多边形内 int is_in(const point<T> &a) const { const auto &p = this->p; if (p.size() == 1) return a == p[0] ? -1 : 0; if (p.size() == 2) return segment<T>{p[0], p[1]}.is_on(a) ? -1 : 0; if (a == p[0]) return -1; if ((p[1] - p[0]).toleft(a - p[0]) == -1 || (p.back() - p[0]).toleft(a - p[0]) == 1) return 0; const auto cmp = [&](const Point &u, const Point &v) { return (u - p[0]).toleft(v - p[0]) == 1; }; const size_t i = lower_bound(p.begin() + 1, p.end(), a, cmp) - p.begin(); if (i == 1) return segment<T>{p[0], p[i]}.is_on(a) ? -1 : 0; if (i == p.size() - 1 && segment<T>{p[0], p[i]}.is_on(a)) return -1; if (segment<T>{p[i - 1], p[i]}.is_on(a)) return -1; return (p[i] - p[i - 1]).toleft(a - p[i - 1]) > 0; } // 凸多边形关于某一方向的极点 // 复杂度 O(logn) // 参考资料:https://codeforces.com/blog/entry/48868 template<typename F> size_t extreme(const F &dir) const { const auto &p = this->p; const auto check = [&](const size_t i) { return dir(p[i]).toleft(p[this->nxt(i)] - p[i]) >= 0; }; const auto dir0 = dir(p[0]); const auto check0 = check(0); if (!check0 && check(p.size() - 1)) return 0; const auto cmp = [&](const Point &v) { const size_t vi = &v - p.data(); if (vi == 0) return 1; const auto checkv = check(vi); const auto t = dir0.toleft(v - p[0]); if (vi == 1 && checkv == check0 && t == 0) return 1; return checkv ^ (checkv == check0 && t <= 0); }; return partition_point(p.begin(), p.end(), cmp) - p.begin(); } // 过凸多边形外一点求凸多边形的切线,返回切点下标 // 复杂度 O(logn) // 必须保证点在多边形外 pair<size_t, size_t> tangent(const point<T> &a) const { const size_t i = extreme([&](const point<T> &u) { return u - a; }); const size_t j = extreme([&](const point<T> &u) { return a - u; }); return {i, j}; } // 求平行于给定直线的凸多边形的切线,返回切点下标 // 复杂度 O(logn) pair<size_t, size_t> tangent(const line<T> &a) const { const size_t i = extreme([&](...) { return a.v; }); const size_t j = extreme([&](...) { return -a.v; }); return {i, j}; } }; using Convex = convex<point_t>; // 点集的凸包 // Andrew 算法,复杂度 O(nlogn) Convex convexhull(vector<Point> p) { vector<Point> st; if (p.empty()) return Convex{st}; sort(p.begin(), p.end()); const auto check = [](const vector<Point> &st, const Point &u) { const auto back1 = st.back(), back2 = *prev(st.end(), 2); return (back1 - back2).toleft(u - back1) <= 0; }; for (const Point &u: p) { while (st.size() > 1 && check(st, u)) st.pop_back(); st.push_back(u); } size_t k = st.size(); p.pop_back(); reverse(p.begin(), p.end()); for (const Point &u: p) { while (st.size() > k && check(st, u)) st.pop_back(); st.push_back(u); } st.pop_back(); return Convex{st}; } // 圆 struct Circle { Point c; long double r; bool operator==(const Circle &a) const { return c == a.c && abs(r - a.r) <= eps; } long double circ() const { return 2 * PI * r; } // 周长 long double area() const { return PI * r * r; } // 面积 // 点与圆的关系 // -1 圆上 | 0 圆外 | 1 圆内 int is_in(const Point &p) const { const long double d = p.dis(c); return abs(d - r) <= eps ? -1 : d < r - eps; } // 直线与圆关系 // 0 相离 | 1 相切 | 2 相交 int relation(const Line &l) const { const long double d = l.dis(c); if (d > r + eps) return 0; if (abs(d - r) <= eps) return 1; return 2; } // 圆与圆关系 // -1 相同 | 0 相离 | 1 外切 | 2 相交 | 3 内切 | 4 内含 int relation(const Circle &a) const { if (*this == a) return -1; const long double d = c.dis(a.c); if (d > r + a.r + eps) return 0; if (abs(d - r - a.r) <= eps) return 1; if (abs(d - abs(r - a.r)) <= eps) return 3; if (d < abs(r - a.r) - eps) return 4; return 2; } // 直线与圆的交点 vector<Point> inter(const Line &l) const { const long double d = l.dis(c); const Point p = l.proj(c); const int t = relation(l); if (t == 0) return vector<Point>(); if (t == 1) return vector<Point>{p}; const long double k = sqrt(r * r - d * d); return vector<Point>{p - (l.v / l.v.len()) * k, p + (l.v / l.v.len()) * k}; } // 圆与圆交点 vector<Point> inter(const Circle &a) const { const long double d = c.dis(a.c); const int t = relation(a); if (t == -1 || t == 0 || t == 4) return vector<Point>(); Point e = a.c - c; e = e / e.len() * r; if (t == 1 || t == 3) { if (r * r + d * d - a.r * a.r >= -eps) return vector<Point>{c + e}; return vector<Point>{c - e}; } const long double costh = (r * r + d * d - a.r * a.r) / (2 * r * d), sinth = sqrt(1 - costh * costh); return vector<Point>{c + e.rot(costh, -sinth), c + e.rot(costh, sinth)}; } // 圆与圆交面积 long double inter_area(const Circle &a) const { const long double d = c.dis(a.c); const int t = relation(a); if (t == -1) return area(); if (t < 2) return 0; if (t > 2) return min(area(), a.area()); const long double costh1 = (r * r + d * d - a.r * a.r) / (2 * r * d), costh2 = (a.r * a.r + d * d - r * r) / (2 * a.r * d); const long double sinth1 = sqrt(1 - costh1 * costh1), sinth2 = sqrt(1 - costh2 * costh2); const long double th1 = acos(costh1), th2 = acos(costh2); return r * r * (th1 - costh1 * sinth1) + a.r * a.r * (th2 - costh2 * sinth2); } // 过圆外一点圆的切线 vector<Line> tangent(const Point &a) const { const int t = is_in(a); if (t == 1) return vector<Line>(); if (t == -1) { const Point v = {-(a - c).y, (a - c).x}; return vector<Line>{{a, v}}; } Point e = a - c; e = e / e.len() * r; const long double costh = r / c.dis(a), sinth = sqrt(1 - costh * costh); const Point t1 = c + e.rot(costh, -sinth), t2 = c + e.rot(costh, sinth); return vector<Line>{{a, t1 - a}, {a, t2 - a}}; } // 两圆的公切线 vector<Line> tangent(const Circle &a) const { const int t = relation(a); vector<Line> lines; if (t == -1 || t == 4) return lines; if (t == 1 || t == 3) { const Point p = inter(a)[0], v = {-(a.c - c).y, (a.c - c).x}; lines.push_back({p, v}); } const long double d = c.dis(a.c); const Point e = (a.c - c) / (a.c - c).len(); if (t <= 2) { const long double costh = (r - a.r) / d, sinth = sqrt(1 - costh * costh); const Point d1 = e.rot(costh, -sinth), d2 = e.rot(costh, sinth); const Point u1 = c + d1 * r, u2 = c + d2 * r, v1 = a.c + d1 * a.r, v2 = a.c + d2 * a.r; lines.push_back({u1, v1 - u1}); lines.push_back({u2, v2 - u2}); } if (t == 0) { const long double costh = (r + a.r) / d, sinth = sqrt(1 - costh * costh); const Point d1 = e.rot(costh, -sinth), d2 = e.rot(costh, sinth); const Point u1 = c + d1 * r, u2 = c + d2 * r, v1 = a.c - d1 * a.r, v2 = a.c - d2 * a.r; lines.push_back({u1, v1 - u1}); lines.push_back({u2, v2 - u2}); } return lines; } // 圆的反演 tuple<int, Circle, Line> inverse(const Line &l) const { const Circle null_c = {{0.0, 0.0}, 0.0}; const Line null_l = {{0.0, 0.0}, {0.0, 0.0}}; if (l.toleft(c) == 0) return {2, null_c, l}; const Point v = l.toleft(c) == 1 ? Point{l.v.y, -l.v.x} : Point{-l.v.y, l.v.x}; const long double d = r * r / l.dis(c); const Point p = c + v / v.len() * d; return {1, {(c + p) / 2, d / 2}, null_l}; } tuple<int, Circle, Line> inverse(const Circle &a) const { const Circle null_c = {{0.0, 0.0}, 0.0}; const Line null_l = {{0.0, 0.0}, {0.0, 0.0}}; const Point v = a.c - c; if (a.is_in(c) == -1) { const long double d = r * r / (a.r + a.r); const Point p = c + v / v.len() * d; return {2, null_c, {p, {-v.y, v.x}}}; } if (c == a.c) return {1, {c, r * r / a.r}, null_l}; const long double d1 = r * r / (c.dis(a.c) - a.r), d2 = r * r / (c.dis(a.c) + a.r); const Point p = c + v / v.len() * d1, q = c + v / v.len() * d2; return {1, {(p + q) / 2, p.dis(q) / 2}, null_l}; } }; // 圆与任意多边形面积交 long double area_inter(const Circle &circ, const Polygon &poly) { const auto cal = [](const Circle &circ, const Point &a, const Point &b) { if ((a - circ.c).toleft(b - circ.c) == 0) return 0.0l; const auto ina = circ.is_in(a), inb = circ.is_in(b); const Line ab = {a, b - a}; if (ina && inb) return ((a - circ.c) ^ (b - circ.c)) / 2; if (ina && !inb) { const auto t = circ.inter(ab); const Point p = t.size() == 1 ? t[0] : t[1]; const long double ans = ((a - circ.c) ^ (p - circ.c)) / 2; const long double th = (p - circ.c).ang(b - circ.c); const long double d = circ.r * circ.r * th / 2; if ((a - circ.c).toleft(b - circ.c) == 1) return ans + d; return ans - d; } if (!ina && inb) { const Point p = circ.inter(ab)[0]; const long double ans = ((p - circ.c) ^ (b - circ.c)) / 2; const long double th = (a - circ.c).ang(p - circ.c); const long double d = circ.r * circ.r * th / 2; if ((a - circ.c).toleft(b - circ.c) == 1) return ans + d; return ans - d; } const auto p = circ.inter(ab); if (p.size() == 2 && Segment{a, b}.dis(circ.c) <= circ.r + eps) { const long double ans = ((p[0] - circ.c) ^ (p[1] - circ.c)) / 2; const long double th1 = (a - circ.c).ang(p[0] - circ.c), th2 = (b - circ.c).ang(p[1] - circ.c); const long double d1 = circ.r * circ.r * th1 / 2, d2 = circ.r * circ.r * th2 / 2; if ((a - circ.c).toleft(b - circ.c) == 1) return ans + d1 + d2; return ans - d1 - d2; } const long double th = (a - circ.c).ang(b - circ.c); if ((a - circ.c).toleft(b - circ.c) == 1) return circ.r * circ.r * th / 2; return -circ.r * circ.r * th / 2; }; long double ans = 0; for (size_t i = 0; i < poly.p.size(); i++) { const Point a = poly.p[i], b = poly.p[poly.nxt(i)]; ans += cal(circ, a, b); } return ans; } // 半平面交 vector<Line> _halfinter(vector<Line> l) { constexpr double LIM = 1e9; const auto check = [](const Line &a, const Line &b, const Line &c) { return a.toleft(b.inter(c)) < 0; }; // const auto check=[](const Line &a,const Line &b,const Line &c) // { // const Point p=a.v*(b.v^c.v),q=b.p*(b.v^c.v)+b.v*(c.v^(b.p-c.p))-a.p*(b.v^c.v); // return p.toleft(q)<0; // }; l.push_back({{-LIM, 0}, {0, -1}}); l.push_back({{0, -LIM}, {1, 0}}); l.push_back({{LIM, 0}, {0, 1}}); l.push_back({{0, LIM}, {-1, 0}}); sort(l.begin(), l.end()); deque <Line> q; for (size_t i = 0; i < l.size(); i++) { if (i > 0 && l[i - 1].v.toleft(l[i].v) == 0 && l[i - 1].v * l[i].v > eps) continue; while (q.size() > 1 && check(l[i], q.back(), q[q.size() - 2])) q.pop_back(); while (q.size() > 1 && check(l[i], q[0], q[1])) q.pop_front(); q.push_back(l[i]); } while (q.size() > 1 && check(q[0], q.back(), q[q.size() - 2])) q.pop_back(); while (q.size() > 1 && check(q.back(), q[0], q[1])) q.pop_front(); if (q.size() <= 2) return vector<Line>(); return vector<Line>(q.begin(), q.end()); } Convex halfinter(const vector<Line> &l) { const auto lines = _halfinter(l); Convex poly; poly.p.resize(lines.size()); if (lines.empty()) return poly; for (size_t i = 0; i < lines.size(); i++) { const size_t j = (i == lines.size() - 1 ? 0 : i + 1); poly.p[i] = lines[i].inter(lines[j]); } poly.p.erase(unique(poly.p.begin(), poly.p.end()), poly.p.end()); if (poly.p.front() == poly.p.back()) poly.p.pop_back(); return poly; } pair<point_t, point_t> minmax_triangle(const vector<Point> &vec) { if (vec.size() <= 2) return {0, 0}; vector <pair<int, int>> evt; evt.reserve(vec.size() * vec.size()); point_t maxans = 0, minans = numeric_limits<point_t >::max(); for (size_t i = 0; i < vec.size(); i++) { for (size_t j = 0; j < vec.size(); j++) { if (i == j) continue; if (vec[i] == vec[j]) minans = 0; else evt.push_back({i, j}); } } sort(evt.begin(), evt.end(), [&](const pair<int, int> &u, const pair<int, int> &v) { const Point du = vec[u.second] - vec[u.first], dv = vec[v.second] - vec[v.first]; return argcmp()({du.y, -du.x}, {dv.y, -dv.x}); }); vector <size_t> vx(vec.size()), pos(vec.size()); for (size_t i = 0; i < vec.size(); i++) vx[i] = i; sort(vx.begin(), vx.end(), [&](int x, int y) { return vec[x] < vec[y]; }); for (size_t i = 0; i < vx.size(); i++) pos[vx[i]] = i; for (auto [u, v]: evt) { const size_t i = pos[u], j = pos[v]; const size_t _i = min(i, j), _j = max(i, j); const Point vecu = vec[u], vecv = vec[v]; if (_i > 0) minans = min(minans, abs((vec[vx[_i - 1]] - vecu) ^ (vec[vx[_i - 1]] - vecv))); if (_j < vx.size() - 1) minans = min(minans, abs((vec[vx[_j + 1]] - vecu) ^ (vec[vx[_j + 1]] - vecv))); maxans = max({maxans, abs((vec[vx[0]] - vecu) ^ (vec[vx[0]] - vecv)), abs((vec[vx.back()] - vecu) ^ (vec[vx.back()] - vecv))}); if (i < j) swap(vx[i], vx[j]), pos[u] = j, pos[v] = i; } return {minans, maxans}; }``` === lyy几何 ```cpp // 点 直线 多边形 圆类型 // 极角排序 // 重载 + - * / ^ sign == // 两点距离 两线夹角 距离平方 距离 三角形面积 点到直线投影 点绕定点旋转 向量定长 两直线交点 直线向点方向移动固定距离 // 点与圆位置关系 0 1 2 // 直线与圆的位置关系,P1,P2 为交点 // 三角形与圆面积交(三角形一点为圆心) // 多边形与圆面积交 // 两圆面积交(半径都非负) // 多边形向内缩小r // 凸多边形内最大三角形 n^2 #include <bits/stdc++.h> using namespace std; const int N=10101; typedef double db; const db pi = acos(-1.0); const db eps = 1e-8; const db inf = 1e20; const db gen2 = sqrt(2.0); struct D{ db x,y; D(){} D(db _x,db _y){x=_x;y=_y;} }; struct line{ D s,t; line(){} line(D _s,D _t){s=_s;t=_t;} }; struct pol{ int n; D d[N]; line l[N]; }; struct cir{ db x,y; db r; cir(){} cir(D P,db _r){x=P.x;y=P.y;r=_r;} }; D O = {0,0}, P = {-1,0}; inline bool cmp_point(D A,D B) { //极角排序(三象限最小,逆时针) if(atan2(A.y,A.x)*atan2(B.y,B.x)<0.0) return atan2(A.y,A.x) < atan2(B.y,B.x); return ((A-O) ^ (B-O)) > 0; } inline bool cmp_vec(D A,D B) { //极角排序 (OP向量逆时针) if(((P-O)^(A-O))==0 && (P.x-O.x)*(A.x-O.x)>0) return 1; if(((P-O)^(B-O))==0 && (P.x-O.x)*(B.x-O.x)>0) return 0; if((((P-O)^(A-O))>0) != (((P-O)^(B-O))>0)) return ((P-O)^(A-O)) > ((P-O)^(B-O)); return ((A-O) ^ (B-O)) > 0; } int sgn(db x) { if(fabs(x) < eps) return 0; if(x<0) return -1; return 1; } bool operator == (D A,D B) { return sgn(A.x-B.x)==0 && sgn(A.y-B.y)==0; } bool operator < (D A,D B) { return sgn(A.x-B.x)==0 ? sgn(A.y-B.y)<0 : A.x<B.x; } D operator - (D A,D B) { return {A.x-B.x,A.y-B.y}; } D operator + (D A,D B) { return {A.x+B.x,A.y+B.y}; } db operator ^ (D A,D B) { return A.x*B.y - B.x*A.y; } db operator * (D A,D B) { return A.x*B.x + A.y*B.y; } D operator * (D A,db k) { return {A.x*k,A.y*k}; } D operator / (D A,db k) { return {A.x/k,A.y/k}; } db dist(D A,D B) { return hypot(A.x-B.x,A.y-B.y); } //两点距离 db rad(D P,D A,D B) { return fabs( atan2( fabs((A-P)^(B-P)), (A-P)*(B-P) ) ); } db len2(D P) { return P.x*P.x + P.y*P.y; } db len1(D P) { return sqrt(len2(P)); } db SS(D A,D B,D C) { return fabs((A-B)^(A-C)) / 2.0; } //三角形面积 D lineprog(D P,line L) { //投影 D M = L.t-L.s; return L.s + ( M * (M*(P-L.s) ) ) / len2(M); } D rotate(D A,D P,db ang) { // A绕P逆时针转ang角度 A = A-P; db c = cos(ang), s = sin(ang); return {P.x + A.x*c-A.y*s, P.y + A.x*s+A.y*c}; } D trunc(D P,db k) { //向量定长 db l = len1(P); if(!sgn(l)) return P; return (P/l) * k; } D cross(line A,line B){ //两直线交点 db a1 = (A.t-A.s)^(B.s-A.s); db a2 = (A.t-A.s)^(B.t-A.s); return D((B.s.x*a2-B.t.x*a1)/(a2-a1),(B.s.y*a2-B.t.y*a1)/(a2-a1)); } line move(line L,D P,db r) { //L向P方向移动距离r D H = lineprog(P,L); D vec = trunc(P-H,r); return {L.s+vec,L.t+vec}; } int relat_D(D A,cir C) { //点与圆位置关系 db d = dist(A,{C.x,C.y}); if(sgn(d-C.r) < 0) return 2; if(sgn(d-C.r) > 0) return 0; // 0在外 return 1; } int relat_L(line L,cir C,D &p1,D &p2) { //直线与圆的位置关系,P1,P2 为交点 D P = {C.x,C.y}; D A = lineprog(P,L); db d = dist(A,P); if(sgn(d-C.r)>0) return 0; if(sgn(d-C.r)==0) { p1=A; p2=A; return 1; } d = sqrt(C.r*C.r-d*d); p1 = A + trunc(L.t-L.s,d); p2 = A - trunc(L.t-L.s,d); return 2; } db TCArea(D A,D B,cir C) { //三角形与圆面积交(三角形一点为圆心) D P = {C.x,C.y}; if(sgn((P-A)^(P-B))==0) return 0.0; line L(A,B); D q[5]; int cnt = 0; q[cnt++] = A; if(relat_L(L,C,q[1],q[2])==2) { if(sgn((A-q[1])*(B-q[1])) < 0) q[cnt++] = q[1]; if(sgn((A-q[2])*(B-q[2])) < 0) q[cnt++] = q[2]; } q[cnt++] = B; if(cnt==4 && sgn((q[0]-q[1])*(q[2]-q[1])) > 0) swap(q[1],q[2]); db ans = 0; for(int i=0; i<cnt-1; i++) { if(relat_D(q[i],C)==0 || relat_D(q[i+1],C)==0) ans += C.r*C.r*rad(P,q[i],q[i+1])/2.0; else ans += fabs((q[i]-P)^(q[i+1]-P))/2.0; } return ans; } db PCArea(pol P,cir C) { //多边形与圆面积交 db ans = 0; D O = {C.x,C.y}; for(int i=0;i<P.n;i++) { int j = (i+1) % P.n; db S = TCArea(P.d[i], P.d[j], C); if(sgn( (P.d[i]-O)^(P.d[j]-O) ) >= 0) ans += S; else ans -= S; } return ans; } db CCArea(cir c1,cir c2) { //两圆面积交(半径都非负) db d = sqrt( (c1.x-c2.x)*(c1.x-c2.x) + (c1.y-c2.y)*(c1.y-c2.y) ); if(d>=c1.r+c2.r) return 0; if(c1.r-c2.r>=d) return pi * c2.r * c2.r; if(c2.r-c1.r>=d) return pi * c1.r * c1.r; db ang1 = acos( (d*d + c1.r*c1.r - c2.r*c2.r) / (2*c1.r*d) ); db ang2 = acos( (d*d + c2.r*c2.r - c1.r*c1.r) / (2*c2.r*d) ); db s1 = ang1 * c1.r*c1.r; db s2 = ang2 * c2.r*c2.r; db s3 = d * c1.r * sin(ang1); return s1+s2-s3; } bool check(line A,line B,line C,db r) { //检查缩小后的边 D p1 = B.t, p2 = C.s, p3 = A.s, p4 = A.t; line nB = move(B,p3,r); line nC = move(C,p4,r); line nA = move(A,p1,r); D p5 = cross(nA,nC); D p6 = cross(nA,nB); return sgn( (p6-p5)*(A.t-A.s) ) > 0; } pol shrink_pol(pol P,db r) { //多边形向内缩小r pol Q; Q.n = 0; line A,B,C; for(int i=0;i<P.n;i++) { A = P.l[i]; if(i!=P.n-1) B = P.l[i+1]; else B = Q.l[0]; if(Q.n) C = Q.l[Q.n-1]; else C = P.l[P.n-1]; if(check(A,B,C,r)) Q.l[Q.n++] = A; } pol SQ; SQ.n = Q.n; for(int i=0;i<Q.n;i++) Q.d[i] = Q.l[i].s; for(int i=0;i<Q.n;i++) SQ.l[i] = move(Q.l[i],Q.d[(i+2)%Q.n],r); for(int i=0;i<Q.n;i++) SQ.d[i] = cross(SQ.l[i],SQ.l[(i-1+Q.n)%Q.n]); return SQ; } db max_T(pol P) { //凸多边形内最大三角形 n^2 db ans = 0; for(int i=0;i<P.n;i++) { D S1 = P.d[i]; int j = (i+1)%P.n; int k1 = (i+1)%P.n; int k2 = (i+2)%P.n; while(j!=i) { D S2 = P.d[j]; if(j!=(i+1)%P.n) { while((k1+1)%P.n!=j && SS(S1,S2,P.d[k1]) < SS(S1,S2,P.d[(k1+1)%P.n])) k1 = (k1+1) % P.n; ans = max(ans,SS(S1,S2,P.d[k1])); } if((j+1)%P.n!=i) { while((k2+1)%P.n!=i && SS(S1,S2,P.d[k2]) < SS(S1,S2,P.d[(k2+1)%P.n])) k2 = (k2+1) % P.n; ans = max(ans,SS(S1,S2,P.d[k2])); } j = (j+1) % P.n; } } return ans; } void outing(db as) { cout<<fixed<<setprecision(6)<<as<<endl; } ``` === lyy凸包 ```cpp const int N=101010; const int qwq=303030; const int inf=0x3f3f3f3f; typedef double db; int n,cnt; struct D{ double x,y; D(double xx=0,double yy=0) { x=xx, y=yy; } } d[N],st[N]; D operator - (D A,D B) { return {A.x-B.x,A.y-B.y}; } db operator ^ (D A,D B) { return A.x*B.y - B.x*A.y; } inline bool cmp(D aa,D bb) { return (aa.x==bb.x) ? (aa.y<bb.y) : (aa.x<bb.x); } double ans; double ju(D aa,D bb) { return sqrt( (aa.x-bb.x)*(aa.x-bb.x) + (aa.y-bb.y)*(aa.y-bb.y) ); } void TUBAO() { st[1] = d[1]; st[2] = d[2]; cnt = 2; for(int i=3;i<=n;i++) { while(cnt>1 && ((st[cnt]-st[cnt-1])^(d[i]-st[cnt-1]))<=0) cnt--; st[++cnt] = d[i]; } st[++cnt] = d[n-1]; for(int i=n-2;i>=1;i--) { while(cnt>1 && ((st[cnt]-st[cnt-1])^(d[i]-st[cnt-1]))<=0) cnt--; st[++cnt] = d[i]; } } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%lf%lf",&d[i].x,&d[i].y); sort(d+1,d+n+1,cmp); if(n==1) { cout<<0; return 0; } TUBAO(); for(int i=2;i<=cnt;i++) ans += ju(st[i],st[i-1]); printf("%.2lf",ans); return 0; } ``` == 图论 === tarjan求点双边数 ```cpp int n,m; int qiao,tot,dian,da,shuang; int bian; int dfn[N],low[N],tim; int st[N],cnt; bool in[N]; vector <int> e[N],d[N]; void tarjan(int u,int zu) { dfn[u] = low[u] = ++tim; st[++cnt] = u; int son = 0; FOR() { int v = e[u][i]; if(!dfn[v]) { son++; tarjan(v,zu); low[u] = min(low[u],low[v]); if(low[v]==dfn[u]) { ++tot; while(1) { int now = st[cnt--]; d[tot].push_back(now); d[now].push_back(tot); if(now==v) break; } d[tot].push_back(u); d[u].push_back(tot); } } else low[u] = min(low[u],dfn[v]); } if(u==zu) cnt = 0; } int query(int fang) { int res = 0; for(int i=0;i<d[fang].size();i++) in[ d[fang][i] ] = 1; for(int i=0;i<d[fang].size();i++) { int u = d[fang][i]; for(int j=0;j<e[u].size();j++) { int v = e[u][j]; if(in[v]) res++; } } for(int i=0;i<d[fang].size();i++) in[ d[fang][i] ] = 0; return res/2; } int main() { int x,y; n = read(); m = read(); tot = n; for(int i=1;i<=m;i++) { x = read(); y = read(); e[x].push_back(y); e[y].push_back(x); } for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i,i); for(int i=1;i<=n;i++) if(d[i].size()>=2) dian++; for(int i=n+1;i<=tot;i++) { if(d[i].size()==2) bian++; if(d[i].size()>=2) shuang++; } for(int i=n+1;i<=tot;i++) da = max(da,query(i)); cout<<dian<<" "<<bian<<" "<<shuang<<" "<<da; return 0; } ``` === Stoer-Wagner ```cpp const int N=1010; const int qwq=303030; const int inf=0x3f3f3f3f; int T; int n,m; int ans = inf, a[N]; int dis[N][N]; int belong[N],vis[N],w[N]; void SW() { for(int h=n;h>=2;h--) { memset(vis,0,sizeof(vis)); memset(w,0,sizeof(w)); int t = 0, s = 0; for(int i=1;i<=h;i++) { s = t; t = 0; for(int j=1;j<=n;j++) { if(!belong[j] && !vis[j] && w[j]>=w[t]) t = j; } vis[t] = 1; for(int j=1;j<=n;j++) { if(!belong[j] && !vis[j]) w[j] += dis[t][j]; } } belong[t] = s; ans = min(ans,w[t]); for(int j=1;j<=n;j++) { dis[s][j] += dis[t][j]; dis[j][s] += dis[j][t]; } } } int main() { int x,y,z; n = read(); m = read(); for(int i=1;i<=m;i++) { x = read(); y = read(); dis[x][y] = dis[y][x] = 1; } SW(); cout<<ans; return 0; } ``` === 点分治 ```cpp int n,Q; struct E{ int to,we; }; vector <E> e[N]; int q[N],ans[N]; int big[N],sss,rt; int siz[N],vis[N],dis[N]; int st[N],cnt; int st2[N],cnt2; bool f[qwq]; void getid(int u,int fa) { siz[u] = 1; big[u] = 0; FOR() { int v = e[u][i].to; if(v==fa || vis[v]) continue; getid(v,u); siz[u] += siz[v]; big[u] = max(big[u],siz[v]); } big[u] = max(big[u],sss-siz[u]); if(big[u] < big[rt]) rt = u; } void DFS(int u,int fa) { if(dis[u]>10000000) return ; st[++cnt] = dis[u]; FOR() { int v = e[u][i].to; if(vis[v] || v==fa) continue; dis[v] = dis[u] + e[u][i].we; DFS(v,u); } } void calc(int u) { FOR() { int v = e[u][i].to; if(vis[v]) continue; dis[v] = e[u][i].we; DFS(v,u); for(int j=1;j<=cnt;j++) { int d = st[j]; for(int l=1;l<=Q;l++) if(q[l]>=d) ans[l] |= f[q[l]-d]; } while(cnt) { f[ st[cnt] ] = 1; st2[++cnt2] = st[cnt--]; } } while(cnt2) f[st2[cnt2--]] = 0; } void TREE(int u) { vis[u] = f[0] = 1; // only TREE->u is visited. calc(u); FOR() { int v = e[u][i].to; if(vis[v]) continue; big[rt=0] = sss = siz[v]; getid(v,0); TREE(rt); } } int main() { int x,y,z; n = read(); Q = read(); for(int i=1;i<n;i++) { x = read(); y = read(); z = read(); e[x].push_back((E){y,z}); e[y].push_back((E){x,z}); } for(int i=1;i<=Q;i++) q[i] = read(); big[rt=0] = sss = n; getid(1,0); TREE(rt); for(int i=1;i<=Q;i++) { if(ans[i]) printf("AYE\n"); else printf("NAY\n"); } return 0; }``` === 差分约束 ```cpp #include <bits/stdc++.h> #define FOR() int le=e[u].size();for(int i=0;i<le;i++) using namespace std; const int N=101010; const int inf=0x3f3f3f3f; int n,m; int dis[N],dep[N],in[N]; struct E{ int to,we; }; vector <E> e[N]; queue <int> q; bool SPFA() { memset(dis,0x3f,sizeof(dis)); // min dis : the max solution // memset(dis,-0x3f,sizeof(dis)); // max dis : the min solution dis[0] = 0; q.push(0); while(!q.empty()) { int u = q.front(); q.pop(); in[u] = 0; FOR() { int v = e[u][i].to, w = e[u][i].we; if(dis[v] > dis[u] + w) { // max solution // if(dis[v] < dis[u] + w) { // min solution dis[v] = dis[u] + w; dep[v] = dep[u] + 1; if(dep[v]>n) return 0; if(!in[v]) q.push(v); in[v] = 1; } } } return 1; } int main() { int x,y,z; n = read(); m = read(); while(m--) { x = read(); y = read(); z = read(); // x-y <= z e[y].push_back( (E){x,z} ); // x <= y+z the max solution // e[x].push_back( (E){y,-z} ); // y >= x-z the min solution } for(int i=1;i<=n;i++) e[0].push_back( (E){i,0} ); if(!SPFA()) { cout<<"NO"; return 0; } for(int i=1;i<=n;i++) cout<<dis[i]<<" "; return 0; }``` === 圆方树 ```cpp const ll N=1010101; const ll qwq=303030; const ll inf=0x3f3f3f3f; int n,m; int qiao,tot,dian,da,shuang; int bian; int dfn[N],low[N],tim; bool cut[N]; int st[N],cnt; bool in[N]; vector <int> e[N],d[N]; void tarjan(int u,int zu) { dfn[u] = low[u] = ++tim; st[++cnt] = u; int son = 0; FOR() { int v = e[u][i]; if(!dfn[v]) { son++; tarjan(v,zu); low[u] = min(low[u],low[v]); if(low[v]==dfn[u]) { ++tot; while(1) { int now = st[cnt--]; d[tot].push_back(now); d[now].push_back(tot); if(now==v) break; } d[tot].push_back(u); d[u].push_back(tot); } } else low[u] = min(low[u],dfn[v]); if(u==zu && son>=2) cut[u] = 1; else if(low[v]>=dfn[u]) cut[u] = 1; } if(u==zu) cnt = 0; } int query(int fang) { int res = 0; for(int i=0;i<d[fang].size();i++) in[ d[fang][i] ] = 1; for(int i=0;i<d[fang].size();i++) { int u = d[fang][i]; for(int j=0;j<e[u].size();j++) { int v = e[u][j]; if(in[v]) res++; } } for(int i=0;i<d[fang].size();i++) in[ d[fang][i] ] = 0; return res/2; } int main() { int x,y; n = read(); m = read(); tot = n; for(int i=1;i<=m;i++) { x = read(); y = read(); e[x].push_back(y); e[y].push_back(x); } for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i,i); for(int i=1;i<=n;i++) if(cut[i]) dian++; for(int i=n+1;i<=tot;i++) { if(d[i].size()==2) bian++; if(d[i].size()>=2) shuang++; } for(int i=n+1;i<=tot;i++) da = max(da,query(i)); cout<<dian<<" "<<bian<<" "<<shuang<<" "<<da; return 0; } ``` === 并查集维护缩点 ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const int N=501010; const int inf=0x3f3f3f3f; int n,m; int fa[N],dep[N]; vector <int> e[N]; int find(int x) { return fa[x]==x ? x : fa[x]=find(fa[x]); } void merge(int x,int y) { if(x==y) return ; if(dep[x]<dep[y]) swap(x,y); fa[x] = y; } void tarjan(int u) { for(int v : e[u]) { if(!dep[v]) { dep[v] = dep[u] + 1; tarjan(v); } int vv = find(v), uu = find(u); if(dep[vv] > 0) merge(uu,vv); } dep[u] = -1; } int main() { int x,y; n = read(); m = read(); for(int i=1;i<=n;i++) fa[i] = i; for(int i=1;i<=m;i++) { x = read(); y = read(); e[x].push_back(y); } for(int i=1;i<=n;i++) { if(!dep[i]) tarjan(i); } for(int i=1;i<=n;i++) cout<<"belong["<<i<<"] = "<<find(i)<<"\n"; return 0; } ``` === 二分图最小点覆盖(dinic) ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const int N=101010; const int qwq=303030; const int inf=0x3f3f3f3f; int n1,n2,m,s,t; int ans; struct E{ int to,nxt,cap; }e[qwq]; int cnt = 1; int head[N],cur[N]; int dep[N],vis[N]; queue <int> q; int tag[N],belong[N]; inline void add(int u,int v,int w) { // cout<<u<<" -> "<<v<<" "<<w<<endl; e[++cnt] = (E){ v,head[u],w }; head[u] = cnt; e[++cnt] = (E){ u,head[v],0 }; head[v] = cnt; } inline bool SPFA() { for(int i=s;i<=t;i++) dep[i] = inf, vis[i] = 0, cur[i] = head[i]; q.push(s); dep[s] = 0; while(!q.empty()) { int u = q.front(); q.pop(); vis[u] = 0; for(int i=head[u]; i; i=e[i].nxt) { int v = e[i].to; if(dep[v] > dep[u] + 1 && e[i].cap) { dep[v] = dep[u] + 1; if(vis[v]) continue; q.push(v); vis[v] = 1; } } } return dep[t]!=inf; } int DFS(int u,int flow) { int res = 0, f; if(u==t || !flow) return flow; for(int i=cur[u]; i; i=e[i].nxt) { cur[u] = i; int v = e[i].to; if(e[i].cap && (dep[v] == dep[u]+1)) { f = DFS(v,min(flow-res,e[i].cap)); if(f) { res += f; e[i].cap -= f; e[i^1].cap += f; if(res==flow) break; } } } return res; } void mark(int u) { if(tag[u]) return ; tag[u] = 1; for(int i=head[u]; i; i=e[i].nxt) { int v = e[i].to; if(v==s) continue; if(!tag[v] && belong[v]) { tag[v] = 1; mark(belong[v]); } } } int main() { int x,y; n1 = read(); n2 = read(); m = read(); s = 0; t = n1+n2+1; for(int i=1;i<=n1;i++) add(s,i,1); for(int i=1;i<=n2;i++) add(i+n1,t,1); while(m--) { x = read(); y = read(); add(x,y+n1,1); } while(SPFA()) ans += DFS(s,inf); for(int u=n1+1;u<t;u++) { for(int i=head[u]; i; i=e[i].nxt) { int v = e[i].to; if(e[i].cap && v!=t) vis[v] = 1, belong[u] = v; } } for(int i=1;i<=n1;i++) if(!vis[i]) mark(i); for(int i=1;i<=n1;i++) if(!tag[i]) cout<<i<<" "; cout<<endl; for(int i=n1+1;i<t;i++) if(tag[i]) cout<<i<<" "; cout<<endl; return 0; } /* 4 4 7 1 1 2 2 1 3 2 3 2 4 3 2 4 2 */ ``` === 欧拉回路 ```cpp const int N=1010101; const int qwq=303030; const int inf=0x3f3f3f3f; int n,m; struct E{ int to,id; }; vector <E> e[N]; int vis[N],cur[N]; int st[N],cnt; void EULER(int u) { for(int i=cur[u];i<e[u].size();i=cur[u]) { cur[u]=i+1; int v = e[u][i].to, id = e[u][i].id; if(vis[id]) continue; vis[id] = 1; EULER(v); st[++cnt] = u; } } int main() { int x,y; n = read(); m = read(); for(int i=1;i<=m;i++) { x = read(); y = read(); e[x].push_back({y,i}); e[y].push_back({x,i}); } EULER(1); for(int i=cnt;i>=1;i--) cout<<st[i]<<" "; cout<<1<<"\n"; return 0; } /* 7 8 1 2 2 3 3 4 4 5 5 1 3 6 6 7 7 3 */``` === Seq ```cpp /* S starts at 0 go range from 1 to n n <- length of string S */ void build() { for (int i = 0; i < 26; i++) last[i] = -1; for (int i = n; i; i--) { for (int j = 0; j < 26; j++) go[i][j] = last[j]; last[S[i - 1] - 'a'] = i; } int now1 = last[T[0] - 'a']; for (int i = 1; i < m; i++) if (~now1) now1 = go[now1][T[i] - 'a']; else break; }``` === 匈牙利算法 ```cpp const int N=101010; const int qwq=303030; const int inf=0x3f3f3f3f; int n,m,k; int ans; int vis[N],belong[N]; // index is the right_part of G(V,E) int mp[1234][1234]; bool DFS(int u) { for(int i=1;i<=m;i++) { if(!mp[u][i] || vis[i]) continue; vis[i] = 1; if(!belong[i] || DFS(belong[i])) { belong[i] = u; return 1; } } return 0; } int main() { int x,y; scanf("%d%d%d",&n,&m,&k); while(k--) { scanf("%d%d",&x,&y); mp[x][y] = 1; } for(int i=1;i<=n;i++) { memset(vis,0,sizeof(vis)); if(DFS(i)) ans++; } cout<<ans; return 0; } ``` === 最大流 ```cpp const int N=101010; const int qwq=303030; const int inf=0x3f3f3f3f; int n,m,s,t; struct E{ int to,nxt,cap; }e[qwq]; int cnt = 1; int head[N],cur[N]; int dep[N],vis[N]; queue <int> q; inline void add(int u,int v,int w) { e[++cnt] = (E){ v,head[u],w }; head[u] = cnt; e[++cnt] = (E){ u,head[v],0 }; head[v] = cnt; } inline bool SPFA() { for(int i=s;i<=t;i++) dep[i] = inf, vis[i] = 0, cur[i] = head[i]; q.push(s); dep[s] = 0; while(!q.empty()) { int u = q.front(); q.pop(); vis[u] = 0; for(int i=head[u]; i; i=e[i].nxt) { int v = e[i].to; if(dep[v] > dep[u] + 1 && e[i].cap) { dep[v] = dep[u] + 1; if(vis[v]) continue; q.push(v); vis[v] = 1; } } } return dep[t]!=inf; } int DFS(int u,int flow) { int res = 0, f; if(u==t || !flow) return flow; for(int i=cur[u]; i; i=e[i].nxt) { cur[u] = i; int v = e[i].to; if(e[i].cap && (dep[v] == dep[u]+1)) { f = DFS(v,min(flow-res,e[i].cap)); if(f) { res += f; e[i].cap -= f; e[i^1].cap += f; if(res==flow) break; } } } return res; } int main() { int x,y,z; n = read(); m = read(); s = read(); t = read(); while(m--) { x = read(); y = read(); z = read(); add(x,y,z); } int max_flow = 0; while(SPFA()) max_flow += DFS(s,inf); cout<<max_flow; return 0; } ``` === 虚树 ```cpp const int N=501010; const int qwq=303030; const int inf=0x3f3f3f3f; int T; int n,a[N],da; vector <int> e[N]; vector <int> g[N]; int dfn[N],tot,dep[N]; int f[N][22],rec[N][22]; int ob[N]; int cnt,st[N]; vector <int> d[N]; inline bool cmp(int x,int y) { return dfn[x] < dfn[y]; } void DFS(int u,int fa) { dep[u] = dep[fa] + 1; f[++tot][0] = dep[u]; rec[tot][0] = u; dfn[u] = tot; FOR() { int v = e[u][i]; if(v==fa) continue; DFS(v,u); f[++tot][0] = dep[u]; rec[tot][0] = u; } } inline int LCA(int x,int y) { if(dfn[x]>dfn[y]) swap(x,y); int l = dfn[x], r = dfn[y], k = ob[r-l+1]; if(f[l][k] < f[r-(1<<k)+1][k]) return rec[l][k]; else return rec[r-(1<<k)+1][k]; } void built(int h) { cout<<"\nh = "<<h<<endl; cnt = 0; st[++cnt] = 1; for(int v : g[h]) st[++cnt] = v; sort(st+1, st+cnt+1, cmp); int now = cnt; for(int i=2;i<=now;i++) st[++cnt] = LCA(st[i-1],st[i]); sort(st+1, st+cnt+1, cmp); cnt = unique(st+1, st+cnt+1) - st - 1; for(int i=2;i<=cnt;i++) { d[ LCA(st[i-1],st[i]) ].push_back( st[i] ); cout<<LCA(st[i-1],st[i])<<" -> "<<st[i]<<endl; } // TREE(1); for(int i=1;i<=cnt;i++) d[st[i]].clear(); } int main() { int x,y; ob[0] = -1; for(int i=1;i<=N-10;i++) ob[i] = ob[i>>1] + 1; n = read(); da = read(); for(int i=1;i<=n;i++) a[i] = read(), g[a[i]].push_back(i); for(int i=1;i<n;i++) { x = read(); y = read(); e[x].push_back(y); e[y].push_back(x); } DFS(1,1); for(int k=1;k<=20;k++) { for(int i=1;i+(1<<k-1)<=tot;i++) { if(f[i][k-1] < f[i+(1<<k-1)][k-1]) f[i][k] = f[i][k-1], rec[i][k] = rec[i][k-1]; else f[i][k] = f[i+(1<<k-1)][k-1], rec[i][k] = rec[i+(1<<k-1)][k-1]; } } for(int i=1;i<=da;i++) { built(i); } return 0; } /* 11 4 1 4 2 1 3 4 1 1 4 2 1 1 2 1 3 2 4 4 5 4 6 3 7 7 8 7 9 1 10 2 11 */ ``` === 二分图最大权完美匹配(KM) ```cpp typedef long double db; const ll N=2010; const ll qwq=2030303; const ll inf=0x3f3f3f3f3f3f3f3f; ll n,m,ans; ll mpx[N],mpy[N],visx[N],visy[N],lx[N],ly[N]; ll li[N][N],slack[N],pre[N]; void BFS(ll u) { ll x,y=0,yy=0,d; memset(pre,0,sizeof(pre)); memset(slack,0x3f,sizeof(slack)); mpy[y] = u; while(1) { x = mpy[y]; d = inf; visy[y] = 1; for(int i=1;i<=n;i++) { if(visy[i]) continue; if(slack[i] > lx[x]+ly[i]-li[x][i]) { slack[i] = lx[x]+ly[i]-li[x][i]; pre[i] = y; } if(slack[i]<d) { d = slack[i]; yy = i; } } for(int i=0;i<=n;i++) { if(visy[i]) lx[mpy[i]] -= d, ly[i] += d; else slack[i] -= d; } y = yy; if(mpy[y]==-1) break; } while(y) { mpy[y] = mpy[pre[y]]; y = pre[y]; } } int main() { ll x,y,z; n = read(); m = read(); memset(li,-0x3f,sizeof(li)); memset(mpy,-1,sizeof(mpy)); for(ll i=1;i<=m;i++) { x = read(); y = read(); z = read(); li[x][y] = max(li[x][y], z); } for(ll i=1;i<=n;i++) { memset(visy,0,sizeof(visy)); BFS(i); } ll ans = 0; for(ll i=1;i<=n;i++) ans += li[mpy[i]][i]; cout<<ans<<"\n"; for(ll i=1;i<=n;i++) cout<<mpy[i]<<" "; return 0; }``` === 删边最短路 ```cpp #include <bits/stdc++.h> #define ll long long #define ls now<<1 #define rs now<<1|1 using namespace std; const ll N=202020; const ll inf=0x3f3f3f3f3f3f3f3f; ll n,m,Q; ll X[N],Y[N],Z[N]; struct E{ ll to,we,id; }; vector <E> e[N]; ll dis1[N],dis2[N],L[N],R[N],pre[N]; ll vis[N],in[N],da; struct D { ll id,di; }; inline bool operator < (D A,D B) { return A.di > B.di; } priority_queue <D> q; void DIJ(ll s,ll *dis,ll cl) { for(ll i=1;i<=n;i++) dis[i] = inf; dis[s] = 0; q.push({s,0}); while(!q.empty()) { D now = q.top(); q.pop(); ll u = now.id; if(dis[u]!=now.di) continue; for(E vv : e[u]) { ll v = vv.to; if(dis[v] > dis[u]+vv.we) { dis[v] = dis[u]+vv.we; pre[v] = vv.id; if(cl==1 && !vis[v]) L[v] = L[u]; if(cl==2 && !vis[v]) R[v] = R[u]; q.push({v,dis[v]}); } } } } void access() { ll u = 1; vis[u] = 1; L[u] = R[u] = 0; while(u!=n) { ll id = pre[u]; in[id] = ++da; u ^= X[id] ^ Y[id]; vis[u] = 1; L[u] = R[u] = da; } } ll t[N<<2]; void built(ll now,ll l,ll r) { t[now] = inf; if(l==r) return ; ll mid = l+r >> 1; built(ls, l, mid); built(rs, mid+1, r); } void insert(ll now,ll l,ll r,ll x,ll y,ll g) { if(x<=l && r<=y) { t[now] = min(t[now],g); return; } ll mid = l+r >> 1; if(x<=mid) insert(ls, l, mid, x, y, g); if(y>mid) insert(rs, mid+1, r, x, y, g); } ll query(ll now,ll l,ll r,ll x) { if(l==r) return t[now]; ll mid = l+r >> 1, res = t[now]; if(x<=mid) res = min(res, query(ls, l, mid, x)); else res = min(res, query(rs, mid+1, r, x)); return res; } int main() { n = read(); m = read(); Q = read(); for(ll i=1;i<=m;i++) { X[i] = read(); Y[i] = read(); Z[i] = read(); e[X[i]].push_back({Y[i],Z[i],i}); e[Y[i]].push_back({X[i],Z[i],i}); } DIJ(n, dis2, 0); access(); DIJ(1, dis1, 1); DIJ(n, dis2, 2); built(1, 1, da); for(ll i=1;i<=m;i++) { if(!in[i]) { ll u = X[i], v = Y[i]; if(L[u]<R[v]) insert(1, 1, da, L[u]+1, R[v], dis1[u]+dis2[v]+Z[i]); if(L[v]<R[u]) insert(1, 1, da, L[v]+1, R[u], dis1[v]+dis2[u]+Z[i]); } } ll id,x; while(Q--) { id = read(); x = read(); ll ans = dis1[n]; if(!in[id]) { if(x<Z[id]) { ans = min(ans, dis1[X[id]]+dis2[Y[id]]+x); ans = min(ans, dis1[Y[id]]+dis2[X[id]]+x); } } else { ans = ans-Z[id]+x; if(x>Z[id]) { ans = min(ans, query(1, 1, da, in[id])); } } cout<<ans<<"\n"; } return 0; }``` === 树哈希 ```cpp // solution 1 ll base = 13333; bool cmp(ll A,ll B) { return ha[A] < ha[B]; } void TREE(ll u) { for(ll i=0;i<e[u].size();i++) TREE(e[u][i],cl); sort(e[u].begin(),e[u].end(),cmp); ha[u] = a[u]; ll now = 114514; for(ll v : e[u]) { (ha1[u] += now * ha1[u] %p) %= p; (now *= base) %= p; } } // solution 2 void dfs3(int u){ dp1[u]=827,dp2[u]=827; for(int i=0;i<g2[u].size();i++){ int v=g2[u][i]; dfs3(v); dp1[u]+=(ull)(siz[v]+dp1[v]-(siz[v]^dp1[v])+siz[u]); dp2[u]+=(ull)(siz[v]+dp2[v]+(siz[v]^dp2[v])+siz[u]); } dp1[u]*=829; dp2[u]*=829; }``` === 二分图最小点覆盖 ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const int N=1010; int n1,n2,m; vector <int> e[N]; int vis[N],belong[N]; // index is the right_part of G(V,E) bool tagx[N],tagy[N]; int DFS(int u) { for(int v : e[u]) { if(vis[v]) continue; vis[v] = 1; if(!belong[v] || DFS(belong[v])) { belong[v] = u; return 1; } } return 0; } void mark(int u) { if(tagx[u]) return ; tagx[u] = 1; for(int v : e[u]) { if(!tagy[v] && belong[v]) { tagy[v] = 1; mark(belong[v]); } } } int main() { int x,y; n1 = read(); n2 = read(); m = read(); while(m--) { x = read(); y = read(); e[x].push_back(y); } int ans = 0; for(int i=1;i<=n1;i++) { memset(vis, 0, sizeof(vis)); ans += DFS(i); } cout<<"ans = "<<ans<<endl; memset(vis, 0, sizeof(vis)); for(int i=1;i<=n2;i++) vis[ belong[i] ] = 1; for(int i=1;i<=n1;i++) if(!vis[i]) mark(i); for(int i=1;i<=n1;i++) if(!tagx[i]) cout<<i<<" "; cout<<endl; for(int i=1;i<=n2;i++) if(tagy[i]) cout<<i<<" "; cout<<endl; return 0; } /* 4 4 7 1 1 2 2 1 3 2 3 2 4 3 2 4 2 */ ``` === 带花树 ```cpp int n,m,ans; int fa[N],cl[N],mp[N],pre[N]; int cnt,tim[N]; vector <int> e[N]; queue <int> q; int find(int x) { return (fa[x]==x) ? x : fa[x]=find(fa[x]); } inline void link(int x,int y) { mp[x] = y; mp[y] = x; } void rev(int x) { if(x) { rev(mp[pre[x]]), link(x,pre[x]); } } inline int lca(int x,int y) { ++cnt; x = find(x); y = find(y); while(tim[x]!=cnt) { tim[x] = cnt; x = find(pre[ mp[x] ]); if(y) swap(x,y); } return x; } inline void blossom(int x,int y,int ff) { for(; find(x)!=ff; x=pre[y]) { pre[x] = y; y = mp[x]; fa[x] = fa[y] = ff; if(cl[y]==2) cl[y] = 1, q.push(y); } } int BFS(int s) { for(int i=1;i<=n;i++) pre[i] = cl[i] = 0, fa[i] = i; while(!q.empty()) q.pop(); cl[s] = 1; q.push(s); while(!q.empty()) { int u = q.front(); q.pop(); FOR() { int v = e[u][i]; if(cl[v]==1) { int ff = lca(u,v); blossom(u,v,ff); blossom(v,u,ff); } else if(!cl[v]) { pre[v] = u; cl[v] = 2; if(!mp[v]) { rev(v); return 1; } else { cl[ mp[v] ] = 1; q.push(mp[v]); } } } } return 0; } int main() { int x,y; n = read(); m = read(); for(int i=1;i<=n;i++) fa[i] = i; for(int i=1;i<=m;i++) { x = read(); y = read(); e[x].push_back(y); e[y].push_back(x); } for(int i=1;i<=n;i++) { if(!mp[i]) ans += BFS(i); } cout<<ans<<"\n"; return 0; } ``` === 有源汇上下界最大流 ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const ll N=101010; const ll inf=0x3f3f3f3f; ll n,m,s,t,ss,tt; struct EE{ ll u,v,l,r; } a[N]; ll cnta; ll du[N]; struct E{ ll to,nxt,cap; }e[N]; ll cnt = 1; ll head[N],cur[N]; ll dep[N],vis[N]; queue <ll> q; inline void add(ll u,ll v,ll w) { // cout<<u<<" -> "<<v<<" "<<w<<endl; e[++cnt] = (E){ v,head[u],w }; head[u] = cnt; e[++cnt] = (E){ u,head[v],0 }; head[v] = cnt; } inline bool SPFA(ll S,ll T) { for(ll i=0;i<=tt;i++) dep[i] = inf, vis[i] = 0, cur[i] = head[i]; q.push(S); dep[S] = 0; while(!q.empty()) { ll u = q.front(); q.pop(); vis[u] = 0; for(ll i=head[u]; i; i=e[i].nxt) { ll v = e[i].to; if(dep[v] > dep[u] + 1 && e[i].cap) { dep[v] = dep[u] + 1; if(vis[v]) continue; q.push(v); vis[v] = 1; } } } return dep[T]!=inf; } ll DFS(ll u,ll goal,ll flow) { ll res = 0, f; if(u==goal || !flow) return flow; for(ll i=cur[u]; i; i=e[i].nxt) { cur[u] = i; ll v = e[i].to; if(e[i].cap && (dep[v] == dep[u]+1)) { f = DFS(v,goal,min(flow-res,e[i].cap)); if(f) { res += f; e[i].cap -= f; e[i^1].cap += f; if(res==flow) break; } } } return res; } ll solve() { ll ans1 = 0, ans2 = 0, cha = 0; for(ll i=1;i<=cnta;i++) { ll u = a[i].u, v = a[i].v; du[u] += a[i].l; du[v] -= a[i].l; add(u, v, a[i].r-a[i].l); } ll lim = cnt; for(ll u=s;u<=t;u++) { if(du[u]>0) add(u,tt,du[u]), cha += du[u]; if(du[u]<0) add(ss,u,-du[u]); } add(t,s,inf); while(SPFA(ss,tt)) cha -= DFS(ss,tt,inf); if(cha) return -1; ans1 = e[cnt].cap; for(ll i=lim+1;i<=cnt;i++) e[i].cap = 0; while(SPFA(s,t)) ans2 += DFS(s,t,inf); return ans1+ans2; } void chushihua() { cnt = 1; cnta = 0; for(ll i=0;i<=tt;i++) head[i] = du[i] = 0; } int main() { ll x,y,l,r; while(scanf("%lld%lld",&n,&m)!=EOF) { chushihua(); s = 0; t = n+m+1; ss = n+m+2; tt = n+m+3; for(int i=1;i<=m;i++) { x = read(); y = read(); l = read(); r = read(); a[++cnta] = {x,y,l,r}; } cout<<solve()<<"\n\n"; } return 0; }``` === tarjan求桥和割点 ```cpp #include <bits/stdc++.h> #include <vector> using namespace std; const int N=101010; const int qwq = 303030; int n,m; int X[N],Y[N],Z[N]; int head[N],to[qwq],cnt=1,we[qwq],nxt[qwq]; int dfn[N],low[N],tim; bool cut[N],br[qwq]; void add(int u,int v,int z) { to[++cnt] = v; we[cnt] = z; nxt[cnt] = head[u]; head[u] = cnt; to[++cnt] = u; we[cnt] = z; nxt[cnt] = head[v]; head[v] = cnt; } void tarjan(int u,int fa) { dfn[u] = low[u] = ++tim; int son = 0; for(int i=head[u]; i; i=nxt[i]) { int v = to[i]; if(v==fa) continue; if(!dfn[v]) { if(!fa) son++; tarjan(v,u); low[u] = min(low[u],low[v]); if(fa && low[v]>=dfn[u]) cut[u] = 1; if(low[v]>dfn[u]) br[i] = 1, br[i^1] = 1; } else low[u] = min(low[u],dfn[v]); } if(son>=2) cut[u] = 1; } int main() { n = read(); m = read(); for(int i=1;i<=m;i++) { X[i] = read(); Y[i] = read(); Z[i] = read(); add(X[i],Y[i],Z[i]); } for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i,0); for(int i=1;i<=n;i++) { cout<<"cut["<<i<<"] = "<<cut[i]<<endl; } for(int i=2;i<=cnt;i++) { cout<<"to = "<<to[i]<<" br = "<<br[i]<<"\n"; } return 0; }``` === K短路 ```cpp const ll N=101010; const ll qwq=503030; const ll inf=0x3f3f3f3f3f3f3f3f; ll n,m,k; ll dis[N],fa[N],head1[N],head2[N]; bool vis[N]; struct E{ ll to,we,nxt,on; } e[qwq],g[qwq]; ll cnt; struct D{ ll id,di; }; bool operator < (D A,D B) { return A.di > B.di; } priority_queue <D> q; ll tot=0, rt[N<<4], ls[N<<4], rs[N<<4], dep[N<<4]; D tree[N<<4]; void add(ll u,ll v,ll z) { cnt++; e[cnt] = (E){v,z,head1[u],0}; head1[u] = cnt; g[cnt] = (E){u,z,head2[v],0}; head2[v] = cnt; } void DIJ() { memset(dis,0x3f,sizeof(dis)); q.push({n,0}); dis[n] = 0; while(!q.empty()) { D now = q.top(); q.pop(); ll u = now.id; if(dis[u]!=now.di) continue; for(ll i=head2[u]; i; i=g[i].nxt) { ll v = g[i].to, w = g[i].we; if(dis[u] + w < dis[v]) { dis[v] = dis[u] + w; q.push({v,dis[v]}); } } } } ll addnew(ll u,ll di) { tree[++tot] = {u,di}; return tot; } ll merge(ll x,ll y) { if(!x || !y) return x | y; if(tree[x] < tree[y]) swap(x,y); ll now = ++tot; tree[now] = tree[x]; ls[now] = ls[x]; rs[now] = merge(rs[x],y); if(dep[ls[now]] < dep[rs[now]]) swap(ls[now],rs[now]); dep[now] = dep[rs[now]] + 1; return now; } void DFS(ll u) { // cout<<"u = "<<u<<"\n"; vis[u] = 1; for(ll i=head2[u]; i; i=g[i].nxt) { ll v = g[i].to; if(vis[v]) continue; if(dis[v] == dis[u]+g[i].we) { fa[v] = u; e[i].on = 1; DFS(v); } } } void DFS2(ll u) { // cout<<" u = "<<u<<"\n"; vis[u] = 1; if(fa[u]) rt[u] = merge(rt[u], rt[ fa[u] ]); for(ll i=head2[u]; i; i=g[i].nxt) { ll v = g[i].to; if(fa[v]==u && !vis[v]) DFS2(v); } } void built() { for(ll u=1;u<=n;u++) { if(dis[u]==inf) continue; for(ll i=head1[u]; i; i=e[i].nxt) { ll v = e[i].to; if(e[i].on || dis[v]==inf) continue; rt[u] = merge(rt[u],addnew(v,dis[v]-dis[u]+e[i].we)); } } } int main() { ll x,y,z; n = read(); m = read(); k = read(); for(ll i=1;i<=m;i++) { x = read(); y = read(); z = read(); add(x,y,z); } DIJ(); DFS(n); if(k==1) { cout<<dis[1]; return 0; } memset(vis,0,sizeof(vis)); built(); DFS2(n); q.push( {rt[1], tree[rt[1]].di} ); while(!q.empty()) { D now = q.top(); q.pop(); ll u = now.id, w = now.di; k--; if(k==1) { cout<<dis[1]+w; return 0; } if(ls[u]) q.push( {ls[u], w-tree[u].di+tree[ls[u]].di} ); if(rs[u]) q.push( {rs[u], w-tree[u].di+tree[rs[u]].di} ); ll v = rt[ tree[u].id ]; if(v) q.push( {v, w+tree[v].di} ); } return 0; }``` === 2-sat ```cpp #include <bits/stdc++.h> #define FOR() int le=e[u].size();for(int i=0;i<le;i++) #define QWQ cout<<"QwQ"<<endl; #define ll long long #include <vector> #include <map> using namespace std; const int N=2010101; const int qwq=303030; const int inf=0x3f3f3f3f; int n,m; int belong[N],tot=0,low[N],dfn[N],tim=0; int in[N],cnt,st[N]; vector <int> e[N]; void tarjan(int u) { dfn[u] = low[u] = ++tim; st[++cnt] = u; in[u] = 1; FOR() { int v = e[u][i]; if(!dfn[v]) { tarjan(v); low[u] = min(low[u],low[v]); } else if(in[v]) low[u] = min(low[u],dfn[v]); } if(low[u]==dfn[u]) { tot++; while(1) { int v = st[cnt--]; in[v] = 0; belong[v] = tot; if(v==u) break; } } } int main() { int x,lx,y,ly; n = read(); m = read(); while(m--) { x = read(); lx = read(); y = read(); ly = read(); if(!lx) x += n; // x is false if(!ly) y += n; if(x>n) e[x-n].push_back(y); // if !x : y else e[x+n].push_back(y); if(y>n) e[y-n].push_back(x); else e[y+n].push_back(x); } for(int i=1;i<=2*n;i++) if(!dfn[i]) tarjan(i); for(int i=1;i<=n;i++) if(belong[i]==belong[i+n]) { printf("IMPOSSIBLE"); return 0; } printf("POSSIBLE\n"); for(int i=1;i<=n;i++) { if(belong[i] > belong[i+n]) cout<<"0 "; // (i) -> (i+n) so i is false else cout<<"1 "; } return 0; }``` === 矩阵树定理 ```cpp const int p=998244353; int n,m; int du[345]; int a[345][345]; int ksm(int aa,int bb) { int sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } int det() { int res = 1, cl = 1; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) a[i][j] = (a[i][j] + p) %p; for(int i=1;i<=n;i++) { if(!a[i][i]) for(int j=i+1;j<=n;j++) if(a[j][i]) { cl ^= 1; for(int k=i;k<=n;k++) swap(a[j][k],a[i][k]); break; } if(!a[i][i]) return 0; (res *= a[i][i]) %= p; int ni = ksm(a[i][i],p-2); for(int j=i;j<=n;j++) (a[i][j] *= ni) %= p; for(int j=1;j<=n;j++) { if(i!=j) { int bei = a[j][i]; for(int k=i;k<=n;k++) a[j][k] = (a[j][k] - a[i][k] * bei %p +p) %p; } } } return cl ? res : -res; } int main() { int x,y; n = read(); m = read(); for(int i=1;i<=m;i++) { x = read(); y = read(); du[x]++; du[y]++; a[x][y]--; a[y][x]--; } for(int i=1;i<=n;i++) a[i][i] = du[i]; // for(int i=1;i<=n;i++) { // for(int j=1;j<=n;j++) cout<<a[i][j]<<" "; // cout<<endl; // } // 无向图: L(n) = D(n) - A(n); // 有向图根向:L(n) = D_out(n) - A(n); //k为根去掉第k行 // 有向图叶向:L(n) = D_in(n) - A(n); n--; //去一行 cout<<det(); return 0; }``` === 边分治缩点 ```cpp #define ls now<<1 #define rs now<<1|1 using namespace std; const ll N=501010; const ll qwq=303030; const ll inf=0x3f3f3f3f; ll T; ll n,m; int ans[N], _ans; int fa[N]; struct E{ int x,y,ti; }; vector <E> d[N<<2]; vector <int> e[N]; int tim,dfn[N],low[N],belong[N]; int in[N],st[N],cnt; int find(int x) { return fa[x]==x ? x : fa[x]=find(fa[x]); } inline void merge(int x,int y) { x = find(x); y = find(y); if(x==y) return ; fa[x] = y; _ans--; } void tarjan(int u) { dfn[u] = low[u] = ++tim; st[++cnt] = u; in[u] = 1; for(int v : e[u]) { if(!dfn[v]) { tarjan(v); low[u] = min(low[u],low[v]); } else if(in[v]) low[u] = min(low[u],dfn[v]); } if(low[u]==dfn[u]) { while(1) { int v = st[cnt--]; in[v] = 0; belong[v] = u; if(v==u) break; } } } void solve(ll now,ll l,ll r) { // cout<<"solve("<<l<<","<<r<<") : "; // for(E vv : d[now]) cout<<vv.x<<"->"<<vv.y<<" "; // cout<<endl; if(l==r) { for(E vv : d[now]) merge(vv.x, vv.y); vector<E>().swap(d[now]); ans[l] = _ans; return ; } ll mid = l+r >> 1; for(E &vv : d[now]) { e[vv.x = find(vv.x)].clear(); e[vv.y = find(vv.y)].clear(); dfn[vv.x] = dfn[vv.y] = 0; } for(E vv : d[now]) if(vv.ti<=mid) e[vv.x].push_back(vv.y); for(E vv : d[now]) { if(vv.ti<=mid) { if(!dfn[vv.x]) tarjan(vv.x); if(!dfn[vv.y]) tarjan(vv.y); if(belong[vv.x]==belong[vv.y]) d[ls].push_back(vv); else d[rs].push_back(vv); } else { d[rs].push_back(vv); } } vector<E>().swap(d[now]); solve(ls, l, mid); solve(rs, mid+1, r); } void chushihua() { _ans = 0; tim = 0; } int main() { int x,y; T = read(); while(T--) { chushihua(); n = read(); m = read(); _ans = n; for(int i=1;i<=n;i++) fa[i] = i; for(int i=1;i<=m;i++) { x = read(); y = read(); d[1].push_back({x,y,i}); } solve(1, 1, m+1); for(int i=1;i<=m;i++) cout<<ans[i]<<"\n"; } return 0; } ``` === 费用流 ```cpp const int N=101010; const int qwq=303030; const int inf=0x3f3f3f3f; int n,m,s,t,cnt=1,maxflow,mincost; struct E{ int to,nxt,cap,we; } e[N]; int head[N],dep[N],vis[N],cur[N]; queue <int> q; inline void add(int u,int v,int w,int z) { e[++cnt] = (E){ v,head[u],w,z }; head[u] = cnt; e[++cnt] = (E){ u,head[v],0,-z }; head[v] = cnt; } bool SPFA() { for(int i=0;i<=t;i++) cur[i] = head[i], vis[i] = 0, dep[i] = inf; dep[s] = 0; q.push(s); while(!q.empty()) { int u = q.front(); q.pop(); vis[u] = 0; for(int i=head[u]; i; i=e[i].nxt) { int v = e[i].to, w = e[i].we; if(e[i].cap && dep[v] > dep[u]+w) { dep[v] = dep[u]+w; if(vis[v]) continue; q.push(v); vis[v] = 1; } } } return dep[t] != inf; } int DFS(int u,int flow) { int res = 0, f; if(u==t || !flow) return flow; vis[u] = 1; for(int i=cur[u]; i; i=e[i].nxt) { cur[u] = i; int v = e[i].to, w = e[i].we; if(vis[v]) continue; if(e[i].cap && dep[v]==dep[u]+w) { f = DFS( v, min(e[i].cap,flow-res) ); if(f) { res += f; e[i].cap -= f; e[i^1].cap += f; mincost += f * w; if(res==flow) break; } } } return res; } int main() { int x,y,z,w; n = read(); m = read(); s = read(); t = read(); while(m--) { x = read(); y = read(); z = read(); w = read(); add(x,y,z,w); } while( SPFA() ) maxflow += DFS(s,inf); cout<<maxflow<<" "<<mincost; return 0; }``` == 字符串 === runs (hash) ```cpp #include <bits/stdc++.h> #define ll long long #define QWQ cout<<"QwQ\n"; using namespace std; const ll N=1010101; const ll inf=0x3f3f3f3f; const ll p=998244353; ll n; char s[N]; ll a[N]; ll ha[N],fi[N],base = 2333; ll ask(ll l,ll r) { return (ha[r] - ha[l-1] * fi[r-l+1] %p + p) %p; } inline ll lcp(ll x,ll y) { ll l=1, r=n-max(x,y)+1, res = 0; while(l<=r) { ll mid = (l+r) >> 1; if(ask(x,x+mid-1) == ask(y,y+mid-1)) l = mid+1, res = mid; else r = mid-1; } return res; } inline ll lcs(ll x,ll y) { ll l=1, r=min(x,y), res=0; while(l<=r) { ll mid = (l+r) >> 1; if(ask(x-mid+1,x) == ask(y-mid+1,y)) l = mid+1, res = mid; else r = mid-1; } return res; } bool cmp(ll l1,ll r1,ll l2,ll r2) { ll l = lcp(l1,l2); if(l>min(r1-l1,r2-l2)) return r1-l1<r2-l2; return a[l1+l]<a[l2+l]; } struct runs{ ll i,j,p; runs(ll i=0,ll j=0,ll p=0) : i(i), j(j), p(p) {} bool operator == (const runs A) const { return i==A.i && j==A.j && p==A.p; } bool operator < (const runs A) const { return i==A.i ? j<A.j : i<A.i; } }; vector <runs> ans; ll st[N],run[N]; void lyndon() { ll r = 0; for(ll i=n;i;i--) { st[++r] = i; for(;r>1 && cmp(i,st[r],st[r]+1,st[r-1]);r--); run[i] = st[r]; } } void get_runs() { for(int i=1;i<=n;i++) { int l1=i, r1=run[i], l2=l1-lcs(l1-1,r1), r2=r1+lcp(l1,r1+1); if(r2-l2+1>=(r1-l1+1)*2) ans.push_back(runs(l2,r2,r1-l1+1)); } } int main() { fi[0] = 1; for(ll i=1;i<=N-10;i++) fi[i] = fi[i-1] * base %p; scanf("%s",s+1); n = strlen(s+1); for(ll i=1;i<=n;i++) a[i] = s[i]-'a'+1, ha[i] = (ha[i-1] * base %p + a[i]) %p; // int x,y; // ask the lcp() and lcs(); // while(1) { // cin>>x>>y; // cout<<lcp(x,y)<<" "<<lcs(x,y)<<"\n"; // } lyndon(); // for(int i=1;i<=n;i++) cout<<run[i]<<" "; get_runs(); for(ll i=1;i<=n;i++) a[i] = 27-a[i]; lyndon(); get_runs(); sort(ans.begin(), ans.end()); ans.erase(unique(ans.begin(), ans.end()), ans.end()); cout<<ans.size()<<"\n"; for(runs vv : ans) cout<<vv.i<<" "<<vv.j<<" "<<vv.p<<endl; return 0; }``` === PAM ```cpp struct PAM { int a[N]; int cnt=1, lst=0; int ch[N][26],fail[N],len[N],dep[N]; int getfail(int i,int x) { while(a[i-len[x]-1] != a[i]) x = fail[x]; return x; } void built() { len[1] = -1; fail[0] = 1; a[0] = -2333; for(int i=1;i<=n;i++) { int u = getfail(i,lst), c = a[i]; if(!ch[u][c]) { int w = getfail(i,fail[u]); len[++cnt] = len[u] + 2; fail[cnt] = ch[w][c]; dep[cnt] = dep[ fail[cnt] ] + 1; ch[u][c] = cnt; } lst = ch[u][c]; } } } P;``` === manacher ```cpp int n,m; char z[N],s[N<<1]; int p[N<<1]; int R,id; int ans; void SAKI() { for(int i=1;i<=n;i++) { if(i<=R) p[i] = min(p[id*2-i],R-i+1); else p[i] = 1; while(s[i+p[i]]==s[i-p[i]]) p[i]++; if(i+p[i]-1 > R) R = i+p[i]-1, id = i; } } int main() { scanf("%s",z+1); m = strlen(z+1); for(int i=1;i<=m;i++) s[(i<<1)-1] = '#', s[i<<1] = z[i]; n = m*2 + 1; s[n] = '#'; s[n+1] = '@'; SAKI(); cout<<s+1<<"\n"; for(int i=1;i<=n;i++) cout<<p[i]<<" "; return 0; }``` === Z函数 ```cpp #include <bits/stdc++.h> using namespace std; const int N=401010; const int qwq=20003030; const int inf=0x3f3f3f3f; int n; char s[N]; int nxt[N]; void qiu() { nxt[0] = n; for(int i=1,j=0;i<=n;i++) { if(j+nxt[j]>i) nxt[i] = min(nxt[i-j], j+nxt[j]-i); while(i+nxt[i]<n && s[nxt[i]]==s[i+nxt[i]]) nxt[i]++; if(i+nxt[i]>j+nxt[j]) j = i; } for(int i=0;i<n;i++) cout<<nxt[i]<<" "; } int main() { scanf("%s",s); n = strlen(s); qiu(); return 0; } /* abaaaba 7 0 1 1 3 0 1 */ ``` === 广义SAM(离线) ```cpp int n,num,cnt=1; ll ans; char s[N]; int to[qwq][26],ch[qwq][26]; int fa[qwq],len[qwq]; struct E{ int id; int lst; int c; }; inline void outing() { for(int u=1;u<=cnt;u++) { cout<<u<<" : fa="<<fa[u]<<" len="<<len[u]-len[fa[u]]<<"\n "; for(int i=0;i<26;i++) { if(ch[u][i]) cout<<(char)('a'+i)<<"="<<ch[u][i]<<" "; } cout<<"\n"; } } inline int insert(int u,int c) { int cur = ++cnt; len[cur] = len[u] + 1; for(; !ch[u][c] && u; u=fa[u]) ch[u][c] = cur; if(!u) fa[cur] = 1; else { int v = ch[u][c]; if(len[v]==len[u]+1) fa[cur] = v; else { int w = ++cnt; len[w] = len[u] + 1; memcpy(ch[w], ch[v], sizeof ch[w]); fa[w] = fa[v]; fa[v] = fa[cur] = w; for(; ch[u][c]==v && u; u=fa[u]) ch[u][c] = w; } } return cur; } int main() { scanf("%d",&n); for(int u=0,k=1;k<=n;k++) { scanf("%s",s); int len = strlen(s); u = 0; for(int i=0;i<len;i++) { int c = s[i]-'a'; if(!to[u][c]) to[u][c] = ++num; u = to[u][c]; } } queue <E> q; for(int i=0;i<26;i++) if(to[0][i]) q.push({to[0][i],1,i}); while(!q.empty()) { E now = q.front(); q.pop(); int u = now.id; int tmp = insert(now.lst,now.c); for(int i=0;i<26;i++) if(to[u][i]) q.push({to[u][i],tmp,i}); } outing(); for(int i=2;i<=cnt;i++) ans += len[i] - len[fa[i]]; cout<<ans<<endl; cout<<cnt; return 0; } /* 4 aa ab bac caa */ ``` === kmp ```cpp #include <bits/stdc++.h> using namespace std; const int N=2001010; const int qwq=1003030; const int inf=0x3f3f3f3f; int n; char s[N]; int nxt[N]; void kmp() { for(int i=2,j=0;i<=n;i++) { while(j && s[i]!=s[j+1]) { // if(j+1<i && nxt[j+1]*2>(j+1) ) // log // j=(j-1)%(j-nxt[j])+1; // else j = nxt[j]; } if(s[i]==s[j+1]) j++; nxt[i] = j; // zu[i] = nxt[i]; // if(nxt[i] && (i-nxt[i])==(nxt[i]-nxt[nxt[i]])) zu[i] = zu[nxt[i]]; } } int main() { scanf("%s",s+1); n = strlen(s+1); kmp(); for(int i=1;i<=n;i++) cout<<nxt[i]<<" "; return 0; } /* abaaabab 0 0 1 1 1 2 3 2 */``` === SA ```cpp // by Flandre_495 ---2023.06.26 const int N=1001010; const int qwq=303030; const int inf=0x3f3f3f3f; int n,m; char s[N]; int sa[N],rk[N],tp[N],c[N],h[N]; inline void jipai() { for(int i=1;i<=n;i++) c[ rk[i] ]++; for(int i=1;i<=m;i++) c[i] += c[i-1]; for(int i=n;i>=1;i--) sa[ c[rk[tp[i]]]-- ] = tp[i]; for(int i=1;i<=m;i++) c[i] = 0; } void SA() { m = 75; for(int i=1;i<=n;i++) rk[i] = s[i] - '0' + 1, tp[i] = i; jipai(); for(int k=1; ;k<<=1) { int p = 0; for(int i=1;i<=k;i++) tp[++p] = n-k+i; for(int i=1;i<=n;i++) if(sa[i]>k) tp[++p] = sa[i]-k; jipai(); swap(tp,rk); //多测改为for rk[sa[1]] = p = 1; for(int i=2;i<=n;i++) if(tp[sa[i-1]]==tp[sa[i]] && tp[sa[i-1]+k]==tp[sa[i]+k]) rk[ sa[i] ] = p; else rk[ sa[i] ] = ++p; m = p; if(p==n) break; } int o; for(int i=1,l=0; i<=n; h[rk[i++]]=l) for(l=(l?l-1:0),o=sa[rk[i]-1]; s[i+l]==s[o+l]; ++l) ; } int main() { scanf("%s",s+1); n = strlen(s+1); SA(); for(int i=1;i<=n;i++) cout<<rk[i]<<" "; return 0; } ``` === SAM ```cpp // by Flandre_495 --2023.06.29 const int N=1001010; const int qwq=2003030; const int inf=0x3f3f3f3f; int n,cnt=1,lst=1; char s[N]; int fa[qwq],ch[qwq][26],len[qwq],siz[qwq]; vector <int> e[qwq]; inline int insert(int c) { int u = lst, cur = ++cnt; len[cur] = len[u] + 1; for(; !ch[u][c] && u; u=fa[u]) ch[u][c] = cur; if(!u) fa[cur] = 1; else { int v = ch[u][c]; if(len[v]==len[u]+1) fa[cur] = v; else { int w = ++cnt; len[w] = len[u] + 1; memcpy(ch[w],ch[v],sizeof ch[w]); fa[w] = fa[v]; fa[v] = fa[cur] = w; for(; ch[u][c]==v && u; u=fa[u]) ch[u][c] = w; } } return cur; } void DFS(int u) { FOR() { int v = e[u][i]; DFS(v); siz[u] += siz[v]; } } int main() { scanf("%s",s+1); n = strlen(s+1); for(int i=1;i<=n;i++) lst = insert(s[i]-'a'), siz[lst]=1; for(int i=2;i<=cnt;i++) e[ fa[i] ].push_back(i); DFS(1); ll ans = 0; for(int i=2;i<=cnt;i++) if(siz[i]>1) ans = max( ans, (ll)siz[i]*len[i] ); cout<<ans; return 0; } /* aababaaba */ ``` === 广义SAM(在线) ```cpp const int N=2010101; const int qwq=303030; const int inf=0x3f3f3f3f; int nn,n,m,lst=1,cnt=1; int cl[N]; char s[N],z[N]; int fa[N],ch[N][26],len[N]; ll ans[N]; vector <int> g[N]; inline void outing() { for(int u=1;u<=cnt;u++) { cout<<u<<" : fa="<<fa[u]<<" len=" <<len[u]-len[fa[u]]<<" siz = "<<g[u].size()<<"\n "; for(int i=0;i<26;i++) { if(ch[u][i]) cout<<(char)('a'+i)<<"="<<ch[u][i]<<" "; } cout<<"\n"; } } inline int insert(int c) { int u = lst; if(ch[u][c]) { int v = ch[u][c]; if(len[v]==len[u]+1) return v; int w = ++cnt; len[w] = len[u] + 1; memcpy(ch[w],ch[v],sizeof ch[v]); fa[w] = fa[v]; fa[v] = w; for(; ch[u][c]==v && u; u=fa[u]) ch[u][c] = w; return w; } int cur = ++cnt; len[cur] = len[u] + 1; for(; !ch[u][c] && u; u=fa[u]) ch[u][c] = cur; if(!u) fa[cur] = 1; else { int v = ch[u][c]; if(len[v]==len[u]+1) fa[cur] = v; else { int w = ++cnt; len[w] = len[u] + 1; memcpy(ch[w],ch[v],sizeof ch[v]); fa[w] = fa[v]; fa[v] = fa[cur] = w; for(; ch[u][c]==v && u; u=fa[u]) ch[u][c] = w; } } return cur; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%s",s); int le = strlen(s); lst = 1; for(int j=0;j<le;j++) lst = insert(s[j]-'a'); } outing(); for(int i=2;i<=cnt;i++) ans += len[i] - len[fa[i]]; cout<<ans<<endl<<cnt; return 0; }``` === AC自动机 ```cpp const int N=101010; const int qwq=1003030; const int inf=0x3f3f3f3f; int n,m; int cnt; char s[qwq]; struct T{ int to[26]; int fail; }f[qwq]; vector <int> e[qwq]; vector <int> g[qwq]; bool vis[qwq]; int ans; void chushihua() { for(int i=0;i<=cnt;i++) e[i].clear(), g[i].clear(); //记得从零开始 cnt = 0; memset( f,0,sizeof(f) ); } inline void AC() { queue <int> q; q.push(0); while(!q.empty()) { int u = q.front(); q.pop(); for(int i=0;i<26;i++) { int v = f[u].to[i]; if(v) { if(u) f[v].fail = f[ f[u].fail ].to[i]; q.push(v); } else f[u].to[i] = f[ f[u].fail ].to[i]; } } for(int i=1;i<=cnt;i++) e[ f[i].fail ].push_back(i); return ; } int main() { n = read(); for(int k=1;k<=n;k++) { scanf("%s",s); int len = strlen(s); int u = 0; for(int i=0;i<len;i++) { int v = s[i]-'a'; if(!f[u].to[v]) f[u].to[v] = ++cnt; u = f[u].to[v]; } g[u].push_back(k); } AC(); for(int i=1;i<=cnt;i++) cout<<"i = "<<i<<" fail = " <<f[i].fail<<" a = "<<f[i].to[0]<<" b = "<<f[i].to[1]<<"\n"; return 0; } ``` === Lyndon分解 ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const int N=5050505; char s[N]; int n; int ans; int main() { scanf("%s",s+1); n = strlen(s+1); for(int i=1;i<=n;) { int j=i, k=i+1; while(k<=n && s[j]<=s[k]) { if(s[j]<s[k]) j = i; else j++; k++; } while(i<=j) { ans ^= i+k-j-1; i += k-j; } } cout<<ans; return 0; } /* bbababaabaaabaaaab */ ``` === SA+ST ```cpp const ll N=2010101; const ll qwq=N*3; const ll inf=0x3f3f3f3f3f3f3f3f; int n,Q; int ob[N]; struct SAST{ int m; char s[N]; int sa[N],rk[N],tp[N],c[N],h[N]; int f[N][22]; void Qsort() { memset(c,0,sizeof(c)); for(int i=1;i<=n;i++) c[rk[i]]++; for(int i=1;i<=m;i++) c[i] += c[i-1]; for(int i=n;i>=1;i--) sa[ c[rk[tp[i]]]-- ] = tp[i]; } void SA() { m = 75; for(int i=1;i<=n;i++) rk[i] = s[i] - 'a' + 1, tp[i] = i; Qsort(); for(int k = 1; ;k <<= 1) { int p = 0; for(int i=1;i<=k;i++) tp[++p] = n - k + i; for(int i=1;i<=n;i++) if(sa[i] > k) tp[++p] = sa[i] - k; Qsort(); swap(tp,rk); rk[sa[1]] = p = 1; for(int i=2;i<=n;i++) { if(tp[sa[i-1]]==tp[sa[i]] && tp[sa[i-1]+k]==tp[sa[i]+k]) rk[sa[i]] = p; else rk[sa[i]] = ++p; } m = p; if(p==n) break; } int b; for(int i=1,l=0;i<=n;h[rk[i++]]=l) for(l=(l?l-1:0),b=sa[rk[i]-1];s[i+l]==s[b+l];++l); for(int i=1;i<=n;i++) f[i][0] = h[i]; for(int k=1;k<=18;k++) for(int i=1;i+(1<<k)-1<=n;i++) f[i][k] = min(f[i][k-1],f[ i+(1<<(k-1)) ][k-1]); } inline int LCP(int i,int j) { if(i<1 || j<1 || i>n || j>n) return 0; if(i==j) return n-i+1; i = rk[i]; j = rk[j]; if(i>j) swap(i,j); i++; int k = ob[j-i+1]; return min(f[i][k],f[j-(1<<k)+1][k]); } }zheng,dao; int main() { for(int i=2;i<=N-1000;i++) ob[i] = ob[i>>1] + 1; n = read(); Q = read(); scanf("%s",zheng.s+1); zheng.SA(); int x,y; while(Q--) { x = read(); y = read(); cout<<zheng.LCP(x,y)<<"\n"; } return 0; } /* */ ``` == 多项式 === NTT ```cpp const ll N=3001010; const ll qwq=303030; const ll inf=0x3f3f3f3f; const ll p=998244353, g=3, gi=332748118; ll n,m; ll r[N]; ll F[N],G[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } void NTT(ll *A,ll len,ll cl) { for(ll i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,gk=gk*g1%p) { ll x = A[i+j], y = gk*A[i+j+k] %p; A[i+j] = (x+y) %p; A[i+j+k] = (x-y+p) %p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(int i=0;i<len;i++) A[i] = A[i] * inv %p; } inline int init(int wo) { ll len = 1, L = 0; while(len<wo) len<<=1, L++; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); return len; } void PMUL(ll *F,ll *G,ll n,ll m) { // F -> 1+..+x^n G -> 1+...+x^m ll len = init(n+m+1); NTT(F,len,1); NTT(G,len,1); for(ll i=0;i<len;i++) F[i] = F[i] * G[i] %p; NTT(F,len,-1); } int main() { n = read(); m = read(); for(ll i=0;i<=n;i++) F[i] = read(); for(ll i=0;i<=m;i++) G[i] = read(); PMUL(F, G, n, m); for(ll i=0;i<=n+m;i++) cout<<F[i]<<" "; return 0; } ``` === 多项式分治乘 ```cpp const ll N=501010; const ll qwq=303030; const ll inf=0x3f3f3f3f; const ll p=998244353, g=3, gi=332748118; ll n,m; ll rev[N],siz[N]; ll a[N],b[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } void NTT(ll *A,ll len,ll cl) { for(ll i=0;i<len;i++) if(i<rev[i]) swap(A[i],A[rev[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,gk=gk*g1%p) { ll x = A[i+j], y = gk*A[i+j+k] %p; A[i+j] = (x+y) %p; A[i+j+k] = (x-y+p) %p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(ll i=0;i<len;i++) A[i] = A[i] * inv %p; } void solve(ll now,ll l,ll r,ll *F,ll *G) { siz[now] = r-l+1; if(l==r) { G[0] = F[l]; G[1] = 1; // a[i] + x return ; } ll len = 1, L = 0; while(len<=siz[now]) len<<=1, L++; for(int i=0;i<len;i++) G[i] = 0; ll A[len], B[len], mid = l+r >> 1; solve(ls, l, mid, F, A); solve(rs, mid+1, r, F, B); if(r-l<32) { for(ll i=0;i<=siz[ls];i++) for(ll j=0;j<=siz[rs];j++) G[i+j] = (G[i+j] + A[i] * B[j] %p) %p; return ; } for(int i=siz[ls]+1;i<len;i++) A[i] = 0; for(int i=siz[rs]+1;i<len;i++) B[i] = 0; for(ll i=0;i<len;i++) rev[i] = (rev[i>>1]>>1) | ((i&1)<<(L-1)); NTT(A, len, 1); NTT(B, len, 1); for(ll i=0;i<len;i++) G[i] = A[i] * B[i] %p; NTT(G, len, -1); } int main() { n = read(); for(ll i=1;i<=n;i++) a[i] = read(); solve(1, 1, n, a, b); for(ll i=0;i<=n;i++) cout<<b[i]<<" "; return 0; } /* 10 10 9 8 7 6 5 4 3 2 1 3628800 10628640 12753576 8409500 3416930 902055 157773 18150 1320 55 1 */ ``` === 多项式vector ```cpp #include <bits/stdc++.h> #define ll long long #define poly vector<ll> using namespace std; const ll N=301010; const ll inf=0x3f3f3f3f; const ll p=998244353, g=3, gi=332748118, inv2=499122177; ll r[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } inline int init(int wo) { ll len = 1; while(len<wo) len<<=1; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)?len>>1:0); return len; } void NTT(poly &A, ll len, ll cl) { for(ll i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,(gk*=g1)%=p) { ll x = A[i+j], y = gk*A[i+j+k]%p; A[i+j] = (x+y)%p; A[i+j+k] = (x-y+p)%p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(int i=0;i<len;i++) A[i] = A[i] * inv %p; } poly PMUL(poly A,poly B,ll mod=-1) { int deg = A.size() + B.size() - 1; if(A.size()<=32 || B.size()<=32) { poly C(deg, 0); for(int i=0;i<A.size();i++) for(int j=0;j<B.size();j++) (C[i+j] += A[i] * B[j] %p) %= p; return C; } ll len = init(deg); A.resize(len); B.resize(len); NTT(A, len, 1); NTT(B, len, 1); for(int i=0;i<len;i++) A[i] = A[i] * B[i] %p; NTT(A, len, -1); if(mod==-1) A.resize(deg); else A.resize(mod); return A; } poly PI(poly A,int deg=-1) { if(deg==-1) deg = A.size(); poly B(1, ksm(A[0],p-2)), C; for(int k=2; (k>>1)<deg; k<<=1) { C.resize(k); ll len = init(k<<1); for(int i=0;i<k;i++) C[i] = i<(int)A.size() ? A[i] : 0; C.resize(len); B.resize(len); NTT(C, len, 1); NTT(B, len, 1); for(int i=0;i<len;i++) B[i] = (2ll - C[i]*B[i] %p + p) %p * B[i] %p; NTT(B, len, -1); B.resize(k); } B.resize(deg); return B; } poly SQRT(poly A,int deg=-1) { // a[0] = 1 if(deg==-1) deg = A.size(); poly B(1,1), C, D; ll len = 0; for(int k=4; (k>>2)<deg; k<<=1) { C = A; C.resize(k>>1); len = init(k); D = PI(B,k>>1); C.resize(len); D.resize(len); NTT(C, len, 1); NTT(D, len, 1); for(int i=0;i<len;i++) C[i] = C[i] * D[i] %p; NTT(C, len, -1); B.resize(k>>1); for(int i=0;i<(k>>1);i++) B[i] = (B[i] + C[i]) %p * inv2 %p; } B.resize(len); return B; } poly PDIV(poly A,poly B) { int deg = A.size() - B.size() + 1; reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); A.resize(deg); A = PMUL(A, PI(B,deg)); A.resize(deg); reverse(A.begin(), A.end()); return A; } poly PMOD(poly A,poly B) { if(A.size() < B.size()) return A; poly C = PMUL(B, PDIV(A, B)); for(int i=0;i<A.size();i++) A[i] = (A[i] - C[i] + p) %p; A.resize(B.size()-1); return A; } poly Pksm2(poly A,ll K,ll mod) { // log^2 poly B(1,1); while(K) { if(K&1) B = PMUL(B, A, mod); K >>= 1; A = PMUL(A, A, mod); } return B; } poly Pdao(poly A) { for(int i=0;i+1<A.size();i++) A[i]=A[i+1]*(i+1)%p; A.pop_back(); return A; } poly Pji(poly A) { for(int i=A.size()-1;i;i--) A[i]=A[i-1]*ksm(i,p-2)%p; A[0]=0; return A; } poly Pln(poly A,ll mod=-1) { if(mod==-1) mod = A.size(); A = Pji( PMUL( Pdao(A), PI(A,mod) ) ); A.resize(mod); return A; } poly Pexp(poly A,ll mod=-1) { if(mod==-1) mod = A.size(); poly B(1,1), C; for(int k=2;(k>>1)<mod;k<<=1) { C = Pln(B,k); for(int i=0;i<k;i++) C[i] = ((i<(int)A.size()?A[i]:0) - C[i] + p) %p; C[0]++; B = PMUL(B,C); B.resize(k); } B.resize(mod); return B; } poly Pksm(poly A,ll K,ll mod=-1) { if(mod==-1) mod = A.size(); poly B = Pln(A); for(int i=0;i<mod;i++) B[i] = B[i] * K %p; A = Pexp(B); A.resize(mod); return A; } ll n,m,k; poly a, b, e[N]; poly calc(int L,int R) { if(L==R) return e[L]; int mid = L+R >> 1; poly A = calc(L,mid), B = calc(mid+1,R); return PMUL(A,B); } int main() { return 0; } ``` === 多项式求逆 ```cpp const ll N=501010; const ll qwq=303030; const ll inf=0x3f3f3f3f; const ll p=998244353, g=3, gi=332748118; ll n,m; ll r[N]; ll a[N],b[N],c1[N],c2[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } void NTT(ll *A,ll len,ll cl) { for(ll i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,(gk*=g1)%=p) { ll x = A[i+j], y = gk*A[i+j+k]%p; A[i+j] = (x+y)%p; A[i+j+k] = (x-y+p)%p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(ll i=0;i<len;i++) A[i] = A[i] * inv %p; } void PI(ll *F,ll *G,ll n) { // F*G = 1 (mod x^n) G[0] = ksm(F[0],p-2); ll *A=c1, *B=c2, k=1; for(ll len,L=1;k<(n+n);k<<=1,L++) { len = k<<1; for(ll i=0;i<k;i++) A[i] = F[i], B[i] = G[i]; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); NTT(A, len, 1); NTT(B, len, 1); for(ll i=0;i<len;i++) G[i] = (2ll - A[i] * B[i] %p + p) %p * B[i] %p; NTT(G, len, -1); for(ll i=k;i<len;i++) G[i] = 0; } for(ll i=0;i<k;i++) A[i] = B[i] = 0; for(ll i=n;i<k;i++) G[i] = 0; } int main() { n = read(); for(ll i=0;i<n;i++) a[i] = read(); PI(a, b, n); for(ll i=0;i<n;i++) cout<<b[i]<<" "; return 0; } /* 5 1 6 3 4 9 1 998244347 33 998244169 1020 */ ``` === 多项式快速幂 ```cpp const ll N=501010; const ll qwq=303030; const ll inf=0x3f3f3f3f; const ll p=998244353, g=3, gi=332748118; ll n,m,K; ll r[N]; ll a[N],b[N]; ll c1[N],c2[N],c3[N],c4[N],c5[N],c6[N],c7[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } void NTT(ll *A,ll len,ll cl) { for(ll i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,(gk*=g1)%=p) { ll x = A[i+j], y = gk*A[i+j+k]%p; A[i+j] = (x+y)%p; A[i+j+k] = (x-y+p)%p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(ll i=0;i<len;i++) A[i] = A[i] * inv %p; } inline int init(int wo) { ll len = 1, L = 0; while(len<wo) len<<=1, L++; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); return len; } void PMUL(ll *F,ll *G,ll n,ll m) { // F -> 1+..+x^n G -> 1+...+x^m ll len = init(n+m+1); NTT(F,len,1); NTT(G,len,1); for(ll i=0;i<len;i++) F[i] = F[i] * G[i] %p; NTT(F,len,-1); } void PI(ll *F,ll *G,ll n) { // F*G = 1 (mod x^n) G[0] = ksm(F[0],p-2); ll *A=c1, *B=c2, k=1; for(ll len,L=1;k<(n+n);k<<=1,L++) { len = k<<1; for(ll i=0;i<k;i++) A[i] = F[i], B[i] = G[i]; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); NTT(A, len, 1); NTT(B, len, 1); for(ll i=0;i<len;i++) G[i] = (2ll - A[i] * B[i] %p + p) %p * B[i] %p; NTT(G, len, -1); for(ll i=k;i<len;i++) G[i] = 0; } for(ll i=0;i<k;i++) A[i] = B[i] = 0; for(ll i=n;i<k;i++) G[i] = 0; } void Pdao(ll *F,ll *G,ll n) { for(ll i=1;i<n;i++) G[i-1] = i*F[i] %p; G[n-1] = 0; } void Pji(ll *F,ll *G,ll n) { for(ll i=1;i<n;i++) G[i] = ksm(i,p-2)*F[i-1] %p; G[0] = 0; } void Pln(ll *F,ll *G,ll n) { // G = ln(F) (mod x^n) ll *A=c3, *B=c4; Pdao(F, A, n); PI(F, B, n); PMUL(A, B, n, n); Pji(A, G, n); } void Pexp(ll *F,ll *G,ll n) { // G = exp(F) (mod x^n) if(n==1) { G[0] = 1; return ; } Pexp(F, G, (n+1)>>1); ll *A=c5, *B=c6; for(ll i=0;i<=(n<<1);i++) A[i] = B[i] = 0; Pln(G, A, n); ll len = init(n+n); for(ll i=0;i<n;i++) B[i] = F[i]; NTT(G, len, 1); NTT(A, len, 1); NTT(B, len, 1); for(ll i=0;i<len;i++) G[i] = (1ll-A[i]+B[i]+p) %p *G[i] %p; NTT(G, len, -1); for(ll i=n;i<len;i++) G[i] = 0; } void Pksm(ll *F,ll *G,ll K,ll n) { // G = F^K (mod x^n) int wei = 0, a0 = 0; for(int i=0;i<=n;i++) { if(i==n) return ; if(F[i]) { wei = i; a0 = F[i]; break; } } int inv = ksm(a0,p-2); for(int i=0;i<n-wei;i++) F[i] = F[i+wei] * inv %p; /*-------- a0 = 1 -------*/ ll *A=c7; Pln(F, A, n); memset(c3,0,sizeof(c3)); memset(c4,0,sizeof(c4)); for(int i=0;i<n;i++) A[i] = A[i] * K %p; Pexp(A, G, n); /*---------------------------*/ int mi = ksm(a0,K); for(int i=n-1;i>=K*wei;i--) G[i] = G[i-K*wei] * mi %p; for(int i=0;i<K*wei;i++) G[i] = 0; } int main() { n = read(); K = read(); for(ll i=0;i<n;i++) a[i] = read(); Pksm(a, b, K, n); for(ll i=0;i<n;i++) cout<<b[i]<<" "; return 0; } /* 9 18948465 1 2 3 4 5 6 7 8 9 1 37896930 597086012 720637306 161940419 360472177 560327751 446560856 524295016 */``` === 多项式开根 ```cpp const ll N=501010; const ll qwq=303030; const ll inf=0x3f3f3f3f; const ll p=998244353, g=3, gi=332748118, inv2=499122177; ll n,m; ll r[N]; ll a[N],b[N],c1[N],c2[N],c3[N],c4[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } void NTT(ll *A,ll len,ll cl) { for(ll i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,(gk*=g1)%=p) { ll x = A[i+j], y = gk*A[i+j+k]%p; A[i+j] = (x+y)%p; A[i+j+k] = (x-y+p)%p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(ll i=0;i<len;i++) A[i] = A[i] * inv %p; } void PI(ll *F,ll *G,ll n) { // F*G = 1 (mod x^n) G[0] = ksm(F[0],p-2); ll *A=c1, *B=c2, k=1; for(ll len,L=1;k<(n+n);k<<=1,L++) { len = k<<1; for(ll i=0;i<k;i++) A[i] = F[i], B[i] = G[i]; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); NTT(A, len, 1); NTT(B, len, 1); for(ll i=0;i<len;i++) G[i] = (2ll - A[i] * B[i] %p + p) %p * B[i] %p; NTT(G, len, -1); for(ll i=k;i<len;i++) G[i] = 0; } for(ll i=0;i<k;i++) A[i] = B[i] = 0; for(ll i=n;i<k;i++) G[i] = 0; } void SQRT(ll *F,ll *G,ll n) { // G*G = F (mod x^n) G[0] = 1; ll *A=c3, *B=c4, k=1; for(ll len,L=1;k<(n+n);k<<=1,L++) { len = k<<1; for(ll i=0;i<k;i++) A[i] = F[i]; PI(G, B, k); for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); NTT(A, len, 1); NTT(B, len, 1); for(ll i=0;i<len;i++) A[i] = A[i] * B[i] %p; NTT(A, len, -1); for(ll i=0;i<k;i++) G[i] = (G[i] + A[i]) %p * inv2 %p; for(ll i=k;i<len;i++) G[i] = 0; } for(ll i=0;i<k;i++) A[i] = B[i] = 0; for(ll i=n;i<k;i++) G[i] = 0; } int main() { n = read(); for(ll i=0;i<n;i++) a[i] = read(); SQRT(a, b, n); for(ll i=0;i<n;i++) cout<<b[i]<<" "; return 0; } /* 7 1 8596489 489489 4894 1564 489 35789489 1 503420421 924499237 13354513 217017417 707895465 411020414 */ ``` === 多项式快速幂(双log) ```cpp const ll N=501010; const ll qwq=303030; const ll inf=0x3f3f3f3f; const ll p=998244353, g=3, gi=332748118; inline ll read() { ll sum = 0, ff = 1; char c = getchar(); while(c<'0' || c>'9') { if(c=='-') ff = -1; c = getchar(); } while(c>='0'&&c<='9') { sum = (sum * 10 + c - '0') %p; c = getchar(); } return sum * ff; } ll n,m,K; ll r[N]; ll a[N],b[N]; ll c1[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } void NTT(ll *A,ll len,ll cl) { for(ll i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,(gk*=g1)%=p) { ll x = A[i+j], y = gk*A[i+j+k]%p; A[i+j] = (x+y)%p; A[i+j+k] = (x-y+p)%p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(ll i=0;i<len;i++) A[i] = A[i] * inv %p; } void Pksm(ll *F,ll *G,ll K,ll n) { // G = F^K (mod x^n) ll len = 1, L = 0; while(len-1<n+n+2) len<<=1, L++; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); G[0] = 1; while(K) { NTT(F, len, 1); if(K&1) { NTT(G, len, 1); for(int i=0;i<len;i++) G[i] = G[i] * F[i] %p; NTT(G, len, -1); for(int i=n;i<len;i++) G[i] = 0; } K >>= 1; for(int i=0;i<len;i++) F[i] = F[i] * F[i] %p; NTT(F, len, -1); for(int i=n;i<len;i++) F[i] = 0; } } int main() { n = read(); K = read(); for(ll i=0;i<n;i++) a[i] = read(); Pksm(a, b, K, n); for(ll i=0;i<n;i++) cout<<b[i]<<" "; return 0; } /* 9 18948465 1 2 3 4 5 6 7 8 9 1 37896930 597086012 720637306 161940419 360472177 560327751 446560856 524295016 */``` === 01序列生成函数 (小武) ```cpp #include<stdio.h> #define rint register int typedef long long ll; const int N=(1<<22)+7; const int Mod=998244353; const int G=3; ll qpow(ll x,int y=Mod-2){ ll ret=1; while(y){ if(y&1) ret=ret*x%Mod; x=x*x%Mod,y>>=1; } return ret; } const int Gi=qpow(G); int rk[N]; inline void swap(ll &x,ll &y){x^=y,y^=x,x^=y;} void NTT(bool op,int n,ll *F){ for(rint i=0;i<n;i++) if(i<rk[i]) swap(F[i],F[rk[i]]); for(rint p=2;p<=n;p<<=1){ rint len=p>>1; ll w=qpow(op? G:Gi,(Mod-1)/p); for(rint k=0;k<n;k+=p){ ll now=1; for(rint l=k;l<k+len;l++){ ll t=F[l+len]*now%Mod; F[l+len]=(F[l]-t+Mod)%Mod; F[l]=(F[l]+t)%Mod; now=now*w%Mod; } } } } inline void Cop(int n,ll *a,ll *b){for(int i=0;i<n;i++)a[i]=b[i];} inline void Clear(int n,ll *F){for(int i=0;i<n;i++)F[i]=0;} inline void Rk(int n){for(int i=0;i<n;i++)rk[i]=(rk[i>>1]>>1)|(i&1? n>>1:0);} void Mul(ll *X,int n,int m,ll *a,ll *b){ static ll x[N],y[N]; Cop(n+1,x,a),Cop(m+1,y,b); for(m+=n,n=1;n<=m;n<<=1); Rk(n); NTT(1,n,x),NTT(1,n,y); for(rint i=0;i<n;i++) x[i]=x[i]*y[i]%Mod; NTT(0,n,x); ll inv=qpow(n); for(rint i=0;i<=m;i++) X[i]=x[i]*inv%Mod; Clear(n,x),Clear(n,y); } void Inv(int n,ll *a,ll *b){ static ll x[N]; if(n==1){b[0]=qpow(a[0]);return;} Inv((n+1)>>1,a,b); int m=n; for(n=1;n<(m<<1);n<<=1); Rk(n); Clear(n,x),Cop(m,x,a); NTT(1,n,x),NTT(1,n,b); for(rint i=0;i<n;i++) b[i]=b[i]*(2-x[i]*b[i]%Mod+Mod)%Mod; NTT(0,n,b); ll inv=qpow(n); for(rint i=0;i<m;i++) b[i]=b[i]*inv%Mod; for(rint i=m;i<n;i++) b[i]=0; } ll a[N],b[N],c[N]; ll calc(int n,int K){ Clear(n+3,a),Clear(n+3,b); a[0]=1,a[1]=Mod-2,a[K+2]=1; Inv(n+3,a,b); a[0]=1,a[1]=Mod-1,a[K+2]=0; Mul(c,n+3,n+3,a,b); // printf("[%d %d]\n",n,K); // for(int i=1;i<=n+1;i++) printf("%lld ",c[i]); // printf("\n"); return c[n+1]; } int main(){ int n=read(),K=read(); // printf("%lld\n",calc(n,K)); printf("%lld",(calc(n,K)-calc(n,K-1)+Mod)%Mod); }``` === 第一类斯特林数(行) ```cpp #include <algorithm> #include <iostream> #include <cstring> #include <cstdio> #include <cmath> #define FOR() ll le=e[u].size();for(ll i=0;i<le;i++) #define QWQ cout<<"QwQ\n"; #define ll long long #include <vector> #include <queue> #include <map> using namespace std; const ll N=801010; const ll qwq=303030; const ll inf=0x3f3f3f3f; const ll p=167772161, g=3, gi=55924054; inline ll read() { ll sum = 0, ff = 1; char c = getchar(); while(c<'0' || c>'9') { if(c=='-') ff = -1; c = getchar(); } while(c>='0'&&c<='9') { sum = sum * 10 + c - '0'; c = getchar(); } return sum * ff; } ll f[N],ni[N]; ll rev[N]; ll a[N]; ll c1[N],c2[N],c3[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } void qiu() { f[0] = ni[0] = 1; for(ll i=1;i<=N-10;i++) f[i] = f[i-1] * i %p; ni[N-10] = ksm(f[N-10],p-2); for(ll i=N-11;i>=1;i--) ni[i] = ni[i+1] * (i+1) %p; } void NTT(ll *A,ll len,ll cl) { for(ll i=0;i<len;i++) if(i<rev[i]) swap(A[i],A[rev[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,gk=gk*g1%p) { ll x = A[i+j], y = gk*A[i+j+k] %p; A[i+j] = (x+y) %p; A[i+j+k] = (x-y+p) %p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(int i=0;i<len;i++) A[i] = A[i] * inv %p; } inline int init(int wo) { ll len = 1, L = 0; while(len<wo) len<<=1, L++; for(ll i=0;i<len;i++) rev[i] = (rev[i>>1]>>1) | ((i&1)<<(L-1)); return len; } void PMUL(ll *F,ll *G,ll n,ll m) { // F -> 1+..+x^n G -> 1+...+x^m ll len = init(n+m+1); NTT(F,len,1); NTT(G,len,1); for(ll i=0;i<len;i++) F[i] = F[i] * G[i] %p; NTT(F,len,-1); } void solve(ll *F,ll m) { if(m==1) { F[1] = 1; return ; } if(m&1) { solve(F, m-1); for(ll i=m;i>=1;i--) F[i] = (F[i-1] + F[i] * (m-1) %p) %p; F[0] = F[0] * (m-1) %p; } else { ll n = m/2; ll res = 1, *A = c1, *B = c2, *G = c3; solve(F, n); for(ll i=0;i<=n;i++) { A[i] = F[i] * f[i] %p; B[i] = res * ni[i] %p; res = res * n %p; } reverse(A, A+n+1); PMUL(A, B, n, n); for(ll i=0;i<=n;i++) G[i] = ni[i] * A[n-i] %p; PMUL(F, G, n, n); ll len = 1; while(len < (n+1)<<1) len <<= 1; for(ll i=n+1;i<len;i++) A[i] = B[i] = G[i] = 0; for(ll i=m+1;i<len;i++) F[i] = 0; } } int main() { qiu(); ll n; n = read(); solve(a, n); for(ll i=0;i<=n;i++) cout<<(a[i]%p+p)%p<<" "; return 0; } ``` === 三模数NTT ```cpp const ll N=301010; const ll inf=0x3f3f3f3f; const ll p1=469762049, p2=998244353, p3=1004535809, g=3; const ll M = p1 * p2; typedef long double db; ll n,m,P; ll r[N]; ll a[N],b[N]; ll c1[N],c2[N]; ll A1[N],A2[N],A3[N]; inline ll ksm(ll aa,ll bb,ll p) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } inline ll gsc(ll aa,ll bb,ll p) { aa %= p; bb %= p; return (( aa * bb - (ll)( (ll)((db)aa / p * bb + 1e-3) * p)) %p + p) %p; } void NTT(ll *A,ll len,ll cl,ll p) { ll gi = ksm(3,p-2,p); for(ll i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1), p); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,gk=gk*g1%p) { ll x = A[i+j], y = gk*A[i+j+k] %p; A[i+j] = (x+y) %p; A[i+j+k] = (x-y+p) %p; } } } if(cl==1) return ; ll inv = ksm(len,p-2, p); for(int i=0;i<len;i++) A[i] = A[i] * inv %p; } inline int init(int wo) { ll len = 1, L = 0; while(len<wo) len<<=1, L++; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); return len; } void PMUL(ll *F,ll *G,ll n,ll m) { // F -> 1+..+x^n G -> 1+...+x^m ll len = init(n+m+1); ll *A = c1, *B = c2; for(int i=0;i<len;i++) A[i] = (i<=n) ? F[i] : 0, B[i] = (i<=m) ? G[i] : 0; NTT(A,len,1,p1); NTT(B,len,1,p1); for(ll i=0;i<len;i++) A1[i] = A[i] * B[i] %p1; NTT(A1,len,-1,p1); for(int i=0;i<len;i++) A[i] = (i<=n) ? F[i] : 0, B[i] = (i<=m) ? G[i] : 0; NTT(A,len,1,p2); NTT(B,len,1,p2); for(ll i=0;i<len;i++) A2[i] = A[i] * B[i] %p2; NTT(A2,len,-1,p2); for(int i=0;i<len;i++) A[i] = (i<=n) ? F[i] : 0, B[i] = (i<=m) ? G[i] : 0; NTT(A,len,1,p3); NTT(B,len,1,p3); for(ll i=0;i<len;i++) A3[i] = A[i] * B[i] %p3; NTT(A3,len,-1,p3); for(int i=0;i<=n+m;i++) { ll wo = (gsc(A1[i]*p2%M, ksm(p2%p1, p1-2, p1), M) + gsc(A2[i]*p1%M, ksm(p1%p2, p2-2, p2), M)) %M; ll K = ((A3[i]-wo) % p3 + p3) %p3 * ksm(M%p3, p3-2, p3) %p3; F[i] = ((K%P) * (M%P) %P + wo%P) %P; } } int main() { n = read(); m = read(); P = read(); for(ll i=0;i<=n;i++) a[i] = read(); for(ll i=0;i<=m;i++) b[i] = read(); PMUL(a, b, n, m); for(ll i=0;i<=n+m;i++) cout<<a[i]<<" "; return 0; } ``` === 多项式除法 ```cpp const ll N=501010; const ll qwq=303030; const ll inf=0x3f3f3f3f; const ll p=998244353, g=3, gi=332748118, inv2=499122177; ll n,m; ll r[N]; ll a[N],b[N]; ll c1[N],c2[N],c3[N]; ll Q[N],R[N]; ll Fr[N],Gri[N],Gr[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } void NTT(ll *A,ll len,ll cl) { for(ll i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,(gk*=g1)%=p) { ll x = A[i+j], y = gk*A[i+j+k]%p; A[i+j] = (x+y)%p; A[i+j+k] = (x-y+p)%p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(ll i=0;i<len;i++) A[i] = A[i] * inv %p; } void PI(ll *F,ll *G,ll n) { // F*G = 1 (mod x^n) G[0] = ksm(F[0],p-2); ll *A=c1, *B=c2, k=1; for(ll len,L=1;k<(n+n);k<<=1,L++) { len = k<<1; for(ll i=0;i<k;i++) A[i] = F[i], B[i] = G[i]; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); NTT(A, len, 1); NTT(B, len, 1); for(ll i=0;i<len;i++) G[i] = (2ll - A[i] * B[i] %p + p) %p * B[i] %p; NTT(G, len, -1); for(ll i=k;i<len;i++) G[i] = 0; } for(ll i=0;i<k;i++) A[i] = B[i] = 0; for(ll i=n;i<k;i++) G[i] = 0; } inline int init(int wo) { ll len = 1, L = 0; while(len<wo) len<<=1, L++; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); return len; } void PMUL(ll *F,ll *G,ll n,ll m) { // F -> 1+..+x^n G -> 1+...+x^m ll len = init(n+m+1); NTT(F,len,1); NTT(G,len,1); for(ll i=0;i<len;i++) F[i] = F[i] * G[i] %p; NTT(F,len,-1); } void PDIV(ll *F,ll *G,ll *Q,ll *R,ll n,ll m) { // F -> 1+..+x^n G -> 1+...+x^m for(ll i=0;i<=n;i++) Fr[n-i] = F[i]; for(ll i=0;i<=m;i++) Gr[m-i] = G[i]; for(ll i=n-m+2;i<=m;i++) Gr[i] = 0; PI(Gr,Gri,n-m+1); PMUL(Fr,Gri,n,n-m); for(ll i=0;i<=n-m;i++) Q[n-m-i] = Fr[i]; ll *A = c3; for(ll i=0;i<=n-m;i++) A[i] = Q[i]; PMUL(G,A,m,n-m); for(ll i=0;i<m;i++) R[i] = (F[i]-G[i]+p)%p; } int main() { n = read(); m = read(); for(ll i=0;i<=n;i++) a[i] = read(); for(ll i=0;i<=m;i++) b[i] = read(); PDIV(a,b,Q,R,n,m); for(ll i=0;i<=n-m;i++) cout<<Q[i]<<" "; cout<<endl; for(ll i=0;i<m;i++) cout<<R[i]<<" "; return 0; } /* 5 1 1 9 2 6 0 8 1 7 237340659 335104102 649004347 448191342 855638018 760903695 */ ``` === 第二类斯特林数(行) ```cpp const ll N=801010; const ll qwq=303030; const ll inf=0x3f3f3f3f; const ll p=167772161, g=3, gi=55924054; ll n,m; ll r[N]; ll a[N],b[N]; ll f[N],ni[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } void qiu() { f[0] = ni[0] = 1; for(int i=1;i<=N-10;i++) f[i] = f[i-1] * i %p; ni[N-10] = ksm(f[N-10],p-2); for(int i=N-11;i>=1;i--) ni[i] = ni[i+1] * (i+1) %p; } void NTT(ll *A,ll len,ll cl) { for(ll i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,gk=gk*g1%p) { ll x = A[i+j], y = gk*A[i+j+k] %p; A[i+j] = (x+y) %p; A[i+j+k] = (x-y+p) %p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(int i=0;i<len;i++) A[i] = A[i] * inv %p; } inline int init(int wo) { ll len = 1, L = 0; while(len<wo) len<<=1, L++; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); return len; } void PMUL(ll *F,ll *G,ll n,ll m) { // F -> 1+..+x^n G -> 1+...+x^m ll len = init(n+m+1); NTT(F,len,1); NTT(G,len,1); for(ll i=0;i<len;i++) F[i] = F[i] * G[i] %p; NTT(F,len,-1); } int main() { qiu(); n = read(); for(int i=0;i<=n;i++) { a[i] = (p+((i&1)?-1:1) * ni[i]) %p; b[i] = ksm(i,n) * ni[i] %p; } PMUL(a,b,n,n); for(int i=0;i<=n;i++) cout<<a[i]<<" "; return 0; } /* 通项公式: for(int i=0;i<=k;i++) S(n,k) += ((-1)^(k-i) * i^n) / (i! * (k-i)!) */``` === FFT ```cpp const ll N=3001010; const ll qwq=303030; const ll inf=0x3f3f3f3f; typedef long double db; const db pi = acos(-1.0); int n,m; int r[N]; complex <db> F[N],G[N],ans[N]; void FFT(complex <db> *A,int len,int cl) { for(int i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(int k=1;k<len;k<<=1) { complex <db> w1( cos(pi/k), cl*sin(pi/k) ); for(int j=0;j<len;j+=(k<<1)) { complex <db> wk(1,0); for(int i=0;i<k;i++,wk*=w1) { complex <db> x = A[i+j], y = wk*A[i+j+k]; A[i+j] = x+y; A[i+j+k] = x-y; } } } if(cl==-1) for(int i=0;i<len;i++) A[i].real(A[i].real()/len); } inline int init(int wo) { ll len = 1, L = 0; while(len<wo) len<<=1, L++; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); return len; } int main() { n = read(); m = read(); int len = init(n+m+1); for(int i=0;i<=n;i++) F[i].real(read()); for(int i=0;i<=m;i++) G[i].real(read()); FFT(F,len,1); FFT(G,len,1); for(int i=0;i<len;i++) ans[i] = F[i] * G[i]; FFT(ans,len,-1); for(int i=0;i<=n+m;i++) cout<<(int)round(ans[i].real())<<" "; return 0; } ``` === 第二类斯特林数(列) ```cpp const ll N=801010; const ll qwq=303030; const ll inf=0x3f3f3f3f; const ll p=167772161, g=3, gi=55924054; ll n,m,K; ll r[N]; ll a[N],b[N],c[N]; ll c1[N],c2[N],c3[N],c4[N],c5[N],c6[N],c7[N]; ll f[N],ni[N]; inline ll ksm(ll aa,ll bb) { ll sum = 1; while(bb) { if(bb&1) sum = sum * aa %p; bb >>= 1; aa = aa * aa %p; } return sum; } void qiu() { f[0] = ni[0] = 1; for(int i=1;i<=N-10;i++) f[i] = f[i-1] * i %p; ni[N-10] = ksm(f[N-10],p-2); for(int i=N-11;i>=1;i--) ni[i] = ni[i+1] * (i+1) %p; } void NTT(ll *A,ll len,ll cl) { for(ll i=0;i<len;i++) if(i<r[i]) swap(A[i],A[r[i]]); for(ll k=1;k<len;k<<=1) { ll g1 = ksm((cl==1)?g:gi, (p-1)/(k<<1)); for(ll j=0;j<len;j+=(k<<1)) { ll gk = 1; for(ll i=0;i<k;i++,(gk*=g1)%=p) { ll x = A[i+j], y = gk*A[i+j+k]%p; A[i+j] = (x+y)%p; A[i+j+k] = (x-y+p)%p; } } } if(cl==1) return ; ll inv = ksm(len,p-2); for(ll i=0;i<len;i++) A[i] = A[i] * inv %p; } inline int init(int wo) { ll len = 1, L = 0; while(len<wo) len<<=1, L++; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); return len; } void PMUL(ll *F,ll *G,ll n,ll m) { // F -> 1+..+x^n G -> 1+...+x^m ll len = init(n+m+1); NTT(F,len,1); NTT(G,len,1); for(ll i=0;i<len;i++) F[i] = F[i] * G[i] %p; NTT(F,len,-1); } void PI(ll *F,ll *G,ll n) { // F*G = 1 (mod x^n) G[0] = ksm(F[0],p-2); ll *A=c1, *B=c2, k=1; for(ll len,L=1;k<(n+n);k<<=1,L++) { len = k<<1; for(ll i=0;i<k;i++) A[i] = F[i], B[i] = G[i]; for(ll i=0;i<len;i++) r[i] = (r[i>>1]>>1) | ((i&1)<<(L-1)); NTT(A, len, 1); NTT(B, len, 1); for(ll i=0;i<len;i++) G[i] = (2ll - A[i] * B[i] %p + p) %p * B[i] %p; NTT(G, len, -1); for(ll i=k;i<len;i++) G[i] = 0; } for(ll i=0;i<k;i++) A[i] = B[i] = 0; for(ll i=n;i<k;i++) G[i] = 0; } void Pdao(ll *F,ll *G,ll n) { for(ll i=1;i<n;i++) G[i-1] = i*F[i] %p; G[n-1] = 0; } void Pji(ll *F,ll *G,ll n) { for(ll i=1;i<n;i++) G[i] = ksm(i,p-2)*F[i-1] %p; G[0] = 0; } void Pln(ll *F,ll *G,ll n) { // G = ln(F) (mod x^n) ll *A=c3, *B=c4; memset(c3,0,sizeof(c3)); memset(c4,0,sizeof(c4)); Pdao(F, A, n); PI(F, B, n); PMUL(A, B, n, n); Pji(A, G, n); } void Pexp(ll *F,ll *G,ll n) { // G = exp(F) (mod x^n) if(n==1) { G[0] = 1; return ; } Pexp(F, G, (n+1)>>1); ll *A=c5, *B=c6; for(ll i=0;i<=(n<<1);i++) A[i] = B[i] = 0; Pln(G, A, n); ll len = init(n+n); for(ll i=0;i<n;i++) B[i] = F[i]; NTT(G, len, 1); NTT(A, len, 1); NTT(B, len, 1); for(ll i=0;i<len;i++) G[i] = (1ll-A[i]+B[i]+p) %p *G[i] %p; NTT(G, len, -1); for(ll i=n;i<len;i++) G[i] = 0; } void Pksm(ll *F,ll *G,ll K,ll n) { // G = F^K (mod x^n) ll *A=c7; Pln(F, A, n); for(int i=0;i<n;i++) A[i] = A[i] * K %p; Pexp(A, G, n); } void stling() { for(int i=0;i<=n;i++) a[i] = ni[i+1]; Pksm(a, c, K, n+1); for(int i=n;i>=0;i--) { if(i>=K) c[i] = c[i-K]; else c[i] = 0; } for(int i=0;i<=n;i++) c[i] = c[i] * f[i] %p * ni[K] %p; } int main() { qiu(); n = read(); K = read(); stling(); for(int i=0;i<=n;i++) cout<<c[i]<<" "; return 0; } ``` == 数据结构 === 李超树 ```cpp #include <bits/stdc++.h> #define ll long long #define db double #define ls now<<1 #define rs now<<1|1 using namespace std; const int p1=39989; const int p2=1000000000; const double eps = 1e-9; const int N=101010; const int RR=40404; int T,ans,cnt; struct E{ db K,B; int id; }d[N],t[RR<<2]; inline void add(int x0,int y0,int x1,int y1) { ++cnt; if(x0==x1) d[cnt] = {0,(db)max(y0,y1),cnt}; else d[cnt].K = (db)(y1-y0)/(x1-x0), d[cnt].B = y0-d[cnt].K*x0, d[cnt].id = cnt; } inline db w(E L,int x) { return L.K * x + L.B; } bool cmp(E L1,E L2,int x) { if(fabs(w(L1,x)-w(L2,x))<eps) return L1.id<L2.id; return w(L1,x)>w(L2,x); } // L1 > L2 void insert(int now,int l,int r,E g) { if( cmp(g,t[now],l) && cmp(g,t[now],r)) { t[now] = g; return; } if(!cmp(g,t[now],l) && !cmp(g,t[now],r)) return ; int mid = l+r >> 1; if(t[now].K < g.K) { if(cmp(g,t[now],mid)) insert(ls, l, mid, t[now]), t[now] = g; else insert(rs, mid+1, r, g); } else { if(cmp(g,t[now],mid)) insert(rs, mid+1, r, t[now]), t[now] = g; else insert(ls, l, mid, g); } } void update(int now,int l,int r,int x,int y,E g) { if(x<=l && r<=y) { insert(now, l, r, g); return ; } int mid = l+r >> 1; if(x<=mid) update(ls, l, mid, x, y, g); if(mid<y) update(rs, mid+1, r, x, y, g); } E query(int now,int l,int r,int x) { if(l==r) return t[now]; int mid = l+r >> 1; E res = t[now]; if(x<=mid) { E la = query(ls, l, mid, x); if(cmp(la,res,x)) res=la; } else { E ra = query(rs, mid+1, r, x); if(cmp(ra,res,x)) res=ra; } return res; } int main() { T = read(); while(T--) { int cz; cz = read(); if(cz==1) { int x0, y0, x1, y1; x0 = read(); y0 = read(); x1 = read(); y1 = read(); if(x0>x1) swap(x0,x1), swap(y0,y1); add(x0,y0,x1,y1); update(1, 1, RR, x0, x1, d[cnt]); } else { int x = read(); cout<<w(query(1, 1, RR, x),x)<<endl; } } return 0; }``` === 点分树 ```cpp /* 求树上邻域权值和,单点修改 */ #include<stdio.h> #include<vector> using namespace std; inline int read(){ int x=0,flag=1; char c=getchar(); while(c<'0'||c>'9'){if(c=='-')flag=-1;c=getchar();} while(c>='0'&&c<='9'){x=(x<<1)+(x<<3)+c-48;c=getchar();} return flag*x; } const int N=1e5+7; int fa[N][20],sz[N],dep[N],Fa[N][20],Dis[N][20],Dep[N],v[N]; vector<int> g[N],C[N][2]; bool vis[N]; inline void swap(int &x,int &y){x^=y^=x^=y;} int Lca(int x,int y){ if(dep[x]<dep[y]) swap(x,y); for(int i=16;~i;i--) if(dep[fa[x][i]]>=dep[y]) x=fa[x][i]; if(x==y) return y; for(int i=16;~i;i--) if(fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i]; return fa[x][0]; } inline int lowbit(const int &x){return -x&x;} inline void add(vector<int> &V,int x,int val){ while(x<(int)V.size())V[x]+=val,x+=lowbit(x); } inline int query(vector<int> &V,int x){ x=min((int)V.size()-1,x); int tmp=0;while(x)tmp+=V[x],x-=lowbit(x);return tmp; } int dis(int x,int y){return dep[x]+dep[y]-2*dep[Lca(x,y)];} void dfs(int u){ dep[u]=dep[fa[u][0]]+1; for(int i=1;i<17;i++) fa[u][i]=fa[fa[u][i-1]][i-1]; for(int v:g[u]) if(v!=fa[u][0]) fa[v][0]=u,dfs(v); } void count(int &s,int u,int f){ s++; for(int v:g[u]) if(v!=f&&!vis[v]) count(s,v,u); } void find_rt(int &rt,int &Min,int u,int f,const int &s){ sz[u]=1; int tmp=0; for(int v:g[u]) if(v!=f&&!vis[v]){ find_rt(rt,Min,v,u,s); sz[u]+=sz[v],tmp=max(sz[v],tmp); } tmp=max(s-sz[u],tmp); if(tmp<Min) Min=tmp,rt=u; } void Dfs(int u,int f){ int s=0,Min,rt; count(s,u,u),Min=s,rt=u; find_rt(rt,Min,u,u,s),vis[rt]=1; C[rt][0].resize(sz[u]+2); C[rt][1].resize(sz[u]+2); for(int i=0;i<17;i++){ Fa[rt][i]=i? Fa[f][i-1]:f; if(!Fa[rt][i]) break; Dis[rt][i]=dis(rt,Fa[rt][i]); add(C[Fa[rt][i]][0],Dis[rt][i],v[rt]); add(C[i? Fa[rt][i-1]:rt][1],Dis[rt][i],v[rt]); } for(int v:g[rt]) if(!vis[v]&&v!=f) Dfs(v,rt); } int main(){ // freopen("P6329_1.in","r",stdin); // freopen("mine.txt","w",stdout); int n=read(),m=read(),ans=0; for(int i=1;i<=n;i++) v[i]=read(); for(int i=1;i<n;i++){ int u=read(),v=read(); g[u].push_back(v); g[v].push_back(u); } dfs(1); Dfs(1,0); // for(int i=1;i<=n;i++) // printf("Fa[%d]=%d\n",i,Fa[i][0]); while(m--){ int op=read(); int x=read()^ans,y=read()^ans; // int x=read(),y=read(); if(!op){ int p=0; ans=query(C[x][0],y)+v[x]; while(Fa[x][p]){ if(y>Dis[x][p]) ans+=query(C[Fa[x][p]][0],y-Dis[x][p]) -query(C[p? Fa[x][p-1]:x][1],y-Dis[x][p]); if(y>=Dis[x][p]) ans+=v[Fa[x][p]]; p++; } printf("%d\n",ans); }else{ int p=0; while(Fa[x][p]){ add(C[Fa[x][p]][0],Dis[x][p],y-v[x]); add(C[p? Fa[x][p-1]:x][1],Dis[x][p],y-v[x]); p++; } v[x]=y; } } } ``` === LCT ```cpp #include <bits/stdc++.h> #define ll long long #define QWQ cout<<"QwQ"<<endl; #define FOR() int le=e[u].size();for(int i=0;i<le;i++) #define ls son[x][0] #define rs son[x][1] using namespace std; const int N=501010; const int inf=0x3f3f3f3f; int n,m,tot; int fa[N],son[N][2],val[N],sum[N],rev[N]; int st[N],cnt; inline void pushup(int x) { sum[x] = sum[ls] ^ sum[rs] ^ val[x]; } inline void rever(int x) { rev[x] ^= 1; swap(ls,rs); } inline void pushdown(int x) { if(rev[x]) { rev[x] = 0; if(ls) rever(ls); if(rs) rever(rs); } } inline bool touhou(int x) { return son[fa[x]][1]==x; } inline bool flandre(int x) { return son[fa[x]][0]==x || son[fa[x]][1]==x; } inline void rotate(int x) { int y = fa[x], z = fa[y], k = touhou(x), w = son[x][k^1]; if(flandre(y)) son[z][touhou(y)] = x; son[x][k^1] = y; son[y][k] = w; if(w) fa[w] = y; fa[y] = x; fa[x] = z; pushup(y); pushup(x); } inline void splay(int x) { int y = x; st[++cnt] = y; while(flandre(y)) st[++cnt] = (y=fa[y]); while(cnt) pushdown(st[cnt--]); while(flandre(x)) { y = fa[x]; if(flandre(y)) { if(touhou(y)==touhou(x)) rotate(y); else rotate(x); } rotate(x); } } inline void access(int x) { for(int y=0;x;x=fa[y=x]) splay(x), son[x][1] = y, pushup(x); } inline void makert(int x) { access(x); splay(x); rever(x); } inline void split(int x,int y) { makert(x); access(y); splay(y); } int find(int x) { access(x); splay(x); while(ls) pushdown(ls), x = ls; splay(x); return x; } inline void link(int x,int y) { makert(x); if(find(y)!=x) fa[x] = y; } inline void cut(int x,int y) { makert(x); if(find(y)==x && fa[y]==x && !son[y][0]) fa[y] = son[x][1] = 0, pushup(x); } inline bool judge(int x,int y) { while(fa[x]) x = fa[x]; while(fa[y]) y = fa[y]; return x==y; } // 是否连通 int main() { int cz,x,y; n = read(); m = read(); for(int i=1;i<=n;i++) val[i] = read(); while(m--) { cz = read(); x = read(); y = read(); if(cz==0) { split(x,y); cout<<sum[y]<<"\n"; } if(cz==1) { link(x,y); } if(cz==2) { cut(x,y); } if(cz==3) { splay(x); sum[x] ^= y ^ val[x]; val[x] = y; } } return 0; }``` === 线段树合并(雨天的尾巴) ```cpp #include <bits/stdc++.h> #define FOR() int le=e[u].size();for(int i=0;i<le;i++) #define ls L[now] #define rs R[now] using namespace std; const int N=101010; const int big = 100000; int n,m; vector <int> e[N]; int t[N*20],d[N*20],rt[N],cnt,L[N*20],R[N*20]; int dep[N],f[N][22]; int ans[N]; void DFS(int u,int fa) { f[u][0] = fa; dep[u] = dep[fa] + 1; FOR() { int v = e[u][i]; if(v==fa) continue; DFS(v,u); } } inline int LCA(int x,int y) { if(dep[x]<dep[y]) swap(x,y); for(int k=20;k>=0;k--) if(dep[ f[x][k] ] >= dep[y]) x = f[x][k]; if(x==y) return x; for(int k=20;k>=0;k--) if(f[x][k] != f[y][k]) x = f[x][k], y = f[y][k]; return f[x][0]; } inline void pushup(int now) { // 合并次数最多的颜色,相同则选择左侧 if(d[ls]>=d[rs]) d[now] = d[ls], t[now] = t[ls]; else d[now] = d[rs], t[now] = t[rs]; } void insert(int &now,int l,int r,int x,int g) { if(!now) now = ++cnt; if(l==r) { d[now] += g; t[now] = l; return ; } int mid = l+r >> 1; if(x<=mid) insert(ls, l, mid, x, g); else insert(rs, mid+1, r, x, g); pushup(now); } int merge(int r1,int r2,int l,int r) { if(!r1 || !r2) return r1 + r2; if(l==r) { d[r1] += d[r2]; return r1; } int mid = l+r >> 1; L[r1] = merge(L[r1], L[r2], l, mid); R[r1] = merge(R[r1], R[r2], mid+1, r); pushup(r1); return r1; } void hebing(int u) { FOR() { int v = e[u][i]; if(v==f[u][0]) continue; hebing(v); rt[u] = merge(rt[u], rt[v], 1, big); } if(d[ rt[u] ]) ans[u] = t[ rt[u] ]; } int main() { int x,y,z; n = read(); m = read(); for(int i=1;i<n;i++) { x = read(); y = read(); e[x].push_back(y); e[y].push_back(x); } DFS(1,0); for(int k=1;k<=20;k++) for(int i=1;i<=n;i++) f[i][k] = f[ f[i][k-1] ][k-1]; while(m--) { x = read(); y = read(); z = read(); int lca = LCA(x,y); insert(rt[x], 1, big, z, 1); insert(rt[y], 1, big, z, 1); insert(rt[lca], 1, big, z, -1); if(f[lca][0]) insert(rt[f[lca][0]], 1, big, z, -1); } hebing(1); for(int i=1;i<=n;i++) cout<<ans[i]<<"\n"; return 0; }``` === 换根树剖 ```cpp #define ls now<<1 #define rs now<<1|1 using namespace std; const int N=101010; const int qwq=N<<2; const int inf=0x3f3f3f3f; int T; int n,m,root = 1; int a[N]; vector <int> e[N]; int son[N],fa[N],dep[N],siz[N]; int tp[N],id[N],w[N],cnt; ll t[qwq],tag[qwq]; void DFS(int u,int f) { dep[u] = dep[f] + 1; siz[u] = 1; fa[u] = f; FOR() { int v = e[u][i]; if(v==f) continue; DFS(v,u); siz[u] += siz[v]; if(siz[v] > siz[son[u]]) son[u] = v; } } void DFS2(int u,int zuzu) { tp[u] = zuzu; id[u] = ++cnt; w[cnt] = a[u]; if(son[u]) DFS2(son[u],zuzu); FOR() { int v = e[u][i]; if(v==fa[u] || v==son[u]) continue; DFS2(v,v); } } inline void pushdown(int now,int l,int r) { if(!tag[now]) return ; int mid = l+r >> 1; tag[ls] += tag[now]; tag[rs] += tag[now]; t[ls] += tag[now] * (ll)(mid-l+1); t[rs] += tag[now] * (ll)(r-mid); tag[now] = 0; } void built(int now,int l,int r) { if(l==r) { t[now] = w[l]; return ; } int mid = l+r >> 1; built(ls, l, mid); built(rs, mid+1, r); t[now] = t[ls] + t[rs]; } inline void insert(int now,int l,int r,int x,int y,ll g) { if(x<=l && r<=y) { t[now] += (r-l+1) * g; tag[now] += g; return ; } int mid = l+r >> 1; pushdown(now, l, r); if(x<=mid) insert(ls, l, mid, x, y, g); if(y>mid) insert(rs, mid+1, r, x, y, g); t[now] = t[ls] + t[rs]; } inline ll query(int now,int l,int r,int x,int y) { if(x<=l && r<=y) return t[now]; ll res = 0, mid = l+r >> 1; pushdown(now, l, r); if(x<=mid) res += query(ls, l, mid, x, y); if(y>mid) res += query(rs, mid+1, r, x, y); return res; } inline int lca(int x,int y) { while(tp[x] != tp[y]) { if(dep[tp[x]] < dep[tp[y]]) swap(x,y); x = fa[tp[x]]; } if(dep[x] > dep[y]) swap(x,y); return x; } inline int LCA(int x,int y) { if(dep[x]>dep[y]) swap(x,y); int rx = lca(x,root), ry = lca(y,root), xy = lca(x,y); if(xy==x) { if(rx==x) { if(ry==y) return y; return ry; } return x; } if(rx==x) return x; if(ry==y) return y; if((rx==root&&xy==ry) || (ry==root&&xy==rx)) return root; if(rx==ry) return xy; if(xy!=rx) return rx; return ry; } inline int find(int x,int y) { // find the son of x while(tp[x] != tp[y]) { if(dep[tp[x]] < dep[tp[y]]) swap(x,y); if(fa[tp[x]]==y) return tp[x]; x = fa[tp[x]]; } if(dep[x] > dep[y]) swap(x,y); return son[x]; } inline void add(int x,ll g) { if(x==root) { t[1] += n * g; tag[1] += g; return ; } if(id[root]>id[x] && id[root]<=id[x]+siz[x]-1) { // root in x int y = find(x, root); t[1] += n * g; tag[1] += g; insert(1, 1, n, id[y], id[y]+siz[y]-1, -g); } else insert(1, 1, n, id[x], id[x]+siz[x]-1, g); } inline ll ask(int x) { if(x==root) return t[1]; if(id[root]>id[x] && id[root]<=id[x]+siz[x]-1) { int y = find(x, root); return t[1] - query(1, 1, n, id[y], id[y]+siz[y]-1); } return query(1, 1, n, id[x], id[x]+siz[x]-1); } int main() { int cz,x,y,z; n = read(); m = read(); for(int i=1;i<=n;i++) a[i] = read(); for(int i=1;i<n;i++) { x = read(); y = read(); e[x].push_back(y); e[y].push_back(x); } DFS(1,0); DFS2(1,1); built(1,1,n); while(m--) { cz = read(); if(cz==1) root = read(); if(cz==2) { x = read(); y = read(); z = read(); add(LCA(x,y), z); } if(cz==3) { x = read(); printf("%lld\n",ask(x)); } } return 0; } ``` === 可持久化01tire ```cpp #define ls L[now] #define rs R[now] using namespace std; const ll N=501010; const ll qwq=N*35; const ll inf=0x3f3f3f3f; ll n,K; ll ans; ll a[N]; ll cnt[N]; ll rt[N],tot; ll val[qwq]; ll L[qwq],R[qwq],siz[qwq]; struct E{ ll zhi,id; }; inline bool operator < (E A,E B) { return A.zhi < B.zhi; } priority_queue <E> q; void insert(ll &now,ll pre,ll h,ll v) { now = ++tot; siz[now] = siz[pre] + 1; ls = L[pre]; rs = R[pre]; if(h==-1) { val[now] = v; return ; } if((v>>h)&1) insert(rs, R[pre], h-1, v); else insert(ls, L[pre], h-1, v); } ll query(ll now,ll k,ll h,ll v) { if(h==-1) { return v ^ val[now]; } if((v>>h)&1) { if(siz[ls] >= k) return query(ls, k, h-1, v); else return query(rs, k-siz[ls], h-1, v); } else { if(siz[rs] >= k) return query(rs, k, h-1, v); else return query(ls, k-siz[rs], h-1, v); } } int main() { ll x; n = read(); K = read(); for(ll i=1;i<=n;i++) { x = read(); a[i] = a[i-1] ^ x; insert(rt[i], rt[i-1], 31, a[i-1]); q.push( E{query(rt[i], ++cnt[i], 31, a[i]), i} ); } ll ci = 0; while(!q.empty()) { E now = q.top(); q.pop(); ans += now.zhi; ci++; if(ci==K) break; ll u = now.id; if(cnt[u] < u) q.push( E{query(rt[u], ++cnt[u], 31, a[u]), u} ); } cout<<ans; return 0; } ``` === 树剖 ```cpp int n,m,rt,p; int a[N]; vector <int> e[N]; int siz[N],fa[N],son[N],dep[N]; int cnt,tp[N],id[N],w[N]; ll tree[qwq],tag[qwq]; void DFS1(int u,int f) { dep[u] = dep[f] + 1; siz[u] = 1; fa[u] = f; FOR() { int v = e[u][i]; if(v==f) continue; DFS1(v,u); siz[u] += siz[v]; if(siz[v] > siz[son[u]]) son[u] = v; } } void DFS2(int u,int zuzu) { tp[u] = zuzu; id[u] = ++cnt; w[cnt] = a[u]; if(son[u]) DFS2(son[u],zuzu); FOR() { int v = e[u][i]; if(v==fa[u] || v==son[u]) continue; DFS2(v,v); } } inline void add(int x,int y,int g) { while(tp[x] != tp[y]) { if(dep[tp[x]] < dep[tp[y]]) swap(x,y); insert(1, 1, n, id[tp[x]], id[x], g); x = fa[ tp[x] ]; } if(dep[x] > dep[y]) swap(x,y); insert(1, 1, n, id[x], id[y], g); } inline int ask(int x,int y) { ll res = 0; while(tp[x] != tp[y]) { if(dep[tp[x]] < dep[tp[y]]) swap(x,y); (res += query(1, 1, n, id[tp[x]], id[x])) %= p; x = fa[ tp[x] ]; } if(dep[x] > dep[y]) swap(x,y); (res += query(1, 1, n, id[x], id[y])) %= p; return res; } int main() { int x,y,z,cz; n = read(); m = read(); rt = read(); p = read(); for(int i=1;i<=n;i++) a[i] = read(); for(int i=1;i<n;i++) { x = read(); y = read(); e[x].push_back(y); e[y].push_back(x); } DFS1(rt,rt); DFS2(rt,rt); built(1, 1, n); while(m--) { cz = read(); x = read(); if(cz==1) { y = read(); z = read(); add(x,y,z); } if(cz==2) { y = read(); printf("%d\n",ask(x,y)); } if(cz==3) { z = read(); insert(1, 1, n, id[x], id[x]+siz[x]-1, z); } if(cz==4) { printf("%d\n",query(1, 1, n, id[x], id[x]+siz[x]-1)); } } return 0; }``` === LCA(ST版) ```cpp const int N=1101010; const int qwq=303030; const int inf=0x3f3f3f3f; int T; int n,m; int ans,a[N]; vector <int> e[N]; int dfn[N],tot; int dep[N]; int f[N][26],rec[N][26]; int ob[N]; void DFS(int u,int fa) { dep[u] = dep[fa] + 1; f[++tot][0] = dep[u]; rec[tot][0] = u; dfn[u] = tot; FOR() { int v = e[u][i]; if(v==fa) continue; DFS(v,u); f[++tot][0] = dep[u]; rec[tot][0] = u; } } inline int LCA(int x,int y) { if(dfn[x]>dfn[y]) swap(x,y); int l = dfn[x], r = dfn[y], k = ob[r-l+1]; if(f[l][k] < f[r-(1<<k)+1][k]) return rec[l][k]; else return rec[r-(1<<k)+1][k]; } int main() { ob[0] = -1; for(int i=1;i<=N-10;i++) ob[i] = ob[i>>1] + 1; int x,y,rt; n = read(); m = read(); rt = read(); for(int i=1;i<n;i++) { x = read(); y = read(); e[x].push_back(y); e[y].push_back(x); } DFS(rt,rt); for(int i=1;i<=tot;i++) cout<<rec[i][0]<<" "; for(int k=1;k<=22;k++) { for(int i=1;i+(1<<k-1)<=tot;i++) { if(f[i][k-1] < f[i+(1<<k-1)][k-1]) f[i][k] = f[i][k-1], rec[i][k] = rec[i][k-1]; else f[i][k] = f[i+(1<<k-1)][k-1], rec[i][k] = rec[i+(1<<k-1)][k-1]; } } while(m--) { x = read(); y = read(); cout<<LCA(x,y)<<"\n"; } return 0; } ``` === 左偏树 ```cpp #include <bits/stdc++.h> #define ll long long using namespace std; const int N=101010; const int inf=0x3f3f3f3f; int n,m; int a[N],fa[N],son[N][2]; int dep[N]; int merge(int x,int y) { if(x==0 || y==0) return x|y; if(a[x]>a[y] || (a[x]==a[y] && x>y) ) swap(x,y); son[x][1] = merge(son[x][1],y); if(dep[ son[x][0] ] < dep[ son[x][1] ]) swap(son[x][0],son[x][1]); dep[x] = dep[ son[x][1] ] + 1; return x; } int find(int x) { return fa[x]==x ? x : fa[x]=find(fa[x]); } void pop(int x) { a[x] = -1; fa[x] = merge(son[x][0],son[x][1]); fa[ fa[x] ] = fa[x]; } int main() { int cz,x,y; n = read(); m = read(); dep[0] = -1; for(int i=1;i<=n;i++) a[i] = read(), fa[i] = i; for(int i=1;i<=m;i++) { cz = read(); if(cz==1) { x = read(); y = read(); if(a[x]==-1 || a[y]==-1) continue; int xx = find(x), yy = find(y); if(xx==yy) continue; fa[xx] = fa[yy] = merge(xx,yy); // merge x tree and y tree } else { x = read(); if(a[x]==-1) printf("-1\n"); // x has been deleted else { int rt = find(x); printf("%d\n",a[rt]); // rt : the min val in x tree pop(rt); } } } return 0; }``` === 李超树(kx+b) ```cpp #include <bits/stdc++.h> #define ll long long #define ls L[now] #define rs R[now] typedef double db; using namespace std; const ll N=101010; const ll inf=0x3f3f3f3f3f3f3f3f; ll n; ll Q; struct E{ ll k,b; // kx + b ll id; }d[N],t[N*64],ling; ll L[N*64],R[N*64],tot,rt; ll max_X = 1e9; ll calc(E wo,ll x) { return wo.k*x + wo.b; } void outing(E wo) { cout<<" k="<<wo.k<<" b="<<wo.b<<" id="<<wo.id<<"\n"; } void insert(ll &now,ll l,ll r,E v) { if(!now) { now = ++tot; t[now] = ling; } ll mid = l+r >> 1, p1 = calc(t[now],mid), p2 = calc(v,mid); // cout<<"t : "; outing(t[now]); // cout<<"v : "; outing(v); // cout<<endl; if(p1<p2 || (p1==p2 && t[now].id>v.id)) swap(t[now], v); if(l==r) return ; if(t[now].k > v.k) insert(ls, l, mid, v); else insert(rs, mid+1, r, v); } E query(ll &now,ll l,ll r,ll x) { if(!now) return ling; if(l==r) return t[now]; ll mid = l+r >> 1; E res = t[now]; if(x<=mid) res = query(ls, l, mid, x); else res = query(rs, mid+1, r, x); ll ct = calc(t[now],x), cr = calc(res,x); if(ct>cr || (ct==cr && t[now].id<res.id)) return t[now]; else return res; } int main() { ll x; ling.b = -inf; n = read(); for(ll i=1;i<=n;i++) { d[i].k = read(); d[i].b = read(); d[i].id = i; insert(rt, -max_X, max_X, d[i]); } Q = read(); while(Q--) { x = read(); E res = query(rt, -max_X, max_X, x); cout<<res.id<<" "<<calc(res,x)<<"\n"; } return 0; }``` === FHQ_Treap_Segment ```cpp struct Node { ModInt Sum, val, tag; int ls, rs, key; int l, r, L, R; } t[N]; int NewNode(int l, int r, ModInt val) { static int cnt = 0; t[++cnt] = (Node){0, val, 0, 0, 0, rand(), l, r, l, r}; t[cnt].Sum = ModInt(r - l + 1) * t[cnt].val; return cnt; } void update(int id) { t[id].L = t[id].ls ? t[t[id].ls].L : t[id].l; t[id].R = t[id].rs ? t[t[id].rs].R : t[id].r; t[id].Sum = t[t[id].ls].Sum + t[t[id].rs].Sum + t[id].val * ModInt(t[id].r - t[id].l + 1); } void add(int id, ModInt val) { t[id].val += val; t[id].Sum += val * ModInt(t[id].R - t[id].L + 1); t[id].tag += val; } void pd(int id) { if (!t[id].tag) return; if (t[id].ls) add(t[id].ls, t[id].tag); if (t[id].rs) add(t[id].rs, t[id].tag); t[id].tag = 0; } int merge(int x, int y) { if (!x || !y) return x | y; if (t[x].key <= t[y].key) { pd(x); t[x].rs = merge(t[x].rs, y); return update(x), x; } else { pd(y); t[y].ls = merge(x, t[y].ls); return update(y), y; } } void split(int id, int k, bool op, int &x, int &y) { if (!id) x = y = 0; else { pd(id); if ((!op && t[id].l <= k) || (op && t[id].r <= k)) x = id, split(t[x].rs, k, op, t[x].rs, y); else y = id, split(t[y].ls, k, op, x, t[y].ls); update(id); } } int n, m, rt; void Split(int l, int r, int &x, int &y, int &z) { static int sta[N], tp = 0; x = y = z = tp = 0; split(rt, l - 1, 0, x, y); split(y, r, 1, y, z); int now = x; while (t[now].rs) sta[tp++] = now, now = t[now].rs; if (now && t[now].r > r) { y = NewNode(l, r, t[now].val); z = merge(NewNode(r + 1, t[now].r, t[now].val), z); t[now].r = l - 1; do { update(now); } while (tp && (now = sta[--tp])); } else { if (now && t[now].r >= l) { y = merge(NewNode(l, t[now].r, t[now].val), y); t[now].r = l - 1; do { update(now); } while (tp && (now = sta[--tp])); } now = z, tp = 0; while (t[now].ls) sta[tp++] = now, now = t[now].ls; if (now && t[now].l <= r) { y = merge(y, NewNode(t[now].l, r, t[now].val)); t[now].l = r + 1; do { update(now); } while (tp && (now = sta[--tp])); } } }``` === Splay(下标顺序) ```cpp #include <bits/stdc++.h> #define QWQ cout<<"QwQ"<<endl; #define ll long long #define ls son[x][0] #define rs son[x][1] using namespace std; const int N=501010; int n,a[N]; int m,rt,tot; int fa[N],son[N][2],siz[N],sum[N],val[N],rev[N]; inline void pushup(int x) { siz[x] = siz[ls] + siz[rs] + 1; sum[x] = sum[ls] + sum[rs] + val[x]; } inline void pushdown(int x) { if(rev[x]) { rev[x] = 0; rev[ls] ^= 1; rev[rs] ^= 1; swap(son[ls][0],son[ls][1]); swap(son[rs][0],son[rs][1]); } } inline bool touhou(int x) { return son[fa[x]][1]==x; } inline void rotate(int x) { int y = fa[x], z = fa[y], k = touhou(x), w = son[x][k^1]; son[z][touhou(y)] = x; son[x][k^1] = y; son[y][k] = w; fa[x] = z; fa[y] = x; fa[w] = y; pushup(y); pushup(x); } inline void splay(int x,int goal) { while(fa[x]!=goal) { int y = fa[x], z = fa[y]; if(z!=goal) { if(touhou(x)==touhou(y)) rotate(y); else rotate(x); } rotate(x); } if(!goal) rt = x; } inline int rnk(int k) { int x = rt; while(1) { pushdown(x); if(siz[ls]>=k) x = ls; else if(siz[ls]+1<k) k -= siz[ls]+1, x = rs; else return x; } } inline int Push(int v) { int x = ++tot; siz[x] = 1; val[x] = sum[x] = v; return x; } int built(int l,int r) { if(l>r) return 0; int mid = l+r >> 1, x = Push(a[mid]); if(ls=built(l,mid-1)) fa[ls] = x; if(rs=built(mid+1,r)) fa[rs] = x; pushup(x); return x; } inline void insert(int wei,int v) { //insert one num after one position int y = rnk(wei+1), z = rnk(wei+2); splay(y,0); splay(z,y); int x = Push(v); son[z][0] = x; fa[x] = z; pushup(z); pushup(y); } inline void del(int wei) { int y = rnk(wei), z = rnk(wei+2); splay(y,0); splay(z,y); int x = son[z][0]; fa[x] = son[z][0] = 0; pushup(z); pushup(y); } inline void zhuan(int L,int R) { int y = rnk(L), z = rnk(R+2); splay(y,0); splay(z,y); int x = son[z][0]; rev[x] ^= 1; swap(ls,rs); } inline int qiu(int L,int R) { int y = rnk(L), z = rnk(R+2); splay(y,0); splay(z,y); return sum[son[z][0]]; } int main() { built(0,n+1); rt = 1; return 0; }``` === Splay(大小顺序) ```cpp #include <bits/stdc++.h> #define QWQ cout<<"QwQ"<<endl; #define ll long long #define ls son[x][0] #define rs son[x][1] using namespace std; const int N=501010; const int inf=0x3f3f3f3f; int m,rt,tot; int fa[N],son[N][2],siz[N],num[N],val[N]; /* inline void access(ll x) { cnt = 0; st[++cnt] = x; while(fa[x]) st[++cnt] = (x=fa[x]); while(cnt) pushdown(st[cnt--]); } */ inline int touhou(int x) { return son[fa[x]][1]==x; } inline void pushup(int x) { siz[x] = siz[ls] + siz[rs] + num[x]; } inline void rotate(int x) { int y = fa[x], z = fa[y], k = touhou(x), w = son[x][k^1]; son[z][touhou(y)] = x; son[x][k^1] = y; son[y][k] = w; fa[w] = y; fa[y] = x; fa[x] = z; pushup(y); pushup(x); } inline void splay(int x,int goal) { // access(x);s while(fa[x]!=goal) { int y = fa[x], z = fa[y]; if(z!=goal) { if(touhou(y)==touhou(x)) rotate(y); else rotate(x); } rotate(x); } if(!goal) rt = x; } inline void insert(int v) { int x = rt, f = 0; while(val[x]!=v && x) f = x, x = son[x][val[x]<v]; if(x) num[x]++, pushup(x); else { x = ++tot; if(f) son[f][val[f]<v] = x; fa[x] = f; siz[x] = num[x] = 1; val[x] = v; } splay(x,0); } inline int rnk(int k) { int x = rt; while(1) { if(siz[ls]>=k) x = ls; else if(siz[ls]+num[x]<k) k -= siz[ls]+num[x], x = rs; else return x; } } inline void find(int v) { int x = rt; while(val[x]!=v && son[x][ val[x]<v ]) x = son[x][ val[x]<v ]; splay(x,0); } inline int qian(int v) { find(v); if(val[rt]<v) return rt; int x = son[rt][0]; while(rs) x = rs; return x; } inline int hou(int v) { find(v); if(val[rt]>v) return rt; int x = son[rt][1]; while(ls) x = ls; return x; } void del(int v) { int y = qian(v), x = hou(v); splay(y,0); splay(x,y); if(num[ls]>1) num[ls]--, siz[ls]--; else ls = 0; pushup(x); pushup(y); } inline void outing() { for(int i=0;i<=tot;i++) { cout<<i<<" : v = "<<val[i]<<" fa = "<<fa[i]<<" ls = "<<son[i][0] <<" rs = "<<son[i][1]<<" num = "<<num[i]<<" siz = "<<siz[i]<<endl; } } int main() { int cz,x; insert(inf); insert(-inf); m = read(); while(m--) { cz = read(); x = read(); if(cz==1) { insert(x); } if(cz==2) { del(x); } if(cz==3) { find(x); cout<<siz[son[rt][0]]+(val[rt]<x?num[rt]:0)<<"\n"; } if(cz==4) { cout<<val[rnk(x+1)]<<"\n"; } if(cz==5) { cout<<val[qian(x)]<<"\n"; } if(cz==6) { cout<<val[hou(x)]<<"\n"; } } return 0; }``` === 线段树分治+可撤销并查集 ```cpp #define ls now<<1 #define rs now<<1|1 using namespace std; const int N=501010; const int qwq=303030; const int inf=0x3f3f3f3f; int T; int n,m; int da; int L[N],R[N]; vector < pair<int,int> > t[N<<2]; struct CZ{ int x,y,depy,tim; }st[N]; int fa[N],tag[N],dep[N]; int cnt; int find(int x) { return x==fa[x] ? x : find(fa[x]); } void insert(int now,int l,int r,int x,int y,pair<int,int>pa) { if(x<=l && r<=y) { t[now].push_back(pa); return ; } int mid = l+r >> 1; if(x<=mid) insert(ls, l, mid, x, y, pa); if(y>mid) insert(rs, mid+1, r, x, y, pa); } void merge(int x,int y,int tim) { int xx = find(x), yy = find(y); if(xx==yy) return ; if(dep[xx] > dep[yy]) swap(xx,yy); // xx -> yy st[++cnt] = {xx, yy, dep[yy], tim}; fa[xx] = yy; if(dep[xx]==dep[yy]) dep[yy]++; tag[xx] -= tag[yy]; } void DFS(int now,int l,int r) { for(auto v : t[now]) { merge(v.first, v.second, now); } if(l==r) tag[find(1)]++; else { int mid = l+r >> 1; DFS(ls, l, mid); DFS(rs, mid+1, r); } while(st[cnt].tim==now) { CZ cz = st[cnt--]; tag[cz.x] += tag[cz.y]; fa[cz.x] = cz.x; dep[cz.y] = cz.depy; } } int main() { int x,y; n = read(); m = read(); for(int i=1;i<=n;i++) L[i] = read(), R[i] = read(), da = max(da,R[i]); for(int i=1;i<=m;i++) { x = read(); y = read(); int le = max(L[x], L[y]); int re = min(R[x], R[y]); if(le<=re) insert(1, 1, da, le, re, pair<int,int>{x,y}); } for(int i=1;i<=n;i++) fa[i] = i; DFS(1, 1, da); for(int i=1;i<=n;i++) if(tag[i]) cout<<i<<" "; return 0; }``` === MST ```cpp struct MST { const int N = 5e4 + 7; int fa[N], rk[N]; MST(int n) { for (int i = 1; i <= n; i++) fa[i] = i, rk[i] = 1; } int find(int x) { if (fa[x] == x) return x; return fa[x] = find(fa[x]); } void merge(int x, int y) { x = find(x), y = find(y); if (x == y) return; if (rk[x] < rk[y]) swap(x, y); rk[x] = max(rk[x], rk[y] + 1); fa[y] = x; } } T;``` === 主席树 ```cpp #include <bits/stdc++.h> #define ll long long #define ls L[now] #define rs R[now] const int N=1010101; int n,m; int a[N],rt[N],tot; int t[N*33], L[N*33], R[N*33]; inline void pushup(int now) { t[now] = t[ls] + t[rs]; } void built(int &now,int l,int r) { now = ++tot; if(l==r) { t[now] = a[l]; return ; } int mid = l+r >> 1; built(ls, l, mid); built(rs, mid+1, r); pushup(now); } void insert(int &now,int pre,int l,int r,int we,int g) { now = ++tot; ls = L[pre]; rs = R[pre]; if(l==r) { t[now] = g; return ; } int mid = l+r >> 1; if(we<=mid) insert(ls, L[pre], l, mid, we, g); else insert(rs, R[pre], mid+1, r, we, g); pushup(now); return ; } int query(int now,int l,int r,int x,int y) { if(x<=l && r<=y) return t[now]; int mid = l+r >> 1, res = 0; if(x<=mid) res += query(ls, l, mid, x, y); if(y>mid) res += query(rs, mid+1, r, x, y); return res; } int main() { int x,y,z,w; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&a[i]); built(rt[0],1,n); for(int i=1;i<=m;i++) { scanf("%d%d%d",&x,&y,&z); if(y==1) { scanf("%d",&w); insert(rt[i], rt[x], 1, n, z, w); } else { printf("%d\n",query(rt[x], 1, n, z, z)); rt[i] = rt[x]; } } return 0; }``` === 李超树可持久化 ```cpp #include <bits/stdc++.h> #define ll long long #define ls L[now] #define rs R[now] typedef double db; using namespace std; const ll N=101010; const ll inf=0x3f3f3f3f3f3f3f3f; ll n; ll Q; struct E{ ll k,b; // kx + b ll id; }d[N],t[N*64],ling; ll L[N*64],R[N*64],tot,rt[N]; ll max_X = 1e9; ll calc(E wo,ll x) { return wo.k*x + wo.b; } void outing(E wo) { cout<<" k="<<wo.k<<" b="<<wo.b<<" id="<<wo.id<<"\n"; } void insert(ll &now,ll pre,ll l,ll r,E v) { now = ++tot; if(!pre) {t[now] = ling; } else { t[now] = t[pre]; L[now] = L[pre]; R[now] = R[pre]; } ll mid = l+r >> 1, p1 = calc(t[now],mid), p2 = calc(v,mid); // cout<<"t : "; outing(t[now]); // cout<<"v : "; outing(v); // cout<<endl; if(p1<p2 || (p1==p2 && t[now].id>v.id)) swap(t[now], v); if(l==r) return ; if(t[now].k > v.k) insert(ls, L[pre], l, mid, v); else insert(rs, R[pre], mid+1, r, v); } E query(ll &now,ll l,ll r,ll x) { if(!now) return ling; if(l==r) return t[now]; ll mid = l+r >> 1; E res = t[now]; if(x<=mid) res = query(ls, l, mid, x); else res = query(rs, mid+1, r, x); ll ct = calc(t[now],x), cr = calc(res,x); if(ct>cr || (ct==cr && t[now].id<res.id)) return t[now]; else return res; } int main() { ll r,x; ling.b = -inf; n = read(); for(ll i=1;i<=n;i++) { d[i].k = read(); d[i].b = read(); d[i].id = i; insert(rt[i], rt[i-1], -max_X, max_X, d[i]); } Q = read(); while(Q--) { r = read(); x = read(); E res = query(rt[r], -max_X, max_X, x); cout<<res.id<<" "<<calc(res,x)<<"\n"; } return 0; } ``` === ST表 ```cpp const int N=2020200; const int qwq=303030; const int inf=0x3f3f3f3f; int n,Q; int a[N]; int ob[N],ma[N][22]; int ask(int l,int r) { int k = ob[r-l+1]; return max(ma[l][k], ma[r-(1<<k)+1][k]); } void built() { ob[0] = -1; for (int i=1;i<=N-10;i++) ob[i] = ob[i>>1] + 1; for (int k=1;k<=21;k++) for (int i=1;i+(1<<(k-1))<=n;i++) ma[i][k] = max(ma[i][k-1], ma[i+(1<<(k-1))][k-1]); } int main() { int x,y; n = read(); Q = read(); for(int i=1;i<=n;i++) a[i] = read(), ma[i][0] = a[i]; built(); while(Q--) { x = read(); y = read(); cout<<ask(x,y)<<"\n"; } return 0; }``` === DSU ```cpp void JI(int u) { nowans += f[u]; FOR() JI(e[u][i]); } void JIA(int u,int cl) { f[u] += cl; FOR() JIA(e[u][i],cl); } void DSU(int u,bool shan) { FOR() { int v = e[u][i]; if(v==son[u]) continue; DSU(v,1); } if(son[u]) DSU(son[u],0); for(int i=0;i<le;i++) { int v = e[u][i]; if(v==son[u]) continue; JI(v); JIA(v,1); } if(shan) JIA(u,-1); }``` === FHQ_Treap ```cpp #include <iostream> #include <cstdlib> #include <algorithm> #include <vector> #include <stack> using namespace std; const int N = 5e5 + 7; struct FHQ_TREAP { struct Node { int ls, rs, key, sz, val; Node(int l_ = 0, int r_ = 0, int key_ = 0, int sz_ = 0, int val_ = 0) : ls(l_), rs(r_), key(key_), sz(sz_), val(val_) { if (!key) key = rand() + 1; } }; vector<Node> t; stack<int> pool; int nd_cnt, rt, x, y, z; FHQ_TREAP() { srand(114514); t.push_back(Node()); rt = nd_cnt = 0; } int node(int x) { Node tmp(0, 0, 0, 1, x); if (!pool.empty()) { int id = pool.top(); pool.pop(); t[id] = tmp; return id; } else { t.push_back(tmp); return ++nd_cnt; } } void update(int id) { t[id].sz = 1 + t[t[id].ls].sz + t[t[id].rs].sz; } int merge(int x, int y) { if (!x || !y) return x + y; if (t[x].key < t[y].key) { t[x].rs = merge(t[x].rs, y); update(x); return x; } else { t[y].ls = merge(x, t[y].ls); update(y); return y; } } void split(int id, int k, int &x, int &y) { if (!id) x = y = 0; else { if (t[id].val <= k) x = id, split(t[id].rs, k, t[id].rs, y); else y = id, split(t[id].ls, k, x, t[id].ls); update(id); } } void Insert(int val) { z = node(val); split(rt, val - 1, x, y); rt = merge(x, merge(z, y)); } void Delete(int val) { split(rt, val - 1, x, y); split(y, val, y, z); pool.push(y); y = merge(t[y].ls, t[y].rs); rt = merge(merge(x, y), z); } int get_rank(int val) { split(rt, val - 1, x, y); int tmp = t[x].sz + 1; rt = merge(x, y); return tmp; } int get_kth(int rk) { int id = rt; while (1) { if (rk <= t[t[id].ls].sz) id = t[id].ls; else if (rk == t[t[id].ls].sz + 1) return t[id].val; else { rk -= (t[t[id].ls].sz + 1); id = t[id].rs; } } } int get_pre(int val) { split(rt, val - 1, x, y); int id = x; while (t[id].rs) id = t[id].rs; rt = merge(x, y); return t[id].val; } int get_suc(int val) { split(rt, val, x, y); int id = y; while (t[id].ls) id = t[id].ls; rt = merge(x, y); return t[id].val; } } T;```
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%2018_155%20-%20Differential%20Analysis%201/Assignments/Assignment%201.typ
typst
#import "/Templates/generic.typ": latex, header #import "@preview/ctheorems:1.1.0": * #import "/Templates/math.typ": * #import "/Templates/assignment.typ": * #show: doc => header(title: "Assignment 1", name: "<NAME>", doc) #show: latex #show: NumberingAfter #show: thmrules #let col(x, clr) = text(fill: clr)[$#x$] #let pb() = { pagebreak(weak: true) } #set page(numbering: "1") #let bar(el) = $overline(#el)$ *Sources consulted* \ Classmates: <NAME>, <NAME>. \ Texts: Class Notes, Evan's PDEs. = Question == Statement Consider the Green functions, for $n = 2$ we have $ G_y (x) = - 1 / (2 pi) ln norm(x - y) quad x,y in RR^2, $ and for $n >= 3$ we have $ G_y (x) = norm(x-y)^(2-n) / ((n-2)abs(S^(n-1))) quad x,y in RR^n. $ Prove that $integral_(RR^n) Delta f dot G_0 = - f(0)$ for any $f in C_c^infinity (RR^n)$. As well as $ u(x) = integral G_y (x) f(y) d y $ satisfies $Delta u = - f$. == Solution We will use the outline given in the question #proposition[ If $u in C^2(ov(Omega))$ and $Delta u = 0$ then $integral_(diff Omega) arrow(nu) dot nabla u = 0$. ] #proof[ Set $v = 1$ in Green's formula, this gives us $ integral_Omega Delta u dot 1 - u dot 0 &= integral_(diff Omega) (arrow(nu) dot nabla u) dot 1 - u (arrow(nu) dot 0) \ 0 &= integral_(diff Omega) (arrow(nu) dot nabla u) $ ] #proposition[ $G_0 (x)$ is harmonic in $RR^n backslash {0}$ and $integral_(diff B_1(0)) (arrow(nu) dot nabla G_0) = -1$ ] #proof[ First check $n = 2$, take any $x != 0$ and after throwing away constants compute $ nabla (ln norm(x)) = (nabla norm(x)) / norm(x) = (x) / norm(x)^2. $ Next we calculate the divergence, $ div(x/norm(x)^2) = div(x) / norm(x)^2 + x dot nabla (1 / norm(x)^2) = 2 / r^2 + r diff_r (1 / r^2) = 2 / r^2 - 2 / r^2 = 0. $ Next we check for $n = 3$, we can ignore the constants so we compute $ nabla norm(x)^(2-n) = (2-n) norm(x)^(1-n) nabla norm(x) = (2-n) norm(x)^(1-n) (x / norm(x)) = (2-n) x norm(x)^(-n). $ Next, after again throwing away constants, $ div(x norm(x)^(-n)) = div(x) norm(x)^(-n) + x dot nabla norm(x)^(-n) = n r^(-n) + r diff_r (r^(-n)) = n r^(-n) - n r^(-n) = 0. $ Finally, we compute for $n = 2$ $ integral_(partial B_1(0)) arrow(n) dot nabla G_0 = - integral_(partial B_1(0)) arrow(n) dot x / (2pi norm(x)^2) = - integral_(partial B_1(0)) 1 / (2pi) = -1, $ where we used the fact that $2pi$ is the perimeter of the circle. For $n = 3$ we have $ integral_(partial B_1(0)) arrow(n) dot nabla G_0 &= - integral_(partial B_1(0)) arrow(n) dot ((2-n) x) / (( n-2 ) abs(S^(n-1)) norm(x)^n) = - integral_(partial B_1(0)) arrow(n) dot x / (abs(S^(n-1)) norm(x)^n) \ &= - integral_(partial B_1(0)) 1 / (abs(S^(n-1))) = -1. $ ] #proposition[ We have $ lim_(epsilon -> 0) integral_(partial B_epsilon (0)) (arrow(nu) dot nabla G_0) f = f(0) wide "as well as" wide lim_(epsilon -> 0) integral_(partial B_epsilon (0)) ( arrow(nu) dot nabla f ) G_0 = 0 $ ] #proof[ We first simplify $ integral_(partial B_epsilon (0)) (arrow(nu) dot nabla G_0)(x) f(x) d S &= - integral_(partial B_epsilon (0)) (arrow(nu) dot x / (abs(S^(n-1)) norm(x)^(n))) f(x) d S \ &= - 1 / (abs(S^(n-1)) epsilon^(n-1))integral_(partial B_epsilon (0)) f(x) d S. $ Now we do a change of variables $ - 1 / (abs(S^(n-1)) epsilon^(n-1)) integral_(partial B_epsilon (0)) f(x) d S &= - 1 / (abs(S^(n-1)) epsilon^(n-1)) integral_(partial B_1 (0)) f(epsilon x) epsilon^(n-1) d S \ &= - 1 / (abs(S^(n-1))) integral_(partial B_1 (0)) f(epsilon x) d S $ now as $epsilon -> 0$, $f(epsilon x) -> f(0)$ and it becomes dominated by $1 + |f(0)|$ so we can use dominated convergence theorem to get $ lim_(epsilon -> 0) (-1) / (abs(S^(n-1))) integral_(partial B_1 (0)) f(epsilon x) d S = (- 1) / (abs(S^(n-1))) integral_(partial B_1 (0)) f(0) d S = - f(0). $ Now we need to do a quick limit calculation $ abs(G_0(x)) norm(x)^(n-1) = cases(r abs(ln r) : n = 2, r : n >= 3) $ in either case we have $lim_(x -> 0) abs(G_0(x))norm(x)^(n-1) = 0$. $ abs(integral_(partial B_epsilon (0)) (arrow(nu) dot nabla f)(x) G_0(x) d S ) &<= integral_(partial B_epsilon (0)) norm(nabla f)_(C^0(RR^n)) abs(G_0(x)) d S \ &= norm(nabla f)_(C^0(RR^n)) abs(G_0(epsilon)) epsilon^(n-1) abs(S^(n-1)) $ where in the final step we used that $G_0$ is always radial. This then gives us that $ lim_(epsilon -> 0) abs(integral_(partial B_epsilon (0)) (arrow(nu) dot nabla f)(x) G_0(x) d S) <= C lim_(epsilon -> 0) abs(G_0(epsilon)) epsilon^(n-1) =0 $ ] #proposition[ We have $ integral_(RR^n) Delta f dot G_0 = - f(0) $ ] #proof[ Let $K$ be a large compact set containing the origin which also contains the support of $f$. We will compute this integral by computing it on $K backslash partial B_epsilon (0)$, the compliment of a radius $epsilon$ ball, and then letting $epsilon -> 0$, this is a valid limit since $G_0$ is locally integrable and thus some multiple of it dominates $Delta f dot G_0 dot bb(1)_(K backslash B_epsilon (0))$. To that end we compute $ integral_(K backslash B_epsilon (0)) Delta f dot G_0 &= integral_(K backslash B_epsilon (0)) f Delta G_0 + integral_(diff B_epsilon (0)) (-arrow(nu) dot nabla f) G_0 - (-arrow(nu) dot nabla G_0) f \ &= 0 + integral_(diff B_epsilon (0)) (-arrow(nu) dot nabla f) G_0 - (-arrow(nu) dot nabla G_0) f \ &= integral_(diff B_epsilon (0)) (arrow(nu) dot nabla G_0) f - (arrow(nu) dot nabla f) G_0. $ Note that we did not need to worry about the outer boundary of $K$ because $f,nabla f, Delta f$ all vanish there, also we had to put an extra negative sign for our normal vectors since they are the outer normal vector from $K backslash B_epsilon (0)$ is oriented opposite from how it was oriented previously. We thus get by the previous proposition $ lim_(epsilon -> 0) integral_(K backslash B_epsilon (0)) Delta f dot G_0 = lim_(epsilon -> 0) integral_(diff B_epsilon (0)) (arrow(nu) dot nabla G_0) f - (arrow(nu) dot nabla f) G_0 = -f(0) $ ] #proposition[ For any $f in C^infinity_c (RR^n)$ we have that $ u(x) := integral_(RR^n) norm(x-y)^(2-n) f(y) d y = integral_(RR^n) norm(y)^(2-n) f(x-y) d y $ satisfies $Delta u(x) = c_n dot f(x)$ for some numerical $C_n$. ] #proof[ We use the second form to compute $ Delta u(x) = integral_(RR^n) norm(y)^(2-n) Delta f(x-y) d y = integral_(RR^n) (n-2) abs(S^(n-1)) G_0 (y) Delta f(x-y) d y, $ then since $G_0$ is symmetric we can replace $y$ by $-y$ and then the previous proposition gives us $ (n-2) abs(S^(n-1)) integral_(RR^n) G_0 (y) Delta f(x+y) d y = - (n-2) abs(S^(n-1)) f(x) $ so the result holds with $C_n = - (n-2) abs(S^(n-1))$. ] = Question == Statement Define the functional $u$ as $ pair(u, f) = sum 1 / n (f(1 / n) - f(0)). $ Prove that it is a distribution of order 1 and find its support. Show that there does not exist a $C > 0$ such that for any $f in C_c^infinity$ we have $ abs(pair(u,f)) <= max_(supp u) (abs(f(x)) + abs(f'(x))). $ == Solution First let's show that it is indeed a distribution of order $1$, let $f$ be a test function, we can use mean value theorem to get a sequence of points $c_n$ such that $ abs(sum_n 1/n (f(1/n) - f(0))) &= sum_n 1 / n (abs(f(1/n) - f(0)) / (1 / n - 0) 1 / n) \ &= sum_n 1 / n^2 abs(f'(c_n)) <= sum_n 1 / n^2 norm(f)_(C^1[0,1]) = pi^2 / 6 norm(f)_(C^1[0,1]) $ Now let us find the support of $u$. Set $K = {0} union {1/n : n in NN}$, then for any function $f$ supported on $RR backslash K$, then by definition $f(0) = f(1/n) = 0$ for all $n$ so $pair(u,f) = 0$. This proves that $RR backslash K seq supp u$. On the other hand fix some $n$ and consider a bump function $phi_n$ which is $1$ at $1/n$ and is supported within $[1/(n+0.5), 1/(n-0.5)]$, it is clear that this function has $pair(u,phi_n) = 1/n$ so all of the points $1/n$ are in the support. Since the support is closed their limit is also in the support hence $K$ is exactly the support of $u$. Finally we will construct a sequence of functions $f_n$ with $ max_(supp u) (abs(f_n (x)) + abs(f_n' (x))) = 1 $ for all $n$ but which will satisfy $ pair(u, f_n) -> infinity, $ as $n -> infinity$, this will prove the last part of the question. We will define $f_n$ to be a bump function which is equal to $1$ on $[1/n, 1]$ and is supported on $[1/(n+0.5), 2]$. We clearly have $f'_m (1/n) = 0$ for all $n$, and also $f'_m (0) = 0$. We hence have $ max_(supp u) (abs(f_n (x)) + abs(f_n' (x))) = 1. $ But we have $ pair(u, f_n) = sum_(k=1) 1 / k (f_n (1 / k) - f(0)) = sum_(k=1)^n 1 / k ( 1 - 0 ) = sum_(k=1)^n 1 / k -> infinity $ = Question == Statement Let $a_k$ be a sequence with polynomial growth, in the sense that $|a_k| <= C k^N$ for some $C$ and $N$. Show that $sum_(k=1)^infinity a_k e^(i k x)$ converges in the sense of distributions. == Solution It is enough to prove that $ lim_(M -> infinity) integral_(RR) sum_(k=1)^M a_k e^(i k x) f(x) $ exists for any $f in C_c^infinity (RR)$, first we will need a lemma given in the question. #lemma[ $ integral e^(i k x) f = - 1 / (i k) integral e^(i k x) f' $ ] Now consider the expression $ integral_(RR) sum_(k=1)^M a_k e^(i k x) f(x). $ If we iterate the lemma above $N + 2$ times we get $ integral_(RR) sum_(k=1)^M a_k e^(i k x) f(x) = integral_RR sum_(k=1)^M i^(N+2) / (k^(N+2)) a_k e^(i k x) f^((n+2))(x) $ so since $|a_k| <= C k^N$ we get $ abs(integral_RR sum_(k=1)^M i^(N+2)/(k^(N+2)) a_k e^(i k x) f^((n+2))(x)) &<= sum_(k=1)^M abs(i^(N+2)/(k^(N+2)) a_k) integral_RR abs(e^(i k x) f^((n+2))(x)) \ &<= sum_(k=1)^M C / (k^2) integral_RR abs(f^((n+2))(x)) <= pi^2 / 6 norm(f)_(C^(n+2) ( RR )) $ Now it is well known that if the absolute value of a series converges then the series itself also converges, so we have proven that $ sum_(k=1)^infinity a_k e^(i k x) $ converges in the sense of distributions. = Question == Statement The principal value functional is defined by $ pair(u,f) := lim_(epsilon -> 0) integral_(abs(x) > epsilon) f(x) / x d x, $ for all $f in C_c^infinity (RR)$. It is often denoted by $P. V. integral f(x)/x d x$. Show that $pair(u,f)$ exists and defines a distribution. == Solution Let us first manipulate the integral into a nicer form using change of variables. $ integral_(abs(x) > epsilon) f(x) / x d x &= integral_(-infinity)^(-epsilon) f(x) / x d x + integral_(epsilon)^(infinity) f(x) / x d x \ &= integral_(infinity)^(epsilon) f(-u) / (-u) (-d u) + integral_(epsilon)^(infinity) f(x) / x d x \ &= - integral_(epsilon)^(infinity) f(-u) / u d u + integral_(epsilon)^(infinity) f(x) / x d x \ &= integral_(epsilon)^(infinity) (f(x) - f(-x)) / x d x \ &= integral_(epsilon)^(1) (f(x) - f(-x)) / x d x + integral_(1)^(infinity) (f(x) - f(-x)) / x d x $ Now that the integral is in this form we can bound it using the differentiability of $f$ for the first integral and its compact support on the right term. Let $K$ be a compact set containing $supp f$ and compute $ integral_(epsilon)^(1) abs(f(x) - f(-x)) / x d x + integral_(1)^(infinity) abs(f(x) - f(-x)) / x d x & <= integral_(epsilon)^(1) 2 norm(f')_(C^0 (RR)) d x + integral_(1)^(infinity) 2 abs(f(x)) d x \ &<= 2 norm(f')_(C^0 (RR)) + 2 abs(K) norm(f)_(C^0 (RR)) \ &<= 2 norm(f)_(C^1 (RR)) + 2 abs(K) norm(f)_(C^1 (RR)) \ &<= (2 + 2 abs(K)) norm(f)_(C^1 (RR)) $ Thus up to a constant $C(K)$ depending on the support, we get $pair(u, f) <= C(K) norm(f)_(C^1(RR))$. = Question == Statement Consider the space $(C^k [0,1])'$ of bounded linear functionals on $C^k [0,1]$. Show that it can be identified with a set of functionals $pair(u,f) = sum_(j=1)^k integral_0^1 diff^j f d mu_j$ where each $mu_j$ is some finite Borel measure on $[0,1]$. == Solution Let us define the vector space $V := (C[0,1])^(k+1)$ and identify $C^k [0,1]$ with the subspace $S seq V$ through $ f tilde (f,f',f'',...,f^((k))). $ With this identification we can consider any element $u in (C^k [0,1])'$ as a linear functional on $S$. Now we define the norm on $V$ by $ norm((f_0,f_1,...,f_k)) = sum_(j=1)^k max abs(f_0). $ One can easily check that this is indeed a norm and if we restrict to to $S$, it coincides with the norm on $C^k [0,1]$. Thus we know that $u$, as a functional on $S$, is dominated by $norm(dot)$, so by the Hahn-Banach Theorem we can extend $u$ to a full functional on all of $V$, denoted $ov(u)$. Now $ov(u)$ is a linear functional over a direct sum of vector spaces, and can thus be decomposed into its components as $ov(u) = ov(u)_0 + ov(u)_1 + ... + ov(u)_k$. For each component we have $ov(u)_i : C[0,1] -> RR$ so by the Riesz-Markov-Kokutoni Theorem it can be written as $ pair(ov(u)_i, f) = integral_0^1 f d mu_i $ where $mu_i$ is some (possibly negative) finite Borel measure on $[0,1]$. Thus we get $ pair(ov(u), (f_0,f_1,...,f_k)) = sum_(i=1)^k integral_0^1 f_i mu_i. $ Restricting $ov(u)$ to $S$ then gives us exactly the required result since $f_i$ becomes $f^((i))$. = Question == Statement Given a function $f$ on a compact set $K seq RR^n$, satisfying the Lipschitz condition with constant $L$, can we find a Lipschitz extension of $f$ onto the whole $RR^n$. You are allowed to use the following lemma (I slightly modified the lemma to make it solvable). #lemma[ Given an open set $Omega seq RR^n$ there exists a collection of balls $B_i$, a collection of smooth compactly supported functions $phi_i$ and a constant $C_n$ such that + For each point $x in Omega$, $1 <= \# {B_i : x in B_i } <= C_n$. + $2 B_i seq Omega$ and $4 B_i sect diff Omega != nothing$ for all $i$. + $supp phi_i seq B_i$ for all $i$. + $sum_i phi_i = 1$ on $Omega$. + $norm(phi_i)_(Lip (RR^n)) <= C_n$ for all $i$. ] == Solution Using this lemma we can construct a Lipschitz extension, first we apply the lemma to $K^c$. Now for each ball $B_i$, we identify its center $c_i$ as well as the point $s_i$ of $K$ closest to it, which always exists because $K$ is compact. We now define $ tilde(f)(x) = cases(sum_i f(s_i) phi_i (x) : x in K^c, f(x) : x in K) $ This is well defined because at any point only finitely many of the $phi_i (x)$ are non-zero by property 1 of the lemma. Now we check that $tilde(f)$ is Lipschitz, this is immediate for $x,y in K$ so assume that $x in K$ and $y in K^c$. We now compute $ abs(tilde(f)(x) - tilde(f)(y)) &= abs(f(x) - sum_(i) f(s_i) phi_i (y)) = abs(sum_(i) phi_i (y) (f(x) - f(s_i))) \ &<= sum_i phi_i (y) abs(f(x) - f(s_i)) <= sum_i phi_i (y) norm(f)_(Lip (K)) norm(x-s_i) $ Now we just need to estimate $norm(x - s_i)$, we first use triangle inequality to get $ norm(x - s_i) <= norm(x - y) + norm(y - s_i) <= norm(x - y) + 2r_i $ where $r_i$ is the radius of $B_i$. Now assuming $phi_i (y)$ is non-zero then we know that $y in B_i$, and yet since $2 B_i seq K^c$ we know that $ 2 r_i <= norm(y - c_i) <= norm(y - x) + norm(x - c_i) <= norm(y - x) + r_i $ so we get $r_i <= norm(y-x)$. We thus get $ norm(x-s_i) <= 3norm(x-y). $ Plugging this back into our original sum we have $ abs(tilde(f)(x) - tilde(f)(y)) <= sum_i phi_i (y) norm(f)_(Lip (K)) 3norm(x-y) = 3 norm(x-y) norm(f)_(Lip (K)) $ thus we get $ abs(tilde(f)(x) - tilde(f)(y)) / (norm(x-y)) <= 3 norm(f)_(Lip (K)) $ Now we check for $x,y in K^c$, if that is the case then $ abs(tilde(f)(x) - tilde(f)(y)) = abs(sum_(i) phi_i (x) f(s_i) - sum_i phi_i (y) f(s_i)) $ Now let $A$ be the collection of $i$ for which either $phi_i (x)$ or $phi_i (y)$ is non-zero, then note that since we can add any constant to $f$ without changing the Lipschitz constant we can replace $f(x)$ with $f(x) - f(z)$ for any arbitrary $z in K$. We then write $ abs(sum_(i in A) phi_i (x) (f(s_i) - f(z)) - sum_(i in A) phi_i (x) (f(s_i) - f(z))) \ <= sum_(i in A) abs(phi_i (x) - phi_i (y)) abs(f(s_i) - f(z)) \ <= sum_(i in A) C_n norm(x - y) norm(f)_(Lip (K)) diam (K) $ where we used the fact that $phi$'s have Lipschitz constant at most $C_n$. Now $A$ has cardinality at most $2 C_n$ again by the lemma so we get $ abs(tilde(f)(x) - tilde(f)(y)) / norm(x-y) <= 2 C_n^2 norm(f)_(Lip (K)) diam (K) $ Combining these all together we get $ norm(tilde(f))_(Lip (RR^n)) <= (3 + 2 C_n^2 diam(K)) norm(f)_(Lip (K)) $
https://github.com/ammar-ahmed22/typst-resume
https://raw.githubusercontent.com/ammar-ahmed22/typst-resume/main/src/main.typ
typst
#import "./utils/resume.typ": resume #let data = yaml("./data.yml") #resume( data, accentColor: rgb("#764BA2") // accentColor: rgb("#9554C8") )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-text_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Sanity check that the direction works on text. #set page(width: 200pt, height: auto, margin: 10pt, background: { rect(height: 100%, width: 30pt, fill: gradient.linear(dir: btt, red, blue)) }) #set par(justify: true) #set text(fill: gradient.linear(dir: btt, red, blue)) #lorem(30)
https://github.com/crd2333/Astro_typst_notebook
https://raw.githubusercontent.com/crd2333/Astro_typst_notebook/main/src/docs/here/test/3.typ
typst
Pay attention to the order. Files with order frontmatter will be shown first, then those without orders will be shown in the order of reading.
https://github.com/FkHiroki/ex-B3
https://raw.githubusercontent.com/FkHiroki/ex-B3/main/sections/section3.typ
typst
MIT No Attribution
= 4. 考察 == 4.1. Pbではなく、Pb-Inを用いた理由 本実験では、Pbではなく、Pb-Inを用いた。Pb-Inを用いた理由は、Pbは超伝導転移温度が$7.2 "K "$(実験動画を参照)であるが、その時の抵抗率が非常に小さく、今回の実験系では測ることが難しいからではないかと考えられる。まず、$7.2 "K "$におけるPbの抵抗率を求めてみる。参考文献@Pb_resist_ratio より、Pbの温度に対する抵抗率の関係は、以下の@tab:Pb_resist_ratio で表される。またこれをグラフにプロットし、線形近似した結果を@fig:Pb_resist_ratio に示す。 #figure( caption: [Pbの温度に対する抵抗率の関係], table( columns: 4, stroke: (none), table.hline(), table.header( [], [$78$ K], [$273$ K], [$373$ K] ), table.hline(), [抵抗率 /$ohm$ $dot$ m], [$4.70 times 10^(-8)$], [$1.92 times 10^(-7)$], [$2.70 times 10^(-7)$], table.hline(), ) ) <tab:Pb_resist_ratio> #figure( image("../figs/pb_rho_theo.png", width: 90%), caption: [Pbの温度に対する抵抗率の関係], ) <fig:Pb_resist_ratio> しかし、@fig:Pb_resist_ratio から、線形回帰の結果、$7.2 "K "$におけるPbの抵抗率は$0$を下回るため、実際の抵抗率の値をここから算出するのは難しい。次に、今回の電圧測定装置は、µVオーダーの電圧を測定することができた。そのため、電圧値が$1$µV変化した時、抵抗率がどの程度変化するかを考える。@tab:pb-in での寸法値を用いると、 $ 0.001 / 100 * (0.1 * 2.40 ) / 1.50 * 0.001 = 1.6 times 10^(-9) space ohm dot "m " $ となる。これらを基に推測すると、Pbの$7.2 "K "$における抵抗率は、$1.6 times 10^(-9) space ohm dot "m "$程度、もしくはそれよりも小さい値なため、超伝導転移をする前とした後の抵抗率の変化を測定することが難しいと考えられる。それに対しInは、抵抗率の変化の傾きがPbに比べて小さく、超伝導転移温度でもある程度大きい抵抗率を示すと考えられるため、それをPbに添加することで、超伝導転移温度の測定を容易にすることができると考えられる。 == 4.2. PbとInの組成比 Pbの超伝導転移温度が$7.2 "K "$であるのに対し、Inの超伝導転移温度は$3.41 "K "$である。@tab:resistance より、$7.1 "K "$で、Pb-Inの抵抗率の急激な現象が確認できる。よって、これを基に以下の式で抵抗率を求めてみる。 $ cases( x + y = 1, 7.2 x + 3.41 y = 7.1 ) $ これを解くと、$x = 0.974, y = 0.026$となった。ただ、$2.6 %$程度のInの添加によって、4.1で考察したように、Pbの抵抗率が変化するのかどうか疑問である。しかし、超伝導転移温度付近のInの抵抗率の具体的な値を得ることができなかったため、ここでは、この先の議論を保留する。 == 4.3. Pb-InとYBCOの残留抵抗率 @tab:resistance からPB-InとYBCOの残留抵抗率を求めた。Pb-Inは、$8.4 ~ 78.7 "K "$、YBCOでは、$55.5 ~ 177.6 "K "$で、残留抵抗率を求めた。その結果を@fig:Pb-In_resist_ratio 、@fig:YBCO_resist_ratio に示す。 #figure( image("../figs/pbin_leave_rho.png", width: 90%), caption: [Pb-Inの残留抵抗率], ) <fig:Pb-In_resist_ratio> #figure( image("../figs/ybco_leave_rho.png", width: 90%), caption: [YBCOの残留抵抗率], ) <fig:YBCO_resist_ratio> == 4.4. Pb-InとYBCOの電気抵抗率比とそれらの純度 @fig:Pb-In_resist_ratio 、@fig:YBCO_resist_ratio から、Pb-InとYBCOの残留抵抗率を求めた。次に、室温でのPb-In、YBCOの抵抗率を残留抵抗率で割ることで、それぞれの電気抵抗率比を求めた。その結果を@tab:resist_ratio に示す。 #figure( caption: [Pb-InとYBCOの残留抵抗率], table( columns: 3, stroke: (none), table.hline(), table.header( [], [Pb-In], [YBCO] ), table.hline(), [室温での抵抗率 /$ohm$ $dot$ m], [$3.22 times 10^(-7)$], [$1.91 times 10^(-5)$], [残留抵抗率 /$ohm$ $dot$ m], [$2.31 times 10^(-7)$], [$1.79 times 10^(-5)$], [電気抵抗率比], [$1.39$], [$1.07$], table.hline(), ) ) <tab:resist_ratio> この抵抗率比は純度の指標になる。参考@rho-T-ratio によると、「温度を下げると、金属の抵抗がぐんぐん下がるのに対して、絶縁体の抵抗は 発散的に増大する。」ということがわかっているようだ。つまり、純度が高ければ、金属的な性質により、残留抵抗率が小さくなり、抵抗率比が大きくなると考えられる。そのため、Pb-InはYBCOの2つを比較すると、Pb-Inの方が純度が高いと考えられる。しかし、今回は室温での測定と室温以外での測定で実験環境が違うので、@fig:Pb-In_resist_ratio 、@fig:YBCO_resist_ratio から、室温($298$ K)でのPb-In、YBCOの抵抗率を残留抵抗率で割ることで、それぞれの電気抵抗率比を求めた。その結果を@tab:resist_ratio_2 に示す。 #figure( caption: [Pb-InとYBCOの残留抵抗率], table( columns: 3, stroke: (none), table.hline(), table.header( [], [Pb-In], [YBCO] ), table.hline(), [室温での抵抗率 /$ohm$ $dot$ m], [$4.035 times 10^(-7)$], [$4.855 times 10^(-5)$], [残留抵抗率 /$ohm$ $dot$ m], [$2.31 times 10^(-7)$], [$1.79 times 10^(-5)$], [電気抵抗率比], [$1.75$], [$2.71$], table.hline(), ) ) <tab:resist_ratio_2> この結果だと、YBCOの方が純度が高いと考えられる。 == 4.5. 零磁場冷却での磁石とYBCOの距離に対する磁石にかかる力の関係 @fig:zero_field から、零磁場冷却での磁石とYBCOの距離に対する磁石にかかる力の関係を示した。まず、グラフの形状についてだが、これは、クーロンの法則より、磁極間に働く力が距離の2乗に反比例するためである。そして、経路によって、磁石にかかる力が変化することについてはYBCOのピン止め効果が原因であると考えられる。最初、YBCOを近づける時は、ある一定の距離までは、マイスナー効果によって、磁石とは逆向きに磁化する。しかし、ある一定の距離になると磁石の磁場が強いことから、YBCO内に磁束が侵入する。その侵入した磁束がピン止め効果によりその場に留まることで、さらなる時速の侵入を防ぎ、結果的に磁石の磁場と反対向きに磁化した状態を保てる。しかし、一部はピン止め効果の影響により、侵入した磁束線の向きに磁化するため、磁石に引き寄せられる力がその部分に対し働く。そのため、YBCOを遠ざける向きの時は、初めに近づける向きにはなかった引力を受けるために磁石が感じる斥力が小さくなり、グラフのように力が小さくなったと考えられる。そして、再び近づける向きにすると、遠ざける向きの時よりは閉じ込めていた磁束が解放されるが一部残留した磁束によって引力を感じるため、遠ざける向きの時よりも力が大きくなり、1回目の近づける向きの時よりは力が小さくなると考えられる。 次に、磁場中冷却の時のグラフ@fig:magnetic_field のグラフの形について考える。まず、磁場中冷却の際は、本来は零磁場の時と同様に外部の磁場に対し逆向きに磁化するが、ピン止め効果によって、冷却前に通過して磁束が閉じ込められる。よって、零磁場冷却の時のグラフのような斥力に加えて磁石には距離に反比例する引力が働く。そのため、グラフは引力と斥力を重ね合わせたような形になっていることがわかる。また経路による力の違いについては、最初の遠ざける向きの時は、ピン止め効果による引力が強く影響し、力が負の向きに大きくなる。そして、近づける向きの時は、ピン止めされた磁束の一部が解放されるため、引力の影響が小さくなる。そして、再び遠ざける向きにすると、再び磁束が侵入し、ピン止めされるため、近づける向きの時よりも力が大きくなるが、冷却の時ほど時速は侵入しないと考えられるため、1回目の遠ざける向きの時よりは小さくなると考えられる。 == 4.6. 磁場上での超伝導体の運動 まず、零磁場冷却したYBCOをレール上に置いた時の運動について考察する。零磁場冷却されたYBCOはマイスナー効果によって物体内部で磁束が存在しないようになり、外部の磁場に対し逆向きの磁化を得る。レールの磁石がN-S-Nの時、真ん中にS極からの磁束の影響が最も強いため、YBCOの下面はS極に磁化される。そうすると、真ん中のS極からは斥力、端のN極からは引力を受ける。また、ピン止め効果の影響も受けると考えられる。S極の磁束が一部侵入し、YBCOの端の方でピン留めされるとその部分だけ下面がN極になる。その結果、YBCOはレール乗を浮くことができ、斥力が推進力となり、YBCOが押された時に動くことができる。また、レールの端のN極がYBCOの中央下面のS極を引っ張りあうことで、ある程度の速さで運動する場合はレール上にとどまることができると考えられる。そして、遠心力がN極の引力より大きくなる、つまりある程度の速さで運動すると、 YBCOはレールから逸れると考えられる。 次にレール上で冷却されたYBCOがその場にとどまり浮かばないのは、@fig:magnetic_field の時とは違い、磁石と接している状態で冷却されたため、YBCOの下面は磁石の磁束線と同じ向きに磁化される。そのたね、このような挙動を見せる。そして、レールの向きを反転させると、YBCOは重力によりレールと距離ができ、その後、@fig:magnetic_field の時と同様の条件になるため、ある一定の距離になったところで、引力が最大値になり、その最大値が重力と釣り合うことで、YBCOが浮き、レール乗を動くことができるのだと考えられる。また、いずれYBCOが落ちてしまうこともピン止め効果によって閉じ込められていた磁束が徐々に解放されることによって引力が減少すると考えると説明がつく。 = 結論 本実験では、Pb-InとYBCOを超伝導体として用いることでゼロ抵抗とマイスナー効果を実際に確認した。Pbではなく、Pb-Inを用いることで、超伝導転移温度の測定を測定を容易にした。また、Pb-InとYBCOの残留抵抗率を求め、電気抵抗率比を求めたことで、Pb-Inの方が純度が高いと考えたが、実験環境の違いを考慮して室温での抵抗率を計算し、電気抵抗率比を求め直してみると、YBCOの方が純度が高いとわかった。そして、零磁場冷却での磁石とYBCOの距離に対する磁石にかかる力の関係を調べ、YBCOのピン止め効果により、経路によって力のかかり方に違いが生じることがわかった。このピン止め効果によってレール上でのYBCOの運動が説明できることがわかった。
https://github.com/weihanglo/weihanglo.github.io
https://raw.githubusercontent.com/weihanglo/weihanglo.github.io/sources/resume/weihanglo-resume.typ
typst
Other
#import "template.typ": * #show: cv.with( author: "<NAME>", img: "bunny.png", contacts: ( [✉ #link("mailto:<EMAIL>")[email]], [🌐 #link("https://weihanglo.tw")[weihanglo.tw]], [🐙 #link("https://github.com/weihanglo")[GitHub]], [💼 #link("https://www.linkedin.com/in/weihanglo/")[LinkedIn]], ) ) = Brief A Rustacean that believes open source and open community would make the world a better place. - Professional Rust developer 🦀. - Maintainer of #ulink("https://github.com/rust-lang/cargo")[the Cargo project]. - Active member and organizer of #ulink("https://rust-lang.tw/")[the Rust Taiwan community]. - Currently focus on build systems and tools development. = Experience #exp( [#ulink("https://aws.amazon.com/")[Amazon Web Services (AWS)]], "Software Engineer", "London, United Kingdom", "July 2022 – Present", [ - Maintain, design, and develop Cargo, the official Rust package manager and build system. - A member of the Rust build experience team, which builds the internal Rust build system at AWS. - Contributed to #ulink("https://github.com/awslabs/smithy-rs")[awslabs/smithy-rs], code generators for generating services for Rust in Rust. ] ) #exp( [#ulink("https://suse.com")[SUSE]], "Senior Software Engineer", "Remote, Taiwan", "June 2021 – June 2022", [ - Contributed to #ulink("https://harvesterhci.io/")[Harvester] GA release. Work on the control plane, VM integration, and disk management. Harvester is an open source HCI solution originated from SUSE and Rancher. ] ) #exp( [#ulink("https://www.linkedin.com/company/hahow/")[Hahow]], "Software Engineer", "Taiwan", "March 2018 – March 2021", [ - Developed autoscaling application to tackle surging demands of online-learning during COVID-19. - Administrated Kubernetes clusters, Helm releases, Consul datacenter, and GKE/GCE infrastructures with alert/monitoring systems and CI/CD processes. - Upgraded 5-year-old MongoDB cluster with minimum downtime by robust migration plan and monitoring. - Designed and developed the migration of legacy order system to decouple business logic from third-party payment service and data storage layer. ] ) #exp( [#ulink("https://www.linkedin.com/company/hyweb/")[Hyweb]], "Software Engineer", "Taiwan", "July 2016 – March 2018", [ - Given Outstanding Employee Award of 2017 (among 10 of 300 employees). - Hosted front-end/Swift study groups and instructed participants from R&D department. - Designed and developed software architecture of HyRead Ebook reader for both web and desktop platforms. HyRead is the largest B2Library Ebook service in Taiwan. - Developed multi-threading download scheduler for #ulink("https://apps.apple.com/app/hyread-3-立即借圖書館小說雜誌電子書/id1098612822")[HyRead 3 iOS App], which won #ulink("https://goo.gl/zyNpLq")[2018 Taiwan Excellence Award]. ] ) #pagebreak() = Education #exp( "National Taiwan University", "BSc in Agriculture Forestry and Resource Conservation", "Taiwan", "August 2012 – Jun 2016", [ - Won Academic Excellence Award 3 times (for top 5% students in class each semester). - Bachelor thesis: _Developed computer-simulated models to imitate a biodiversity assessment method based on human decision modeling_. - Linux system administrator at Forest Mensuration Lab. - Built social corpus with data mining and machine learning techs at #ulink("https://lope.linguistics.ntu.edu.tw/")[Lab of Ontologies, Language Processing & e-Humanities]. ] ) = Projects #exp( "The Rust Programming Language", "Cargo Team Member", [#link("https://rust-lang.org")], "", [ Have been hacking on #ulink("https://github.com/rust-lang/cargo")[Cargo] since 2020. Became a member of the Cargo Team since 2022. Cargo is the official package manager and build tool for Rust. Some data from 2022-09 to 2023-06: - Focus on improving the contributor experience. - One of top three contributors of all time for Cargo. - Triaged 420+ issue with informative responses and labels. - Reviewed 200+ pull requests for rust-lang/cargo - Submitted 120+ pull requests to rust-lang/cargo - Mentored 11+ people from issue to pull request merged - See more #ulink("https://weihanglo.tw/weihanglo-achievements.pdf")[open source achievements here]. ] ) #exp( "Rust Taiwan Community", "Organizer", [#link("https://github.com/rust-tw")], "", [ - Translated “The Rust Programming Language" book to #ulink("https://rust-lang.tw/book-tw/")[Traditional Chinese]. - Gave a #ulink("https://bit.ly/2ZzG1iy")[talk about asynchronous programming] in COSCUP 2019. - Moderate Rust Taiwan Telegram and Facebook groups. ] ) = Skills - *Professional:* - Open source software developement and management - Rust, Cargo, Go, Node.js - MongoDB, Redis, React, GCP, NGINX - Kubernetes development, OS storage management - *Has Experiences in Production:* - Kotlin, TypeScript, Python, Swift/Objective-C - PostgreSQL, SQLAlchemy, Protocol Buffer - Consul, Serverless, AWS CloudFormation/Lambda - libvirt, kvm = Miscellaneous - Languages: English — working proficiency, Chinese — native, Taiwanese — native. - Open source projects contributions: `git2-rs`, `curl-rust`, `hyper`, `mdBook`, `redis-rs`, and others.
https://github.com/Anastasia-Labs/project-close-out-reports
https://raw.githubusercontent.com/Anastasia-Labs/project-close-out-reports/main/f10-plug-and-play-01-closeout-report/plug-and-play-01.typ
typst
#let image-background = image("../images/Background-Carbon-Anastasia-Labs-01.jpg", height: 100%, fit: "cover") #let image-foreground = image("../images/Logo-Anastasia-Labs-V-Color02.png", width: 100%, fit: "contain") #let image-header = image("../images/Logo-Anastasia-Labs-V-Color01.png", height: 75%, fit: "contain") #let fund-link = link("https://projectcatalyst.io/funds/10/f10-developer-ecosystem-the-evolution/plug-and-play-smart-contract-api-a-game-changing-platform-to-deploy-open-source-contracts-instantly")[Catalyst Proposal] #let git-link = link("https://github.com/Anastasia-Labs/plug-n-play-contracts")[Main Github Repo] #let single-asset-staking-link = link("https://github.com/Anastasia-Labs/single-asset-staking")[Single Asset Staking] #let linear-vesting-link = link("https://github.com/Anastasia-Labs/linear-vesting")[Linear Vesting] #let direct-offer-link = link("https://github.com/Anastasia-Labs/direct-offer")[Direct Offer] #let single-asset-staking-api-link = link("https://docs.gomaestro.org/category/single-asset-staking-1")[Single Asset Staking API] #let linear-vesting-api-link = link("https://docs.gomaestro.org/category/linear-vesting-1")[Linear Vesting API] #let direct-offer-api-link = link("https://docs.gomaestro.org/category/direct-swap-1")[Direct Offer API] #let maestro-link = link("https://www.gomaestro.org/smart-contracts")[Maestro Platform] #set page( background: image-background, paper :"a4", margin: (left : 20mm,right : 20mm,top : 40mm,bottom : 30mm) ) // Set default text style #set text(15pt, font: "Montserrat") #v(3cm) // Add vertical space #align(center)[ #box( width: 60%, stroke: none, image-foreground, ) ] #v(1cm) // Add vertical space // Set text style for the report title #set text(22pt, fill: white) // Center-align the report title #align(center)[#strong[Plug-and-play-01 Smart Contract API]] #set text(18pt, fill: white) #align(center)[#strong[PROJECT CLOSE-OUT REPORT]] #v(5cm) // Set text style for project details #set text(13pt, fill: white) // Display project details #table( columns: 2, stroke: none, [*Project Number*], [1000149], [*Project manager*], [Maestro Team & Anastasia Labs], [*Date Started*], [December 23, 2023], [*Date Completed*], [May 31, 2024], ) // Reset text style to default #set text(fill: luma(0%)) // Display project details #show link: underline #set terms(separator:[: ],hanging-indent: 18mm) #set par(justify: true) #set page( paper: "a4", margin: (left: 20mm, right: 20mm, top: 40mm, bottom: 35mm), background: none, header: [ #align(right)[ #image("../images/Logo-Anastasia-Labs-V-Color01.png", width: 25%, fit: "contain") ] #v(-0.5cm) #line(length: 100%, stroke: 0.5pt) ], ) #v(20mm) #show link: underline #show outline.entry.where(level: 1): it => { v(6mm, weak: true) strong(it) } // Initialize page counter #counter(page).update(0) #outline(depth:2, indent: 1em) #pagebreak() #set text(size: 11pt) // Reset text size to 10pt #set page( footer: [ #set text(size: 11pt, fill: gray) #line(length: 100%, stroke: 0.5pt) #v(-3mm) #align(center)[ *Anastasia Labs – Plug-and-play-01 Smart Contract API* #v(-3mm) Project Closeout Report #v(-3mm) // Copyright © // #set text(fill: black) // Anastasia Labs ] #v(-6mm) #align(right)[ #counter(page).display( // Page numbering "1/1", both: true, ) ] ] ) // Display project details #set terms(separator:[: ],hanging-indent: 18mm) / Project Name: Plug-and-play Smart Contract API: A game-changing platform to deploy open-source contracts instantly / URL: #link("link")[#fund-link] \ = List of KPIs \ == Challenge KPIs \ + *Enhancing Developer Productivity:* Given the complexities and time-consuming nature of building secure and reliable smart contracts from scratch, we aimed to streamline the development process. By providing a comprehensive library of modular, reusable, and secure smart contracts, this proposal simplifies integration and deployment. Developers will be able to leverage ready-made and customizable smart contracts, employing best practices and security patterns through a standardized smart contract interface. This minimizes the effort developers spend on repetitive tasks, allowing them to focus on innovation and application-specific logic. + *Increasing Smart Contract Security:* A major challenge for developers is the high risk of smart contract exploitation due to insufficient auditing and security expertise. Our solution provides battle-tested smart contracts, significantly reducing vulnerability risks and enhancing the overall security of Cardano DApps. + *Driving Ecosystem Growth and Adoption:* Our smart contract-as-a-service platform simplifies integration and deployment, attracting more developers to the Cardano ecosystem. Developers will have access to fully integrated smart contracts and be able to interact with them simply via APIs. This will revolutionize Cardano dApp development, unleashing the full potential of Cardano. By offering a standardized interface and best practices, we make it easier for both small teams and large enterprises to build on Cardano. \ == Project KPIs \ + *Provide Secure, Modular and Reusable APIs :* The team developed robust, optimized, and well-tested implementations of Single Asset Staking Contracts, Linear Vesting Contracts, and Direct Offer Contracts. These solutions aim to reduce the time required for developers to build and deploy smart contracts, from weeks or months to even mere minutes, depending on the developer's skill level. By providing secure, modular, and reusable APIs, we address the community's needs for reliable and efficient tools. + *Ensuring Robustness and Reliability:* We conducted rigorous code reviews and comprehensive unit testing to ensure that all smart contracts are robust, reliable, and production-ready. This effort included validating the correctness and efficiency of our implementations, guaranteeing their performance in real-world applications. + *Streamlined Onboarding and Integration:* The project delivered ready-to-use smart contract APIs, along with comprehensive documentation and user-friendly tutorials available on the project’s #git-link. Additionally, our smart contracts and SDKs were seamlessly integrated with Maestro, providing developers with a unified platform for deploying and managing smart contracts. This integration simplifies the development process, allowing developers to interact with our contracts easily and efficiently. + *Increased Developer Adoption:* We have implemented tools to monitor key metrics such as API call volume, the number of unique developers using the APIs, and the number of projects integrating the APIs. This monitoring, combined with community feedback, will guide us in continuously improving the projects and developing new features throughout the project's lifecycle. #pagebreak() \ = Key achievements \ + *Development and Deployment of Core Smart Contracts:* - *Single Asset Staking Contracts:* We successfully developed and deployed contracts that enable users to collectively stake their digital assets and distribute rewards fairly. This contract addresses a significant need within the Cardano ecosystem, providing a reliable and standardized way to implement staking mechanisms. - *Linear Vesting Contracts:* Our team implemented secure linear vesting contracts, which offer customizable options for releasing assets gradually over a specified period. This feature is essential for projects that need to manage token distributions in a controlled manner, such as vesting schedules for team members or early investors. - *Direct Offer Contracts:* We developed a contract that facilitates peer-to-peer trading of assets through a Direct Offer feature. This contract enhances the flexibility of trading within the ecosystem, enabling secure and efficient transactions directly between parties. + *Creation of Comprehensive Off-Chain SDKs:* - We developed off-chain SDKs for each of our smart contracts, including Single Asset Staking, Linear Vesting, and Direct Offer. These SDKs are available on our #git-link and are designed to simplify the integration of our smart contracts into dApps, providing developers with the tools they need to interact with the blockchain seamlessly. + *Integration with Maestro:* - We successfully integrated our smart contracts and SDKs with Maestro, enabling developers to interact with our contracts through Maestro's platform. This integration provides a streamlined interface for deploying and managing smart contracts, further lowering the barrier to entry for developers. + *Extensive documentation and tutorials:* - We provided thorough documentation and tutorials for each contract available on our #git-link. These resources are designed to help developers quickly understand and implement our solutions, ensuring a smooth onboarding process and encouraging adoption. #pagebreak() \ = Key learnings: \ - *Modular Design and Security:* Our project reaffirmed the value of modular, reusable smart contracts for streamlining development and enhancing security. By providing pre-built contracts, we enabled developers to focus on innovation, reducing the need for extensive coding. Rigorous testing and code reviews further validated that our battle-tested contracts effectively mitigate vulnerabilities. This approach demonstrated the potential of modular smart contracts to accelerate the development of secure and reliable dApps on Cardano. - *Simplifying Integration for Ecosystem Growth:* We confirmed that simplifying integration via APIs lowers barriers for developers, making it easier for both small teams and larger enterprises to adopt Cardano. This strategy is essential for driving ecosystem growth and increasing adoption. - *Balancing Customization with Standardization:* The project underscored the need to balance customizable solutions with standardized interfaces. This flexibility ensures consistency while catering to diverse developer needs, which will be crucial as the project evolves. - *Importance of Comprehensive Documentation and Monitoring:* Creating thorough documentation and user-friendly tutorials is vital for effective developer onboarding. Additionally, implementing monitoring tools for key metrics prepares us to make informed, data-driven improvements, helping guide future development based on real-world usage patterns. #pagebreak() \ = Next steps \ + *Expand Smart Contract Library:* Continue developing and integrating additional smart contracts based on developer feedback and ecosystem needs. This will ensure the platform remains relevant and valuable to the growing Cardano developer community. + *Enhance API Documentation:* Improve the API documentation with more examples, use cases, and best practices to make it even easier for developers to integrate and utilize the smart contract services. + *Optimize Performance and Scalability:* Monitor the performance of the smart contract APIs as usage grows and make necessary optimizations to ensure high availability and responsiveness, even under heavy load. + *Collaborate with Ecosystem Partners:* Engage with other Cardano ecosystem projects and partners to explore opportunities for integrating the smart contract APIs into their platforms and services, further expanding the reach and adoption of the solution. + *Continuously Gather Feedback:* Maintain an open dialogue with the developer community, regularly soliciting feedback and suggestions for improvement. Use this input to guide future development and ensure the platform remains aligned with the evolving needs of Cardano builders. #pagebreak() \ = Final thoughts/comments: \ We are proud to introduce our modular smart contract library to the Cardano community. Our commitment to creating secure and scalable solutions lays a strong foundation for future development. We believe that our implementations can enhance the capabilities of DApps on Cardano and serve as a valuable resource for developers. We eagerly anticipate how these tools will inspire innovation and drive adoption in upcoming projects. Moving forward, we remain dedicated to supporting the developer community and adapting our offerings to meet their needs, ensuring our library contributes meaningfully to the Cardano ecosystem. \ = Resources \ #box(height: 100pt, columns(3, gutter: 1pt)[ == Project \ #fund-link #v(1mm) #maestro-link #v(1mm) #git-link == Smart Contracts \ #single-asset-staking-link #v(1mm) #linear-vesting-link #v(1mm) #direct-offer-link == APIs \ #single-asset-staking-api-link #v(1mm) #linear-vesting-api-link #v(1mm) #direct-offer-api-link ]) \ #align(center)[== Closeout Video] \ #align(center)[#link("https://www.youtube.com/watch?v=eXtPjU3aSQc")[ Plug-and-play-01 API -Closeout Video]]
https://github.com/EpicEricEE/typst-equate
https://raw.githubusercontent.com/EpicEricEE/typst-equate/master/tests/margin/test.typ
typst
MIT License
#import "/src/lib.typ": equate #set page(width: 6cm, height: auto, margin: 1em) #show: equate.with(breakable: true) // Test number positioning with different page margins. #set math.equation(numbering: "(1)") #for side in ("left", "right", "x", "inside", "outside") { page(margin: ((side): 2cm))[ $ a + b $ #set math.equation(number-align: start) $ a + b $ #set text(dir: rtl) $ a + b $ ] } // Test break over pages with different margins. #set page(margin: (inside: 2cm), height: 2cm) $ a + b \ c + d \ e + f \ g + h $
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/166.%20safe.html.typ
typst
safe.html Why It's Safe for Founders to Be Nice August 2015I recently got an email from a founder that helped me understand something important: why it's safe for startup founders to be nice people.I grew up with a cartoon idea of a very successful businessman (in the cartoon it was always a man): a rapacious, cigar-smoking, table-thumping guy in his fifties who wins by exercising power, and isn't too fussy about how. As I've written before, one of the things that has surprised me most about startups is how few of the most successful founders are like that. Maybe successful people in other industries are; I don't know; but not startup founders. [1]I knew this empirically, but I never saw the math of why till I got this founder's email. In it he said he worried that he was fundamentally soft-hearted and tended to give away too much for free. He thought perhaps he needed "a little dose of sociopath-ness."I told him not to worry about it, because so long as he built something good enough to spread by word of mouth, he'd have a superlinear growth curve. If he was bad at extracting money from people, at worst this curve would be some constant multiple less than 1 of what it might have been. But a constant multiple of any curve is exactly the same shape. The numbers on the Y axis are smaller, but the curve is just as steep, and when anything grows at the rate of a successful startup, the Y axis will take care of itself.Some examples will make this clear. Suppose your company is making $1000 a month now, and you've made something so great that it's growing at 5% a week. Two years from now, you'll be making about $160k a month.Now suppose you're so un-rapacious that you only extract half as much from your users as you could. That means two years later you'll be making $80k a month instead of $160k. How far behind are you? How long will it take to catch up with where you'd have been if you were extracting every penny? A mere 15 weeks. After two years, the un-rapacious founder is only 3.5 months behind the rapacious one. [2]If you're going to optimize a number, the one to choose is your growth rate. Suppose as before that you only extract half as much from users as you could, but that you're able to grow 6% a week instead of 5%. Now how are you doing compared to the rapacious founder after two years? You're already ahead—$214k a month versus $160k—and pulling away fast. In another year you'll be making $4.4 million a month to the rapacious founder's $2 million.Obviously one case where it would help to be rapacious is when growth depends on that. What makes startups different is that usually it doesn't. Startups usually win by making something so great that people recommend it to their friends. And being rapacious not only doesn't help you do that, but probably hurts. [3]The reason startup founders can safely be nice is that making great things is compounded, and rapacity isn't.So if you're a founder, here's a deal you can make with yourself that will both make you happy and make your company successful. Tell yourself you can be as nice as you want, so long as you work hard on your growth rate to compensate. Most successful startups make that tradeoff unconsciously. Maybe if you do it consciously you'll do it even better.Notes[1] Many think successful startup founders are driven by money. In fact the secret weapon of the most successful founders is that they aren't. If they were, they'd have taken one of the acquisition offers that every fast-growing startup gets on the way up. What drives the most successful founders is the same thing that drives most people who make things: the company is their project.[2] In fact since 2 ≈ 1.05 ^ 15, the un-rapacious founder is always 15 weeks behind the rapacious one.[3] The other reason it might help to be good at squeezing money out of customers is that startups usually lose money at first, and making more per customer makes it easier to get to profitability before your initial funding runs out. But while it is very common for startups to die from running through their initial funding and then being unable to raise more, the underlying cause is usually slow growth or excessive spending rather than insufficient effort to extract money from existing customers.Thanks to <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this, and to <NAME> for being such a nice guy.
https://github.com/lxl66566/my-college-files
https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/写作与表达/结课论文/main.typ
typst
The Unlicense
#import "template.typ": * // 需要 typst 0.10.0 #show: project.with( title: "初探拥塞控制与 BBR 算法", authors: ( "absolutex", ), abstract_zh: [ 拥塞控制是计算机网络中的重要组成部分,并随着互联网的发展而不断显现其重要性。近代互联网的复杂度、联系紧密度都远超之前人们的想象,想管理好如此这样一个庞大系统,拥塞控制是必不可少的技术。拥塞控制确保了当网络出现拥塞时,网络仍然能够以较低的利用率运转,且各用户尽可能公平地利用剩余带宽,避免网络瘫痪。 本文通过拥塞控制的历史与简单的计算机通信模型,引入了拥塞控制原理与算法分析,并着重介绍了其中 BBR 算法的具体实现,分析其优劣与发展潜力。 ], abstract_en: [ Congestion control is an important part of computer networks and continues to show its importance with the development of the Internet. The complexity and tightness of the modern Internet is far beyond what was previously imagined, and congestion control is an essential technique for managing such a large system. Congestion control ensures that when the network is congested, the network can still operate at a low utilization rate, and each user can utilize the remaining bandwidth as fairly as possible to avoid network paralysis. This paper introduces the analysis of congestion control principles and algorithms through the history of congestion control and a simple computer communication model, and focuses on the implementation of the BBR algorithm and analyzes its advantages and disadvantages as well as its development potential. ], keywords_zh: ("拥塞控制", "BBR 算法"), keywords_en: ("congestion control", "BBR algorithm"), ) = 绪论 == 研究背景 随着互联网的普及和应用范围的不断扩大,网络中的信息呈现爆炸式增长,对网络及其基础设施提出了更高的要求。网络数据传输的条件也在不断变化:在地面互联网中,传输带宽越来越高,链路构成越来越复杂;而在一些特殊网络中,如卫星网络中,通信距离越来越远,传播延时越来越大。这都为当前的传输协议带来了前所未有的挑战@曹涛涛:2017。 TCP 作为一种可靠传输协议,通过在数据传输中引入确认和重传机制保证可靠性。当链路不稳定时,丢包率和错误率都会上升;当网络拥挤时,排队的分组总量超出了路由器缓存的大小,导致后续到达的分组被丢弃。由此,大量数据需要重传,从而加剧了网络拥塞。 1983 年,TCP 被默认部署在当时的互联网—— ARPANet 上。1986 年 10 月,由于 ARPANET 网络中的一个路由器出现了故障,大量数据包被重复发送。在加州大学伯克利分校和 400 码外的劳伦斯伯克利国家实验室之间的 32 kbps 链路上检测到互联网拥塞崩溃,在此期间吞吐量下降了近 1000 倍,降至 40 bps@CaltechNetlab。这一现象引起了网络研究者的注意,因此提出了拥塞控制,使其成为一门新的研究领域。 拥塞控制算法是 TCP 协议中非常重要的一部分。在网络拥塞时,主机不再贪婪地发出数据,而是采取更加保守的策略,降低自身发送数据包的速率,从而保证互联网的可用性,尽可能提高带宽利用率。 == 主机通信模型 本文不考虑路由器的转发寻址功能,因此将复杂的计算机网络抽象为点对点的通信链路,如图1所示。 #figure( image("主机模型.png", width: 70%), caption: [网络抽象模型], ) 数据被划分成一个个分组在网络上传播。每个路由器具有一个缓存池,用于缓存路由器接收到的分组。若将链路当成水管,每个数据包分组作为水流,则缓存相当于水池,具有积蓄作用。当某个路由器的输入速率大于输出速率时,多余的分组将在缓存中排队。若分组到达路由器,而缓存已满,该分组将会被丢弃。 在点对点数据传输中所能达到的最高速率取决于瓶颈链路的带宽,也就是传输能力最弱的链路的带宽。 空闲网络中的分组增加,可以提高网络吞吐量。但是当拥塞发生时,网络中的每台主机都需要降低自身的数据发送速率。这必然会导致网络的总体利用率变低,就像在堵车时,道路的车流量实际是减少的。 #figure( image("拥塞崩溃.png", width: 70%), caption: [随着负载的增加,吞吐量会上升,然后在拥塞崩溃点下降。@SystemsApproach], ) = 拥塞控制 == 拥塞控制概述 计算机与路由器构成了一个庞大的网络,任一时间任一节点的数据传输量都在变化。拥塞控制算法运行于主机之上,(在不改变现有网络协议与结构条件下)不能直接访问路由的缓存状态。因此拥塞控制算法需要通过其他办法探知网络的拥挤程度,并控制主机行为缓解拥塞。 拥塞控制的主要目的有两个:一是在网络不拥塞时,让数据发送得尽可能快;二是当拥塞发生时,主动降低数据发送速率,减少重传,避免发生网络崩溃。 除了探测拥塞、控制速度与重传,在拥塞控制算法的具体实现中,还需要考虑算法的公平性。拥塞发生时,网络资源不应被少量主机占有,而是需要尽可能地让所有主机共享相同的带宽。 == 拥塞模型 从 TCP 的角度来看,任意复杂的路径都表现为具有相同 RTT(Round-trip time,往返时间)和瓶颈速率的单个链路。RTprop(Round-trip propagation time,往返传播时间)和 BtlBw(Bottleneck Bandwidth,瓶颈带宽)这两个物理约束限制了传输性能。如果网络路径是物理管道,则 RTprop 将是其长度,BtlBw 将是其最小直径@NealCardwell:2016。 #figure( image("DRandRTT.jpg", width: 70%), caption: [传输速率与往返时间的关系@NealCardwell:2016], ) 图 3 展示了网络运行过程中的三个阶段。第一个阶段,网络处于轻载状态,由于分组无需排队,往返延迟不变,而吞吐量完全取决于主机的发送速率,发送方发送得多快,接收方就能收得多快。第二个阶段,应用进程向网络中的注入速率超过了瓶颈链路的带宽,这个带宽本质上是吞吐量的上限。分组在缓存中排队,而往返延迟随排队的长度增加而增加。此时网络已经出现了拥塞。第三个阶段,网络负载继续增加,排队分组数量超过了缓存容量,多余分组被丢弃,数据需要重传,因此往返延迟与吞吐量是未知的。 == 拥塞控制算法 根据拥塞控制算法的网络感知方式,大致将其分为两类。 === 基于丢包的拥塞控制算法 基于丢包的拥塞控制算法(Black box algorithms@Mamatas2007)又称经典拥塞控制算法。此类算法主要通过是否发生丢包来探测拥塞,采用负反馈方式对主机进行控制。常见的有 Tahoe 算法、Reno 算法、NewReno 算法、SACK 算法,CUBIC 算法等。目前家用 Windows 与 Linux 系统采用 CUBIC 算法作为其默认拥塞控制算法。 此类算法的最大问题是,需要网络实际上出现丢包后,算法才能作出响应。此时网络运行处于第三个阶段,网络的可用性已经大幅下降。同时该类算法还有一些其他问题,例如无法分辨由于高出错率造成的丢包,导致不应有的降速。在无线传输领域,链路的出错率高,经典拥塞控制算法的表现与基于延迟的拥塞控制算法产生了较大差距。 经典拥塞控制算法的工作优势区间是链路多,带宽小,路由器缓存小的网络。然而近年来,随着网络基础设施的不断升级,缓存增大,此类算法在实际应用上的优势已经不明显。 === 基于延迟的拥塞控制算法 基于延迟的拥塞控制算法(Grey box algorithms)通过主动探测 RTT 来感知拥塞。常见的有 Vegas 算法、BBR 算法等。 基于延迟的拥塞控制算法能够在网络运行的第二个阶段感知到拥塞并及时反馈,解决了经典拥塞控制算法的最大痛点。由于其探知拥塞的时机较早,可以很好地适应网络的动态变化。 基于延迟的拥塞控制算法在丢包率高时具有极佳的表现。其中,Vegas 算法过于温和,在面对经典拥塞控制算法时难以取得足够的带宽。而 BBR 算法则具有不逊色于 CUBIC 算法的竞争力,因此成为最具有潜力的拥塞控制算法。 = BBR 算法 == 算法概述 BBR(Bottleneck Bandwidth and Round-trip propagation time)拥塞控制算法由 Google 在 2016 年提出,其通过实时测量网络瓶颈带宽和最小延迟,计算带宽延时积(Bandwidth-Delay Product, BDP)来调整发送速率,实现了高吞吐量和低延时。因此,BBR 算法被认为开创了拥塞控制的新纪元。 BBR 算法现已大规模应用于 Google B4 网络与服务器设施。 == 原理解析 BBR由“初始”,“排空”,“探测带宽”与“探测RTT”四个阶段组成,如图4所示。BBR在这四个阶段通过测量RTT和传输速度对瓶颈带宽和传播时延进行交替性的估计,并以此计算使网络链路处于最优操作点的BDP@杨明:2022。 #figure( image("BBRstatus.png", width: 90%), caption: [BBR的状态机], ) === 初始阶段(Startup) 在 TCP 连接刚建立时,以增益为 2/ln2 的增长速度加速发送数据,直到探测到的最大带宽在连续 3 个 RTT 内不再增加,通过计算得到最优操作点时的 BDP。这种调节机制使得 BBR 能快速地探测网络带宽@杨明:2022。 === 排空阶段(Drain) 在排空阶段,在该阶段 BBR 以初始阶段速率的倒数发送数据包,直到网络中的数据包数量小于等于 BDP。其目的在于排空初始阶段超发的数据包@黄宏平:2023。 === 探测带宽阶段(Probe_BW) 探测带宽阶段是一个稳定阶段,也是 BBR 的主要阶段。这一阶段 BBR 通过累乘增益系数,使发送速率主动适应瓶颈带宽的变化。 === 探测 RTT 阶段(Probe_RTT) 当最小延迟在设定时间内未更新时,减少数据包发送量,以尝试检测更小的最小 RTT,然后在检测完成后根据最新延迟数据确定进入的下一个阶段@马力文:2023(初始或探测带宽阶段)。 == 参考代码 BBR 算法核心伪代码由两部分组成@NealCardwell:2016。 === 接收 ACK 根据每个 ACK (acknowledgement,响应应答)更新 RTprop 和 BtlBw 估计值。 ```js function onAck(packet) rtt = now - packet.sendtime update_min_filter(RTpropFilter, rtt) delivered += packet.size delivered_time = now deliveryRate = (delivered - packet.delivered) / (delivered_time - packet.delivered_time) if (deliveryRate > BtlBwFilter.currentMax || ! packet.app_limited) update_max_filter(BtlBwFilter, deliveryRate) if (app_limited_until > 0) app_limited_until = app_limited_until - packet.size ``` === 发送数据 对每个数据包发送速率进行调整,使数据包到达速率与瓶颈链路的出发速率相匹配。 ```js function send(packet) bdp = BtlBwFilter.currentMax × RTpropFilter.currentMin if (inflight >= cwnd_gain × bdp) // wait for ack or retransmission timeout return if (now >= nextSendTime) packet = nextPacketToSend() if (! packet) app_limited_until = inflight return packet.app_limited = (app_limited_until > 0) packet.sendtime = now packet.delivered = delivered packet.delivered_time = delivered_time ship(packet) nextSendTime = now + packet.size / (pacing_gain × BtlBwFilter.currentMax) timerCallbackAt(send, nextSendTime) ``` == 算法性能 === 算法优势 BBR 算法不将丢包视为拥塞,所以在丢包率较高的网络中,BBR 依然有极高的吞吐量。如图 5 所示。在 1% 丢包率的网络环境下,CUBIC 的吞吐量已经降低 90% 以上,而 BBR 的吞吐量几乎没有受到影响,当丢包率大于 5% 时,BBR 的吞吐量才出现明显的下降,但是当丢包率小于 $10^(-5)$ 时,BBR 吞吐量不如 CUBIC@改进BBR算法在卫星网TCP加速网关中的应用研究。 #figure( image("BBRcomp.jpg", width: 50%), caption: [BBR 与 CUBIC 在不同丢包率情况下吞吐量], ) === 算法缺陷 一些评估报告指出,BBR算法仍存在着一些问题。比如BBR与Reno/CUBIC共享瓶颈时存在不公平性,攻击性太强;在浅缓冲区中丢包率高;具有不同 RTT 的数据流之间存在带宽不公平性等@潘婉苏:2023。 2019 年,BBR 发布了新的 alpha 版本,即版本 2(BBRv2),致力于解决这些局限性。BBRv2 使用两个估算值来确定连接的发送速率:瓶颈带宽和连接的 RTT,并采用带宽探测,以便更好地与 Reno/CUBIC 共存。BBRv2 还采用了显式拥塞通知 (ECN),并能更好地估计丢包率,以确定发送速率@BBRv2。 = 总结 计算机网络依赖于数量庞大的基础设施与传统协议,在给定框架内提出新的思路,是拥塞控制算法的长远任务。BBR 算法由于其优越性倍受青睐,正在取代传统的 TCP 拥塞控制算法,例如 Linux 内核从 4.9 版本开始支持 BBR 算法。 BBR 算法(v2,v3)已大规模应用于 Google B4 网络,并且与新传输协议 QUIC 协议相互配合,实现了更好的传输性能和使用体验,具有巨大的发展潜力。但是对于其存在的具体缺陷,还需要进一步研究和改进,这也是 BBR 尚未在家用设备上普及的一个原因。
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/157.%20pinch.html.typ
typst
pinch.html The Fatal Pinch December 2014Many startups go through a point a few months before they die where although they have a significant amount of money in the bank, they're also losing a lot each month, and revenue growth is either nonexistent or mediocre. The company has, say, 6 months of runway. Or to put it more brutally, 6 months before they're out of business. They expect to avoid that by raising more from investors. [1]That last sentence is the fatal one.There may be nothing founders are so prone to delude themselves about as how interested investors will be in giving them additional funding. It's hard to convince investors the first time too, but founders expect that. What bites them the second time is a confluence of three forces: The company is spending more now than it did the first time it raised money. Investors have much higher standards for companies that have already raised money. The company is now starting to read as a failure. The first time it raised money, it was neither a success nor a failure; it was too early to ask. Now it's possible to ask that question, and the default answer is failure, because at this point that is the default outcome. I'm going to call the situation I described in the first paragraph "the fatal pinch." I try to resist coining phrases, but making up a name for this situation may snap founders into realizing when they're in it.One of the things that makes the fatal pinch so dangerous is that it's self-reinforcing. Founders overestimate their chances of raising more money, and so are slack about reaching profitability, which further decreases their chances of raising money.Now that you know about the fatal pinch, how do you avoid it? Y Combinator tells founders who raise money to act as if it's the last they'll ever get. Because the self-reinforcing nature of this situation works the other way too: the less you need further investment, the easier it is to get.What do you do if you're already in the fatal pinch? The first step is to re-evaluate the probability of raising more money. I will now, by an amazing feat of clairvoyance, do this for you: the probability is zero. [2]Three options remain: you can shut down the company, you can increase how much you make, and you can decrease how much you spend.You should shut down the company if you're certain it will fail no matter what you do. Then at least you can give back the money you have left, and save yourself however many months you would have spent riding it down.Companies rarely have to fail though. What I'm really doing here is giving you the option of admitting you've already given up.If you don't want to shut down the company, that leaves increasing revenues and decreasing expenses. In most startups, expenses = people, and decreasing expenses = firing people. [3] Deciding to fire people is usually hard, but there's one case in which it shouldn't be: when there are people you already know you should fire but you're in denial about it. If so, now's the time.If that makes you profitable, or will enable you to make it to profitability on the money you have left, you've avoided the immediate danger.Otherwise you have three options: you either have to fire good people, get some or all of the employees to take less salary for a while, or increase revenues.Getting people to take less salary is a weak solution that will only work when the problem isn't too bad. If your current trajectory won't quite get you to profitability but you can get over the threshold by cutting salaries a little, you might be able to make the case to everyone for doing it. Otherwise you're probably just postponing the problem, and that will be obvious to the people whose salaries you're proposing to cut. [4]Which leaves two options, firing good people and making more money. While trying to balance them, keep in mind the eventual goal: to be a successful product company in the sense of having a single thing lots of people use.You should lean more toward firing people if the source of your trouble is overhiring. If you went out and hired 15 people before you even knew what you were building, you've created a broken company. You need to figure out what you're building, and it will probably be easier to do that with a handful of people than 15. Plus those 15 people might not even be the ones you need for whatever you end up building. So the solution may be to shrink and then figure out what direction to grow in. After all, you're not doing those 15 people any favors if you fly the company into ground with them aboard. They'll all lose their jobs eventually, along with all the time they expended on this doomed company.Whereas if you only have a handful of people, it may be better to focus on trying to make more money. It may seem facile to suggest a startup make more money, as if that could be done for the asking. Usually a startup is already trying as hard as it can to sell whatever it sells. What I'm suggesting here is not so much to try harder to make money but to try to make money in a different way. For example, if you have only one person selling while the rest are writing code, consider having everyone work on selling. What good will more code do you when you're out of business? If you have to write code to close a certain deal, go ahead; that follows from everyone working on selling. But only work on whatever will get you the most revenue the soonest.Another way to make money differently is to sell different things, and in particular to do more consultingish work. I say consultingish because there is a long slippery slope from making products to pure consulting, and you don't have to go far down it before you start to offer something really attractive to customers. Although your product may not be very appealing yet, if you're a startup your programmers will often be way better than the ones your customers have. Or you may have expertise in some new field they don't understand. So if you change your sales conversations just a little from "do you want to buy our product?" to "what do you need that you'd pay a lot for?" you may find it's suddenly a lot easier to extract money from customers.Be ruthlessly mercenary when you start doing this, though. You're trying to save your company from death here, so make customers pay a lot, quickly. And to the extent you can, try to avoid the worst pitfalls of consulting. The ideal thing might be if you built a precisely defined derivative version of your product for the customer, and it was otherwise a straight product sale. You keep the IP and no billing by the hour.In the best case, this consultingish work may not be just something you do to survive, but may turn out to be the thing-that-doesn't-scale that defines your company. Don't expect it to be, but as you dive into individual users' needs, keep your eyes open for narrow openings that have wide vistas beyond.There is usually so much demand for custom work that unless you're really incompetent there has to be some point down the slope of consulting at which you can survive. But I didn't use the term slippery slope by accident; customers' insatiable demand for custom work will always be pushing you toward the bottom. So while you'll probably survive, the problem now becomes to survive with the least damage and distraction.The good news is, plenty of successful startups have passed through near-death experiences and gone on to flourish. You just have to realize in time that you're near death. And if you're in the fatal pinch, you are. Notes[1] There are a handful of companies that can't reasonably expect to make money for the first year or two, because what they're building takes so long. For these companies substitute "progress" for "revenue growth." You're not one of these companies unless your initial investors agreed in advance that you were. And frankly even these companies wish they weren't, because the illiquidity of "progress" puts them at the mercy of investors.[2] There's a variant of the fatal pinch where your existing investors help you along by promising to invest more. Or rather, where you read them as promising to invest more, while they think they're just mentioning the possibility. The way to solve this problem, if you have 8 months of runway or less, is to try to get the money right now. Then you'll either get the money, in which case (immediate) problem solved, or at least prevent your investors from helping you to remain in denial about your fundraising prospects.[3] Obviously, if you have significant expenses other than salaries that you can eliminate, do it now.[4] Unless of course the source of the problem is that you're paying yourselves high salaries. If by cutting the founders' salaries to the minimum you need, you can make it to profitability, you should. But it's a bad sign if you needed to read this to realize that. Thanks to <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.Arabic Translation
https://github.com/liuguangxi/fractusist
https://raw.githubusercontent.com/liuguangxi/fractusist/main/src/sierpinski.typ
typst
MIT License
//============================================================================== // The Sierpiński curve // // Public functions: // sierpinski-curve, sierpinski-square-curve // sierpinski-arrowhead-curve // sierpinski-triangle //============================================================================== #import "util.typ": gen-svg //---------------------------------------------------------- // Public functions //---------------------------------------------------------- // Generate classic Sierpiński curve // // iterations: [0, 7] // axiom: "F--XF--F--XF" // rule set: // "X" -> "XF+G+XF--F--XF+G+X" // angle: 45 deg // // Arguments: // n: the number of iterations // step-size: step size (in pt), optional // fill-style: fill style, can be none or color or gradient, optional // stroke-style: stroke style, can be none or color or gradient or stroke object, optional // width: the width of the image, optional // height: the height of the image, optional // fit: how the image should adjust itself to a given area, "cover" / "contain" / "stretch", optional // // Returns: // content: generated vector graphic #let sierpinski-curve(n, step-size: 10, fill-style: none, stroke-style: black + 1pt, width: auto, height: auto, fit: "cover") = { assert(type(n) == int and n >= 0 and n <= 7, message: "`n` should be in range [0, 7]") assert(step-size > 0, message: "`step-size` should be positive") assert((fill-style == none) or (type(fill-style) == color) or (type(fill-style) == gradient and (repr(fill-style.kind()) == "linear" or repr(fill-style.kind()) == "radial")), message: "`fill-style` should be none / color / gradient.linear / gradient.radial") if stroke-style != none {stroke-style = stroke(stroke-style)} let stroke-width = if (stroke-style == none) {0} else if (stroke-style.thickness == auto) {1} else {calc.abs(stroke-style.thickness.pt())} let axiom = "F--XF--F--XF" let rule-set = ("X": "XF+G+XF--F--XF+G+X") let fdx = (step-size, step-size/2*calc.sqrt(2), 0, -step-size/2*calc.sqrt(2), -step-size, -step-size/2*calc.sqrt(2), 0, step-size/2*calc.sqrt(2)) let fdy = (0, step-size/2*calc.sqrt(2), step-size, step-size/2*calc.sqrt(2), 0, -step-size/2*calc.sqrt(2), -step-size, -step-size/2*calc.sqrt(2)) let gdx = (step-size*calc.sqrt(2), step-size, 0, -step-size, -step-size*calc.sqrt(2), -step-size, 0, step-size) let gdy = (0, step-size, step-size*calc.sqrt(2), step-size, 0, -step-size, -step-size*calc.sqrt(2), -step-size) let fdx-str = fdx.map(i => repr(i)) let fdy-str = fdy.map(i => repr(i)) let gdx-str = gdx.map(i => repr(i)) let gdy-str = gdy.map(i => repr(i)) let s = axiom for i in range(n) {s = s.replace("X", rule-set.at("X"))} let dir = 7 let path-d = "M0 0 " for c in s { if c == "-" { dir -= 1 if dir < 0 {dir = 7} } else if c == "+" { dir += 1 if (dir == 8) {dir = 0} } else if c == "F" { path-d += "l" + fdx-str.at(dir) + " " + fdy-str.at(dir) + " " } else if c == "G" { path-d += "l" + gdx-str.at(dir) + " " + gdy-str.at(dir) + " " } } path-d += "Z" let margin = calc.max(5, stroke-width * 1.5) let x-min = (3/2 - calc.pow(2, n + 1)) * calc.sqrt(2) * step-size let x-max = step-size / 2 * calc.sqrt(2) let y-min = (1 - calc.pow(2, n + 1)) * calc.sqrt(2) * step-size let y-max = 0 x-min = calc.floor(x-min - margin) x-max = calc.ceil(x-max + margin) y-min = calc.floor(y-min - margin) y-max = calc.ceil(y-max + margin) let svg-code = gen-svg(path-d, (x-min, x-max, y-min, y-max), fill-style, stroke-style) return image.decode(svg-code, width: width, height: height, fit: fit) } // Generate Sierpiński square curve // // iterations: [0, 7] // axiom: "F+XF+F+XF" // rule set: // "X" -> "XF-F+F-XF+F+XF-F+F-X" // angle: 90 deg // // Arguments: // n: the number of iterations // step-size: step size (in pt), optional // fill-style: fill style, can be none or color or gradient, optional // stroke-style: stroke style, can be none or color or gradient or stroke object, optional // width: the width of the image, optional // height: the height of the image, optional // fit: how the image should adjust itself to a given area, "cover" / "contain" / "stretch", optional // // Returns: // content: generated vector graphic #let sierpinski-square-curve(n, step-size: 10, fill-style: none, stroke-style: black + 1pt, width: auto, height: auto, fit: "cover") = { assert(type(n) == int and n >= 0 and n <= 7, message: "`n` should be in range [0, 7]") assert(step-size > 0, message: "`step-size` should be positive") assert((fill-style == none) or (type(fill-style) == color) or (type(fill-style) == gradient and (repr(fill-style.kind()) == "linear" or repr(fill-style.kind()) == "radial")), message: "`fill-style` should be none / color / gradient.linear / gradient.radial") if stroke-style != none {stroke-style = stroke(stroke-style)} let stroke-width = if (stroke-style == none) {0} else if (stroke-style.thickness == auto) {1} else {calc.abs(stroke-style.thickness.pt())} let axiom = "F+XF+F+XF" let rule-set = ("X": "XF-F+F-XF+F+XF-F+F-X") let dx = (step-size, 0, -step-size, 0) let dy = (0, step-size, 0, -step-size) let dx-str = dx.map(i => repr(i)) let dy-str = dy.map(i => repr(i)) let s = axiom for i in range(n) {s = s.replace("X", rule-set.at("X"))} let dir = 0 let path-d = "M0 0 " for c in s { if c == "-" { dir -= 1 if dir < 0 {dir = 3} } else if c == "+" { dir += 1 if (dir == 4) {dir = 0} } else if c == "F" { path-d += "l" + dx-str.at(dir) + " " + dy-str.at(dir) + " " } } path-d += "Z" let margin = calc.max(5, stroke-width) let x-min = (2 - calc.pow(2, n + 1)) * step-size let x-max = (calc.pow(2, n + 1) - 1) * step-size let y-min = 0 let y-max = (calc.pow(2, n + 2) - 3) * step-size x-min = calc.floor(x-min - margin) x-max = calc.ceil(x-max + margin) y-min = calc.floor(y-min - margin) y-max = calc.ceil(y-max + margin) let svg-code = gen-svg(path-d, (x-min, x-max, y-min, y-max), fill-style, stroke-style) return image.decode(svg-code, width: width, height: height, fit: fit) } // Generate Sierpiński arrowhead curve // // iterations: [0, 8] // axiom: "XF" // rule set: // "X" -> "YF+XF+Y" // "Y" -> "XF-YF-X" // angle: 60 deg // // Arguments: // n: the number of iterations // step-size: step size (in pt), optional // stroke-style: stroke style, can be none or color or gradient or stroke object, optional // width: the width of the image, optional // height: the height of the image, optional // fit: how the image should adjust itself to a given area, "cover" / "contain" / "stretch", optional // // Returns: // content: generated vector graphic #let sierpinski-arrowhead-curve(n, step-size: 10, stroke-style: black + 1pt, width: auto, height: auto, fit: "cover") = { assert(type(n) == int and n >= 0 and n <= 8, message: "`n` should be in range [0, 8]") assert(step-size > 0, message: "`step-size` should be positive") if stroke-style != none {stroke-style = stroke(stroke-style)} let stroke-width = if (stroke-style == none) {0} else if (stroke-style.thickness == auto) {1} else {calc.abs(stroke-style.thickness.pt())} let axiom = "XF" let rule-set = (X: "YF+XF+Y", Y: "XF-YF-X") let dx = (step-size, step-size/2, -step-size/2, -step-size, -step-size/2, step-size/2) let dy = (0, step-size/2*calc.sqrt(3), step-size/2*calc.sqrt(3), 0, -step-size/2*calc.sqrt(3), -step-size/2*calc.sqrt(3)) let dx-str = dx.map(i => repr(i)) let dy-str = dy.map(i => repr(i)) let s = axiom for i in range(n) {s = s.replace(regex("X|Y"), x => rule-set.at(x.text))} let dir = if calc.even(n) {0} else {5} let path-d = "M0 0 " for c in s { if c == "-" { dir -= 1 if dir < 0 {dir = 5} } else if c == "+" { dir += 1 if (dir == 6) {dir = 0} } else if c == "F" { path-d += "l" + dx-str.at(dir) + " " + dy-str.at(dir) + " " } } let margin = calc.max(5, stroke-width * 1.5) let x-min = 0 let x-max = calc.pow(2, n) * step-size let y-min = (1 - calc.pow(2, n)) * calc.sqrt(3)/2 * step-size let y-max = 0 x-min = calc.floor(x-min - margin) x-max = calc.ceil(x-max + margin) y-min = calc.floor(y-min - margin) y-max = calc.ceil(y-max + margin) let svg-code = gen-svg(path-d, (x-min, x-max, y-min, y-max), none, stroke-style) return image.decode(svg-code, width: width, height: height, fit: fit) } // Generate 2D Sierpiński triangle // // iterations: [0, 6] // axiom: "F-G-G" // rule set: // "F" -> "F-G+F+G-F" // "G" -> "GG" // angle: 120 deg // // Arguments: // n: the number of iterations // step-size: step size (in pt), optional // fill-style: fill style, can be none or color or gradient, optional // stroke-style: stroke style, can be none or color or gradient or stroke object, optional // width: the width of the image, optional // height: the height of the image, optional // fit: how the image should adjust itself to a given area, "cover" / "contain" / "stretch", optional // // Returns: // content: generated vector graphic #let sierpinski-triangle(n, step-size: 10, fill-style: none, stroke-style: black + 1pt, width: auto, height: auto, fit: "cover") = { assert(type(n) == int and n >= 0 and n <= 6, message: "`n` should be in range [0, 6]") assert(step-size > 0, message: "`step-size` should be positive") assert((fill-style == none) or (type(fill-style) == color) or (type(fill-style) == gradient and (repr(fill-style.kind()) == "linear" or repr(fill-style.kind()) == "radial")), message: "`fill-style` should be none / color / gradient.linear / gradient.radial") if stroke-style != none {stroke-style = stroke(stroke-style)} let stroke-width = if (stroke-style == none) {0} else if (stroke-style.thickness == auto) {1} else {calc.abs(stroke-style.thickness.pt())} let axiom = "F-G-G" let rule-set = ("F": "F-G+F+G-F", "G": "GG") let dx = (step-size, -step-size/2, -step-size/2) let dy = (0, step-size/2*calc.sqrt(3), -step-size/2*calc.sqrt(3)) let dx-str = dx.map(i => repr(i)) let dy-str = dy.map(i => repr(i)) let s = axiom for i in range(n) {s = s.replace(regex("F|G"), x => rule-set.at(x.text))} let dir = 0 let path-d = "M0 0 " for c in s { if c == "-" { dir -= 1 if dir < 0 {dir = 2} } else if c == "+" { dir += 1 if (dir == 3) {dir = 0} } else if c == "F" or c == "G" { path-d += "l" + dx-str.at(dir) + " " + dy-str.at(dir) + " " } } path-d += "Z" let margin = calc.max(5, stroke-width) let x-min = 0 let x-max = calc.pow(2, n) * step-size let y-min = -calc.pow(2, n - 1) * calc.sqrt(3) * step-size let y-max = 0 x-min = calc.floor(x-min - margin) x-max = calc.ceil(x-max + margin) y-min = calc.floor(y-min - margin) y-max = calc.ceil(y-max + margin) let svg-code = gen-svg(path-d, (x-min, x-max, y-min, y-max), fill-style, stroke-style) return image.decode(svg-code, width: width, height: height, fit: fit) }
https://github.com/EGmux/PCOM-2023.2
https://raw.githubusercontent.com/EGmux/PCOM-2023.2/main/lista2/lista2q6.typ
typst
=== A informação em uma forma de onda analógica, cuja frequência máxima vale *$f_m = 4000 "Hz"$*, é transmitida usando-se um sistema 16-PAM. A distorção de quantização não deve exceder *$plus.minus 1%$* da tensão de pico-a-pico do sinal analógico. \ ==== a) Qual o número mínimo de bits por amostra ou bits por palavra PCM que dev ser usado neste sistema de transmissão PAM ? \ dada a frequência máxima temos que a frequência de Nyquist é de #math.equation(block: true, $ f_N = 8000 "Hz" $) assim o número de bits é _l_ que é dado por #math.equation( block: true, $ l = log_2(1/(2p)) tilde.eq 5.6438561897747 = 6 "bits/amostra" $, ) ==== b) Qual a taxa de amostragem mínima necessária e qual a taxa de bits resultante? \ a taxa de amostragem mínima já foi computada é é de 8000 Hz a taxa de bits resultante pode ser computada como segue abaixo: #math.equation( block: true, $ R_b = (8000 "amostras/s") dot (6 "bits/amostras") = 48 "kbits/s" $, ) ==== Qual a taxa de símbolos do sistema 16-PAM? \ aqui é computar _k_ primeiramente que é dado por #math.equation(block: true, $ k = log_2 16 = 4 "bits/símbolo" $) e por fim temos #math.equation(block: true, $ R_s = R_b / k = 12 "k símbolos/s" $)
https://github.com/actsasflinn/typst-rb
https://raw.githubusercontent.com/actsasflinn/typst-rb/main/test/template_with_font_and_icon/template.typ
typst
Apache License 2.0
#let template(body) = { set text(12pt, font: "Fasthand") set page( paper: "us-letter", margin: (left: 1.6cm, right: 1.6cm, top: 1.5cm), fill: blue ) body }
https://github.com/JosephBoom02/Appunti
https://raw.githubusercontent.com/JosephBoom02/Appunti/main/Anno_3_Semestre_1/Elettronica/Elettronica.typ
typst
#import "@preview/physica:0.9.0": * #import "@preview/i-figured:0.2.3" #import "@preview/cetz:0.1.2" #import "@preview/xarrow:0.2.0": xarrow #import cetz.plot #let title = "Elettronica" #let author = "<NAME>" #set page(numbering: "1") #set document(title: title, author: author) #cetz.canvas({ import cetz.draw: * // Your drawing code goes here }) #show math.equation: i-figured.show-equation.with(level: 2, only-labeled: true) #show link: set text(rgb("#cc0052")) #show ref: set text(green) #set page(margin: (y: 1cm)) #set heading(numbering: "1.1.1.1.1.1") //#set math.equation(numbering: "(1)") #set math.mat(gap: 1em) //Code to have bigger fraction in inline math #let dfrac(x,y) = math.display(math.frac(x,y)) //Equation without numbering (obsolete) #let nonum(eq) = math.equation(block: true, numbering: none, eq) //Usage: #nonum($a^2 + b^2 = c^2$) #let space = h(3.5em) #let Space = h(5em) //Shortcut for centered figure with image #let cfigure(img, wth) = figure(image(img, width: wth)) //Usage: #cfigure("images/Es_Rettilineo.png", 70%) #let nfigure(img, wth) = figure(image("images/"+img, width: wth)) //Code to have sublevel equation numbering /*#set math.equation(numbering: (..nums) => { locate(loc => { "(" + str(counter(heading).at(loc).at(0)) + "." + str(nums.pos().first()) + ")" }) },) #show heading: it => { if it.level == 1 { counter(math.equation).update(0) } }*/ // //Shortcut to write equation with tag aligned to right #let tageq(eq,tag) = grid(columns: (1fr, 1fr, 1fr), column-gutter: 1fr, [], math.equation(block: true ,numbering: none)[$eq$], align(horizon)[$tag$]) // Usage: #tageq($x=y$, $j=1,...,n$) // Show title and author #v(3pt, weak: true) #align(center, text(18pt, title)) #v(8.35mm, weak: true) #align(center, text(15pt, author)) #v(8.35mm, weak: true) // Color in math mode #let colpurp(x) = text(fill: purple, $#x$) #let colred(x) = text(fill: red, $#x$) #outline() = SI == Unità derivate SI #table( columns: (13em, auto, auto, 13em), inset: 10pt, align: horizon, table.header( [*Grandezza*], [*Simbolo*], [*Unità SI non di base*], [*Unità SI di base*] ), [Carica elettrica], [$C$ (Coulomb)], [], [$s times A$], [Tensione elettrica e differenza di potenziale elettrico ], [$V$ "(Volt)"], [$ dfrac(W,A)$], [$m^2 times k g times s^(-3) times A^(-1)$], [Forza], [$N$ (Newton)], [], [$m times k g times s^(-2)$], [Energia/Lavoro], [$J$ (Joule)], [$N times m$], [$m^2 times k g times s^(-2)$], [Potenza], [$W$ (Watt)], [$dfrac(J,s)$], [$m^2 times k g times s^(-3)$], [Flusso magnetico], [$W b$ (Weber)], [$V times s$], [$m^2 times k g times s-2 times A^(-1)$], [Induzione magnetica], [$T$ (Tesla)], [$dfrac(W b,m^2)$], [$k g times s^(-2) times A^(-1)$], [Resistenza elettrica], [$Omega$ (Ohm)], [$dfrac(V,A)$], [$m^2 times k g times s^(-3) times A^(-2)$], [Conduttanza elettrica], [$S$ (Siemens)], [$dfrac(A,V)$], [$m^(-2) times k g^(-1) times s^3 times A^2$], [Capacità], [$F$ (Farad)], [$dfrac(C,V)$], [$m^(-2) times k g^(-1) times s^4 times A^2$], [Induttanza], [$H$ (Henry)], [$dfrac(W b,A)$], [$m^2 times k g times s^(-2) times A^(-2)$], [Frequenza], [$H z$ (Hertz)], [], [$s^(-1)$] ) #pagebreak() == Prefissi #align(center)[ #table( columns: (auto, auto, auto), inset: 10pt, align: horizon, table.header( [*Factor*], [*Name*], [*Symbol*] ), [$10^(-24)$] , [yocto] , [y], [$10^(-21)$] , [zepto] , [z], [$10^(-18)$] , [atto] , [a], [$10^(-15)$] , [femto] , [f], [$10^(-12)$] , [pico] , [p], [$10^(-9)$] , [nano] ,[n], [$10^(-6)$] , [micro] , [$mu$], [$10^(-3)$] , [milli] , [m], [$10^(-2)$] , [centi] , [c], [$10^(-1)$] , [deci] , [d], [$10^(1)$] , [deca] , [da], [$10^(2)$] , [hecto] , [mh], [$10^(6)$] , [mega] , [M], [$10^(9)$] , [giga] , [G], [$10^(12)$] , [tera] , [T], [$10^(15)$] , [peta] ,[P], [$10^(18)$] , [exa] , [E], [$10^(21)$] , [zetta] , [Z], [$10^(24)$] , [yotta] , [Y] ) ] #pagebreak() = Tipi di esercizi == A === Formule notevoli *N.B.* Alcune formule si trovano nel #link("./Formulario_elettronica.pdf")[Formulario]. ==== Formule simboliche di resistore, induttore e condensatore $ &bold("Resistore") &space space &bold("Induttore") &space space &bold("Condensatore") \ &V = R I & &V = j omega L I & &V = - dfrac(j, omega C) I \ &Z = R & &Z = j omega L & Z = &dfrac(1, j omega C) = - dfrac(j,omega C) $ === Diagrammi di Bode ==== Guadagno statico $ G_a (j omega) &= mu & space |G_a (j omega)|_("dB") &= 20 log|mu| & space arg(G(j omega)) = arg( mu) $ #cfigure("images/Diagramma_guadagno_statico_1.png", 63%) Per quanto riguarda il diagramma dell'ampiezza, - se $|mu| >= 1$ allora $20 log|mu| >= 0$ - se $|mu| <1$ allora $20 log|mu| < 0$. Per il diagramma della fase invece - se $ mu >0$ allora $ arg( mu)=0$ - se $ mu <0$ allora $ arg( mu)=-180 degree$. ==== Zeri nell'origine Consideriamo una risposta con uno zero nell'origine (cioè $g=-1$) $ G_b (j omega) &= frac(1,(j omega)^(-1)) = j omega &wide |G_b (j omega)|_("dB") &= 20 log omega &wide arg(G_b (j omega)) &= arg(j omega) $ #cfigure("images/Diagramma_zero_origine.png", 72%) La retta che definisce l'ampiezza $ log omega arrow.r.bar 20 log omega$ ha pendenza $20 "dB/dec"$; se ho $g$ zeri nell'origine allora la pendenza della retta sarà $20 dot g "dB/dec"$.\ $j omega$ è un punto sul semiasse immaginario positivo $forall omega > 0$, quindi fase $90^degree forall > 0$. ==== Poli nell'origine Consideriamo una risposta con un polo nell'origine (cioè $g=1$) $ G_b (j omega) &= frac(1,(j omega)^1) = frac(1,j omega) &space |G_b (j omega)|_("dB") &= -20 log omega &space arg(G_b (j omega)) &= - arg(j omega) $ #cfigure("images/Diagramma_poli_origine.png", 75%) Anche in questo caso, se ho $g$ poli nell'origine allora la pendenza della retta sarà $-20 "dB/dec"$. Per quanto riguarda la fase $-j omega$ è un punto sul semiasse immaginario negativo $ forall omega>0$, quindi la fase è $-90^ degree$. ==== Zero reale (ampiezza) Consideriamo una risposta con uno zero reale $ G_c (j omega) = 1 + j omega tau $ $ |G_c (j omega)|_("dB") = 20 log sqrt(1 + omega^2 tau^2) approx cases( 20 log 1 = 0 & omega << dfrac(1,|tau|)\ 20 log omega |tau| = -20 log dfrac(1,|tau|) + 20 log omega wide& omega >> dfrac(1,|tau|) ) $ $ lr(|G_c (j frac(1,|tau|) )|)_("dB") &= 20 log sqrt(1+ frac(1,|tau|^2) tau^2) \ &= 20 log sqrt(2) approx 3 $ per $ omega = frac(1,|tau|)$ abbiamo lo scostamento massimo. #nfigure("Zero_reale_ampiezza.png", 60%) ==== Zero reale negativo (fase) Consideriamo una una risposta con uno zero reale negativo #tageq($G_c (j omega) = 1 + j omega tau$, $ tau > 0$) $ arg(G_c (j omega)) = arg(1+j omega tau) approx cases( 0 wide& omega << frac(1, tau) \ 90^ degree & omega >> frac(1, tau) ) $ Se $ omega arrow 0$ allora $ arg(1+j omega tau) approx arg(1)=0$ #cfigure("images/Diagramma_zero_reale_negativo_1.png", 60%) se $ omega >> dfrac(1, tau)$ allora graficamente #cfigure("images/Diagramma_zero_reale_negativo_2.png", 60%) #cfigure("images/Diagramma_zero_reale_negativo_3.png", 72%) il cambio di fase inizia circa una decade prima e finisce circa una decade dopo la pulsazione di taglio $ omega = dfrac(1, tau)$. #cfigure("images/Diagramma_zero_reale_negativo_4.png", 60%) $ dfrac(1,5) dot dfrac(1, tau) = 0.2 dot dfrac(1, tau) = 2 dot 10^(-1) dfrac(1, tau)$, il doppio in scala logaritmica è $ dfrac(1,3)$ di una decade. ==== Zero reale positivo (fase) Consideriamo $G_c (j omega) = 1 + j omega tau, tau <0$ (cioè una risposta con uno zero reale positivo) #cfigure("images/Diagramma_zero_reale_positivo_1.png", 32%) $ arg(G(j omega)) = arg(1+j omega tau) approx cases( 0 & omega << frac(1,|tau|) \ -90^( degree) wide& omega >> frac(1,|tau|) ) $ #cfigure("images/Diagramma_zero_reale_positivo_2.png", 70%) ==== Polo reale Consideriamo $G_c (j omega) = dfrac(1,1+j omega T)$ (cioè una risposta con un polo reale) $ |G_c (j omega)|_("dB") &= 20 log lr(| frac(1,1+j omega T) |) \ &= -20 log |1+j omega T| $ $ |G_c (j omega)|_("dB") &= -20 log sqrt(1+ omega^2T^2) & space arg(G_c (j omega)) = - arg(1+j omega T) $ #cfigure("images/Diagramma_polo_reale.png", 73%) Il diagramma è uguale al diagramma dello zero ma ribaltato rispetto all'asse reale (consistentemente con il segno di $T$). ==== Polo reale negativo Consideriamo $G_c (j omega) = dfrac(1,1+j omega T), T>0$ (cioè una risposta con un polo reale negativo) $ |G_c (j omega)|_("dB") &= -20 log sqrt(1+ omega^2T^2) & space arg(G_c (j omega)) = - arg(1+j omega T) $ #cfigure("images/Diagramma_polo_reale_negativo_1.png", 53%) Fino a $ dfrac(1,T)$, (pulsazione di taglio), si ha un andamento costante a $0 "dB" $, cioè il modulo della sinusoide in uscita non cambia. A partire da $ dfrac(1,T)$ si ha una retta $ log omega arrow.r.bar 20 log dfrac(1,|T|) - 20 log omega$ con pendenza $-20 "dB/dec"$. Lo scostamento massimo (tra diagramma asintotico e diagramma reale) si ha in $ omega = dfrac(1,T)$ dove $ |G_c (j omega)|_("dB") &= -20 log sqrt(1+1) \ &= -20 log sqrt(2) approx -3 $ Il cambio di fase inizia circa una decade prima e finisce circa una decade dopo la pulsazione di taglio $ omega = dfrac(1,T)$. ==== Zeri complessi coniugati (ampiezza) Consideriamo $G_d (j omega) = 1+ 2j zeta dfrac( omega, alpha_n) - dfrac( omega^2, alpha_n^2)$, una risposta con una coppia di zeri complessi coniugati $ |G_d (j omega)|_("dB") = 20 log sqrt( (1 - frac( omega^2, alpha_n^2) )^2 + 4 zeta^2 frac( omega^2, alpha_n^2)) $ per $ omega >> alpha_n$ $ |G_d (j omega)|_("dB") & approx 20 log sqrt( ( frac( omega^2, alpha_n^2) )^2) \ &=20 log frac( omega^2, alpha_n^2) \ &= 20 log ( frac( omega, alpha_n) )^2 \ &= 40 log frac( omega, alpha_n) \ &= underbrace(40 log omega, "variabile") - underbrace(40 log alpha_n, "costante") $ Quindi la risposta si comporta come una retta, di pendenza pari a 40 dB. Analizziamo ora la risposta per $ omega = alpha_n$ $ |G_d (j omega)|_("dB") &20 log sqrt( (1 - frac( omega^2, alpha_n^2) )^2 + 4 zeta^2 frac( omega^2, alpha_n^2)) \ &= 20 log sqrt(4 zeta^2) \ &= 23 log 2|zeta| \ &= underbrace(20 log 2 ,6 "dB") +20 log |zeta| $ quindi scostamento significativo dipendente dal valore di $ zeta$. $ |G_d (j omega)|_("dB") = 20 log sqrt( (1 - frac( omega^2, alpha_n^2) )^2 + 4 zeta^2 frac( omega^2, alpha_n^2)) approx cases( 20 log(1) = 0 & omega << alpha_n \ 20 log dfrac( omega^2, alpha_n^2) = -40 log alpha_n + 40 log omega wide& omega >> alpha_n ) $ #cfigure("images/Diagramma_zeri_cc_ampiezza_1.png", 55%) #cfigure("images/Diagramma_zeri_cc_ampiezza_2.png", 55%) Il minimo dell'ampiezza si ha alla pulsazione $ omega_r = alpha_n sqrt(1-2 zeta^2)$ con $|G_d (j omega_r)| = 2 |zeta| sqrt(1- zeta^2)$ ==== Zeri complessi coniugati a parte reale negativa (fase) Consideriamo $G_d (j omega) = 1+ 2j zeta dfrac( omega, alpha_n) - dfrac( omega^2, alpha_n^2), zeta>0$, una risposta con una coppia di zeri complessi coniugati a parte reale negativa $ arg(G_d (j omega)) approx cases( 0 & omega << alpha_n \ 180^ degree wide& omega >> alpha_n ) $ #cfigure("images/Diagramma_zeri_cc_neg_1.png", 60%) Vediamo che la risposta, per $ omega >> alpha_n$, nel piano complesso ha sicuramente una parte reale molto negativa, mentre la parte immaginaria dipende dal valore $ zeta$, il quale influenza molto l'andamento della fase. Ad esempio se $ zeta arrow 0$ la parte immaginaria nel piano complesso tenderà anch'essa a 0, così da rendere molto facile appurare che l'argomento della nostra risposta sia quasi $180^ degree$. Anche con $ zeta =1$ l'argomento sarà circa $180^ degree$, ma solo per pulsazioni molto grandi, perché la parte reale tende a $ dfrac( omega^2, alpha_n^2)$, che è $O( dfrac( omega, alpha_n))$ (la parte immaginaria) per $ omega arrow infinity$. #cfigure("images/Diagramma_zeri_cc_neg_2.png", 73%) Nel diagramma di fase più $ zeta$ è piccolo e più la discontinuità da $0^ degree$ a $180^ degree$ è rapida. ==== Zeri complessi coniugati a parte reale positiva Consideriamo $G_d (j omega) = 1+ 2j zeta dfrac( omega, alpha_n) - dfrac( omega^2, alpha_n^2), quad zeta < 0$, una risposta con una coppia di zeri complessi coniugati a parte reale positiva. Il diagramma di fase di è speculare a quello precedente #cfigure("images/Diagramma_zeri_cc_pos_1.png", 73%) ==== Poli complessi coniugati a parte reale negativa <poli_complessi_coniugati_parte_reale_negativa> Consideriamo una risposta in frequenza con poli complessi coniugati a parte reale negativa $G_d (j omega) = dfrac(1,1+2j xi frac( omega, omega_n)- frac( omega^2, omega_n^2)), xi > 0$ #cfigure("images/Diagramma_poli_cc_neg_1.png", 63%) I diagrammi sono quelli precedenti ribaltati rispetto all'asse reale, infatti la retta del diagramma di ampiezza asintotico dopo la pulsazione $ omega_n$ ha pendenza $-40$ dB/dec. Il picco di risonanza si trova alla pulsazione (di risonanza) $ omega_r = omega_n sqrt(1-2 xi^2)$ con $|G_d (j omega_r)| = dfrac(1,2|xi| sqrt(1-2 xi^2))$; alla frequenza $ omega_n$ si ha $|G_d (j omega_n)| = dfrac(1,2|xi|)$ Soffermiamoci un attimo sul caso in cui $ xi arrow 0$: se do una sinusoide con frequenza inferiore a $ omega_n$ essa non viene sfasata; se invece la sua frequenza è di poco superiore a $ omega_n$ la sua fase viene sfasata di $90^ degree$; il modulo viene amplificato di molto se la frequenza della sinusoide è nell'intorno di $ omega_n$. ==== Poli complessi coniugati a parte reale positiva Consideriamo una risposta in frequenza con una coppia di poli complessi coniugati a parte reale positiva #tageq($G_d (j omega) = frac(1,1+2j xi frac( omega, omega_n) - frac( omega^2, omega_n^2))$, $ xi < 0$) Calcoliamo i poli $ G_d (s) =& frac(1,1+2 frac( xi, omega_n)s + frac(s^2, omega_n^2)) \ =& frac( omega_n^2,s^2+2 xi omega_n s + omega_n^2) \ ==>& p_(1 slash 2) = - xi omega_n plus.minus j omega_n sqrt(1 - xi^2) $ #cfigure("images/Diagramma_poli_cc_pos.png", 68%) Diagramma ottenuto da quello degli zeri (caso $ zeta<0$) ribaltando rispetto all'asse reale. === Esame 14/09/2021 #cfigure("images/Esame_14-09-2021.jpg",43%) #cfigure("images/Screenshot_20240904-100842.png", 55%) #set enum(numbering: "1)") + Usiamo la sovrapposizione degli effetti per calcolare $v_O$ #circle(radius: 7pt)[#set align(center + horizon) 1] $v_a != 0, v_B = 0 $\ \ $ space space underbrace(v_(O_1) &= dfrac(R_2,R_1) dot v_a, "amplificatore lineare " \ "invertente") space space underbrace(v_("OUT"_A) &= - dfrac(R_4,R_3) dot v_(O_1) , "amplificatore lineare" \ "invertente") = dfrac(R_4,R_3) dot dfrac(R_2,R_1) dot v_A $ #circle(radius: 7pt)[#set align(center + horizon) 2] $v_a = 0, v_B != 0 $\ $ space space v_(O_1) = 0 space space wide underbrace(v_("OUT"_B) = (1 + dfrac(R_4,R_3) dot v_B), "amplificatore lineare" \ "non invertente") = dfrac(R_3 + R_4,R_3) dot v_B $ $ v_"OUT" = v_("OUT"_A) + v_("OUT"_B) = colpurp( dfrac(R_4,R_3) dot dfrac(R_2,R_1) ) dot v_A + colpurp( dfrac(R_3 + R_4,R_3) ) dot v_B $ + #text(fill: purple, size: 12pt)[Sommatore tra $v_A$ e $v_B$]\ Si eguagliano i coefficienti davanti a $v_A$ e $v_B$ $ colpurp( dfrac(R_4,R_3) dot dfrac(R_2,R_1) ) = colpurp( dfrac(R_3 + R_4,R_3) ) &==> dfrac(40 k ohm dot 40 k ohm, 10 k ohm dot R_1) = (10 k ohm + 40 k ohm, 10 k ohm ) \ &==> dfrac(160 k ohm, R_1) = 5 k ohm \ &==> R_1 = dfrac(150,5) k ohm = 32 k ohm $ === Esame 28/01/2021 #cfigure("images/Esame_28-01-2021.jpg", 45%) #cfigure("images/Screenshot_20240904-113654.png", 35%) + Usiamo la sovrapposizione degli effetti per calcolare $v_0$ #circle(radius: 7pt)[#set align(center + horizon) 1] $v_a != 0, v_B = 0 $, abbiamo come $"OPAMP"_1$ un FOLLOWER e come $"OPAMP"_2$ un NON INVERTENTE \ #cfigure("images/ResizedImage_2024-09-04_11-47-37_2619.png",45%) $ space space underbrace(v_x &= 0, "follower spento") space space v_y &= (1 + dfrac(20 R,10 R) ) dot v_A \ &= 3 v_A $ $ i_(0_1) = dfrac(3v_A,R) $ #circle(radius: 7pt)[#set align(center + horizon) 2] $v_a = 0, v_B != 0 $, abbiamo come $"OPAMP"_1$ un FOLLOWER e come $"OPAMP"_2$ un INVERTENTE \ #cfigure("images/ResizedImage_2024-09-04_11-49-06_2358.png",45%) $ space space underbrace(v_x = v_B, "follower acceso") space space wide v_y = - dfrac(20 R,10 R) dot v_x &= dfrac(R_3 + R_4,R_3) dot v_B \ &= - dfrac(20 R,10 R) dot v_B \ &= -2 v_B $ $ v_y - v_x - v_(0_2) = 0 ==> v_(0_2) = v_y - v_x $ $ i_(0_2) &= dfrac(v_y - v_B, R)\ &=dfrac(-2 v_B - v_B, R)\ &= - dfrac(3v_b,R) $ $ i_0 = i_(0_1) + i_(0_2) &= dfrac(3v_A,R) - dfrac(3v_b,R)\ &= dfrac(3v_A - 3v_b,R)\ &= dfrac(3,R) (v_A - v_B) $ + #text(fill: purple, size: 12pt)[Modulo massimo corrente]\ $ i_("OUT"_"MAX") = i_0 + i_1 &= dfrac(3,R) (v_A - v_B) + dfrac(3v_a - 2v_B - v_A,20R)\ &= dfrac(1,R) ( dfrac(30v_A - 30 v_B +v_A - v_B,10) )\ &= dfrac(31,10R) (v_A - v_B) $ Adesso, siccome il testo dell'esercizio ci dice che $v_A$ e $v_B$ possono assumere valori all'interno dell'intervallo $[-2V .. thin 2V]$, impostiamo i seguenti valori: $v_A = 2V$, $v_B = -2V$ $ i_("OUT"_"MAX") = dfrac(31,10R) dot 4 V\ &= dfrac(124 V,10 R)\ &=1,24 dot 10^(-4) A \ &= 12,4 thin m A $ === Esame 08/02/2021 (Diagramma di Bode standard + saturazione) #cfigure("images/Esame_08-02-2021_Disegno_1.png",40%) Dati: $ R_1 &= 10 k ohm &space space R_2 &= 90 k ohm \ C &= 180 p F & L_+=L_- &= 10V $ #text(fill: purple, size: 12pt)[1) Calcolo funzione di trasferimento]\ È stata ricavata la seguente funzione di trasferimento $ H(j omega) = dfrac( 1+ dfrac( j omega C R_2, 10 ),1 + j omega C R_2 ) $ Calcoliamo i valori della funzione di trasferimento a $0$ e a $+ infinity$ $ omega -> 0 ==> H(j omega) = 10 space space omega -> + infinity ==> H(j omega) = 1 $ e trasformiamo tali valori in dB $ abs(10)_"dB" = 20 "dB" space space abs(1)_"dB" = 0 "dB" $ Ora si calcolano le pulsazioni di taglio del polo e dello zero $ omega_z = 10/(C R_2) = 617 thin k"rad/"s space space omega_p = 1/(C R_2) = 61,7 thin k"rad/"s $ #cfigure("images/Esame_08-02-2021_Disegno_2.png",50%) Per il diagramma delle fasi teniamo a mente che - uno #text(fill: green)[zero] negativo aumenta la fase di $90 degree$ - un #text(fill: red)[polo] negativo abbassa la fase di $90 degree$ - lo scostamento di fase avviene tra metà decade prima e metà decade dopo la pulsazione di taglio - se il guadagno è positivo, il diagramma parte da $O degree$, se negativo parte da $- pi /2$ 2) Calcolare il minimo valore di $R_L$ che garantisce staticamente la non saturazione dell'OPAMP sapendo che questo può erogare massimo $plus.minus 10 m A$ in uscita. Siccome siamo in condizioni statiche $C$ è un circuito aperto, quindi il nostro circuito diventa #cfigure("images/Esame_08-02-2021_Disegno_3.png",37%) Abbiamo un OPAMP non invertente, quindi $ v_"OUT" = (1 + R_1/R_2) dot v_"IN" ==> v_"IN" = dfrac(R_1,R_1+R_2) dot v_"OUT" $ Siccome non deve raggiungere la saturazione, dobbiamo considerare $v_"OUT" = plus.minus 10 V$; troviamo la formula per $i_"OUT"$, che sappiamo dalla consegna che deve essere $10 m A$ $ i_"OUT" = i_1 + i_(R_L) =& dfrac( v_"OUT" , R_1 + R_2 ) + v_"OUT"/R_L \ ==>& R_L = dfrac( v_"OUT", i_"OUT" - dfrac( v_"OUT" , R_1 + R_2 ) ) $ === Esame 17/06/2021 (Diagramma di Bode) #cfigure("images/Esame_17-06-2021.jpg", 60%) #cfigure("images/Esame_17-06-2021_Disegno_1.png", 60%) #enum( enum.item(1)[ #text(fill: purple, size: 12pt)[Calcolo funzione di trasferimento]\ OPAMP ideale ($L_+ = L_- = 0$) e in alto guadagno ($v_0=0$), quindi il circuito è lineare, e quindi si può applicare la sovrapposizione degli effetti. #circle(radius: 7pt)[#set align(center + horizon) 1] $v_a != 0, v_B = 0 ==>$ Filtro attivo passa basso\ #cfigure("images/Esame_17-06-2021_Disegno_2.png", 60%) $ v_"OUT"_1 &= - dfrac(R,R) dot dfrac(1,1+ j omega C R) dot v_"IN" \ &= - dfrac(1,1+ j omega C R) dot v_"IN" $ #circle(radius: 7pt)[#set align(center + horizon) 2] $v_a = 0, v_B != 0 ==>$ OPAMP non invertente\ #cfigure("images/Esame_17-06-2021_Disegno_3.png",60%) $ dfrac(1,Z_2) &= dfrac(1,R) + j omega C \ &= dfrac(1+ j omega R C,R) ==> Z_2 = dfrac(R,1+ j omega R C) $ Per calcolare la tensione $v_"BB"$ si usa la formula del partitore di tensione $ v_"BB" = v_B dot dfrac(3R,3R+R) $ $ v_"OUT"_2 &= (1+ dfrac(Z_2,R) ) dot v_"BB" \ &= ( 1 + dfrac(Z_2,R) ) dot underbrace( v_B,v_"IN" ) dot underbrace( dfrac(3R, 3R + R), 3/4 ) \ &= dfrac(3,4) thin v_"IN" thin ( 1+ dfrac(1,1+j omega R C) ) $ $ v_"OUT" = v_"OUT"_1 + v_"OUT"_2 &= - dfrac(1,1+ j omega C R) dot v_"IN" + dfrac(3,4) thin v_"IN" thin ( 1+ dfrac(1,1+j omega R C) ) \ &= v_"IN" ( - dfrac(1,1+ j omega C R) + dfrac(3,4) + dfrac(3,4 thin (1+j omega R C)) ) \ &= v_"IN" ( dfrac(-4 + 3 (1+j omega R C) + 3, 4 thin (1 + j omega R C)) ) \ &= v_"IN" thin dfrac(2 + 3 j omega R C, 4 thin (1 + j omega R C)) \ &= v_"IN" dfrac(1 + 3/2 j omega R C, 2 thin (1 + j omega R C)) $ quindi $ H(j omega) = 1/2 thin dfrac(1 + 3/2 j omega R C, 1 + j omega R C) $ Ora dobbiamo disegnare il diagramma di Bode della funzione di trasferimento appena ricavata.\ Iniziamo con il diagramma del modulo:\ - la funzione ha uno #text(fill: green)[zero], rappresentato da $1 + 3/2 j omega R C$ - e un #text(fill: red)[polo], rappresentato da $1 + j omega R C$ Possiamo utilizzare due metodi per tracciare il diagramma del modulo: - tracciare il diagramma del modulo dello #text(fill: green)[zero] e del #text(fill: red)[polo] e "sommarli" - calcolare il valore di $H(j omega)$ per $omega -> 0$ e $omega -> + infinity$ e trasformarlo in decibel Di seguito li illustrerò entrambi. $ omega -> 0 ==> H(j omega) = 1/2 space space omega -> + infinity ==> H(j omega) = 3/4 \ abs(1/2)_"dB" = 20 log (1/2) = -6 space space abs(3/4)_"dB" = 20 log (3/4) = -2,5 $ Calcoliamo le pulsazioni di taglio di #text(fill: red)[polo] e #text(fill: green)[zero] $ omega_p &= dfrac(1,R C) &space space omega_z &= dfrac(1, 3/2 R C) \ &= 3030 "rad/"s & &=4545 "rad/"s \ &= 3 thin k"rad/"s & &=4,5 thin k"rad/"s $ Adesso possiamo disegnare il diagramma del modulo tenendo conto che prima di $omega_z$ vale $-6 "dB"$ e dopo $omega_p$ vale $-2,5 "dB"$, e che all'interno delle due pulsazioni di taglio aumenta con una pendenza di $20 "dB/dec"$ #cfigure("images/Esame_17-06-2021_Disegno_4.png",35%) Per quanto riguarda il diagramma della fase anche qui si può tracciare il diagrammi di #text(fill: red)[polo] e #text(fill: green)[zero] e sommarli ma, siccome le pulsazioni di taglio si trovano nella stessa fase, il diagramma risultante dalla somma sarebbe impreciso, quindi dobbiamo utilizzare un altro metodo. Calcoliamo l'argomento della nostra funzione di trasferimento $ arg( 1/2 thin dfrac( 1 + 3/2 j omega R C, 1 + j omega R C ) ) &= arg( 1 + 3/2 j omega R C ) - arg( 2 + 2 j omega R C ) $ $ arg( 1 + 3/2 j omega R C ) = arctan( 3/2 w R C) &= cases( 0 degree &wide omega << omega_z, 45 degree &wide omega = omega_z, 56 degree &wide omega = omega_p, 90 degree &wide omega >> omega_z ) \ arg( 1 + j omega R C ) = arctan( w R C) &= cases( 0 degree &wide omega << omega_p, -45 degree &wide omega = omega_p, -33 degree &wide omega = omega_z, -90 degree &wide omega >> omega_p ) $ quindi sommiamo tutte le quantità (tra l'altro si può immaginare senza difficoltà anche il valore che assume a metà tra le due pulsazioni di taglio) $ arg( 1/2 thin dfrac( 1 + 3/2 j omega R C, 1 + j omega R C ) ) &= cases( 0 degree &wide omega << omega_z wide omega << omega_p, 12 degree &wide omega = omega_z, 11.5 degree &wide omega = dfrac(omega_z + omega_p,2), 11 degree &wide omega = omega_p, 0 degree &wide omega >> omega_z wide omega << omega_p ) $ Quindi il diagramma delle fasi inizia metà decade prima di $omega_z$ a salire (da $0 degree$) fino a raggiungere il valore di circa $dfrac(pi,16)$ per tutto l'intervallo $[omega_z,omega_p]$, per poi scendere per metà decade dopo $omega_p$ e stabilizzarsi al valore $0 degree$. ], enum.item(2)[ #text(fill: purple, size: 12pt)[Calcolo $I_(O_"MAX")$]\ Siccome siamo in condizioni statiche il circuito con $C$ è aperto, e nella relazione tra $v_"IN"$ e $v_"OUT"$ $omega=0$ $ v_"OUT" = 1/2 thin v_"IN" $ $ v_"IN" = -5 V ==> v_"OUT" = -2,5 V space space v_"IN" = 5 V ==> v_"OUT" = 2,5 V $ $ I_O = i_1 + I_L &= dfrac( v_"OUT"- v_"IN" , 2R ) + dfrac( v_"OUT", R_L )\ &= 0,01654 thin A\ &= 16,54 thin m A $ ] ) /* === Esercizio diagramma di Bode con OPAMP non ideale Questo esercizio specifica di tracciare anche il diagramma di Bode considerando l'OPAMP non ideale, quindi ci da il #text(fill: purple)[prodotto guadagno-banda finito dell'OPAMP] $ A_v dot B = 1 M"Hz" $ che bisogna trasformare in rad/s (basta moltiplicare per $2 pi$) $ A_v dot B = 6,28 "rad/"s #colred($:= omega_T$) $ dove $omega_T$ è la #text(fill: red)[posizione della pulsazione al guadagno di taglio]. Prima si traccia il grafico del circuito ideale, dopo si modifica tale grafico in base alla pulsazione del guadagno di taglio. In particolare, per il diagramma del modulo, bisogna considerare una retta con pendenza $-20 "dB/dec"$ che interseca l'asse $log omega$; dopo il punto di intersezione tra il diagramma ideale e la retta, il diagramma reale segue l'andamento della retta; per il diagramma della fase, metà decade prima di $omega_T$ vi è uno sfasamento di $90 degree$. #cfigure("images/Esercizio_Bode_non_ideale.png",60%) Abbiamo la seguente funzione di trasferimento $ H(j omega) = - 30 thin dfrac( 1+j omega C thin 35/3 thin R , 1+ j omega C thin 50 thin R ) $ $ omega -> 0 ==> H(j omega) = -30 space space omega -> + infinity ==> H(j omega) = -5 \ abs(-30)_"dB" = 20 log (1/2) = 29 space space abs(-5)_"dB" = 20 log (3/4) = 14 $ */ === Esercizio Diagramma di Bode non ideale #cfigure("images/Esercizio_2_Bode_non_ideale.png",70%) *Amplificatore invertente* $ v_O_1 = - dfrac(R_2,R_1) dot v_"IN" $ *Filtro attivo passa basso* $ v_O_2 = - dfrac(R_1,R_2) dot dfrac(1,1+j omega C R_4) dot v_"IN" $ Applico la sovrapposizione degli effetti #circle(radius: 7pt)[#set align(center + horizon) 1] $v_O_1 != 0, v_O_2 = 0 $\ $ v_"OUT"_1 = - dfrac(R_6,R_5) dot v_O_1 &= dfrac(R_6,R_5) dot dfrac(R_2,R_1) dot v_"IN" \ &= 200 dot v_"IN" $ #circle(radius: 7pt)[#set align(center + horizon) 2] $v_O_1 = 0, v_O_2 != 0 $\ Per calcolare $v_22$ utilizziamo la formula del partitore di tensione $ v_22 = v_O_2 dot dfrac(R_8,R_7+R_8) $ $ v_"OUT"_2 = (1 + R_6/R_5) dot v_22 &= (1 + R_6/R_5) (dfrac(R_8,R_7+R_8)) dot v_O_2 \ &= (1 + (20 cancel(R))/cancel(R)) (dfrac(R,6 R + R)) dot v_O_2 \ &=(1+20) dot 1/7 dot v_O_2 \ &= 3 v_O_2 $ $ v_"OUT"_2 = -180 dot dfrac(1,1+j omega C R_4) dot v_"IN" $ $ v_"OUT" = 200 dot v_"IN" - 180 dfrac(1,1+j omega 60 C R) dot v_"IN" = 20 dfrac(1 + j omega 600 C R, 1 + j omega 60 C R) dot v_"IN" $ $ H(j omega) = 20 dfrac(1 + j omega 600 C R, 1 + j omega 60 C R) $ Questo esercizio specifica di tracciare anche il diagramma di Bode considerando l'OPAMP non ideale, quindi ci da il #text(fill: purple)[prodotto guadagno-banda finito dell'OPAMP] $ A_v dot B = 1 M"Hz" $ che bisogna trasformare in rad/s (basta moltiplicare per $2 pi$) $ A_v dot B = 6,28 "rad/"s $ da cui si ricava $omega_H$, cioè la posizione della pulsazione al guadagno di taglio $ omega_H = dfrac(A_v dot B, abs(mu dot dfrac("coeff zero", "coeff polo") )) $ Prima si traccia il grafico del circuito ideale, dopo si modifica tale grafico in base alla pulsazione del guadagno di taglio. In particolare, per il diagramma del modulo, bisogna considerare una retta con pendenza $-20 "dB/dec"$ che interseca l'asse $log omega$; dopo il punto di intersezione tra il diagramma ideale e la retta, il diagramma reale segue l'andamento della retta; per il diagramma della fase, metà decade prima di $omega_T$ vi è uno sfasamento di $90 degree$. $ w -> 0 ==> H(j omega) tilde 20 = 26 "dB" space space w -> + infinity ==> H(j omega) tilde 200 = 46 "dB" $ $ omega_z = dfrac(1,600 C R)= 297,6 "rad/"s space space omega_p = dfrac(1,60 C R)= 2976 "rad/"s \ omega_H = dfrac(A_v dot B, abs(20 dot 600/60))= 31,4 thin k"rad/"s $ #cfigure("images/Esercizio_2_Bode_non_ideale_2.png",80%) === Esame 09/11/2021 (frequenza di taglio) Dal seguente circuito si calcolino i valori di $R_1$ e $R_2$ in modo che la frequenza di taglio sia $20 "Hz"$ e il guadagno in centro banda risulti pari a 10. Si supponga l'OPAMP ideale e in alto guadagno. #cfigure("images/Esame_9-11-2021_Disegno_1.png", 55%) Dati: $ R_3 &= 9 thin k ohm &space f_T &= 20 "Hz" \ C &= 1 thin mu F & A_(v_"CB")&= 10 \ L_+ = - L_- &= 10 V $ #text(fill: green, size: 12pt)[OPAMP non invertente] $ v_"OUT" &= (1+ R_3/R_2) dot v_x \ &= ( dfrac( R_2 + R_3, R_2 ) ) dot v_x $ #text(fill: purple, size: 12pt)[Partitore di tensione] $ v_x &= v_"IN" dot dfrac( R_1, Z_C + R_1 ) \ &= v_"IN" dot dfrac( R_1, dfrac(1,j omega C) + R_1 ) \ &= v_"IN" dot dfrac( R_1, dfrac(1 + j omega C R_1,j omega C)) \ &= v_"IN" dot dfrac( j omega C R_1, 1 + j omega C R_1 ) $ Quindi la funzione di trasferimento è: $ H(j omega) = underbrace( dfrac(R_2 + R_3, R_2) , mu ) dot dfrac( j omega C R_1, 1 + j omega C R_1 ) $ $ abs(A_(v_"CB"))_"dB" = 20 log_10 (10) = 20 "dB" $ #cfigure("images/Esame_9-11-2021_Disegno_2.png", 45%) $ omega_T = 1/(R_1 C) space omega_T = 2 pi f_T wide ==> wide R_1 = 1/(omega_T C) &= dfrac(1,2 pi f_T C) \ &= dfrac( 1 , 2 pi dot 20 "Hz" dot 1 times 10^(-6) F ) \ &= 7,96 thin k ohm $ $ abs(A_(v_"CB"))_"dB" = mu = dfrac(R_2 + R_3 , R_2) = 10 ==> &R_2 + R_3 = 10 dot R_2 \ &R_2 - 10 dot R_2 = - R_3 \ &-9 dot R_2 = - R_3 \ &9 R_2 = R_3 \ &R_2 = R_3/9 = 1 thin k ohm $ === Esame 30/06/2021 (grafico corrente) Si deve tracciare nel piano la relazione $I_"IN""-"I_"OUT"$ per $I_"IN" in [-10 m A thin .. thin 10 m A ]$. La relazione trovata è $ I_"OUT" = -0,1 dot I_"IN" + 0,4 m A $ Calcoliamo i valori interessanti di $I_"OUT"$ in relazione a $I_"IN"$ e in relazione ai valori di saturazione $L_+ = L_- = 10 V$, tenendo conto che $v_"OUT" = - 1 k ohm dot I_"IN" + 4 V$ $ I_"IN" &= -10 m A &space space I_"OUT" &= 1,4 m A \ I_"IN" &= 10 m A & I_"OUT" &= -0,6 m A \ I_"IN" &= 0 m A &space space I_"OUT" &= 0,4 m A \ L_+: space - 1 k ohm dot I_"IN" + 4 V &=10 V & I_"IN" &= -6 $ #cfigure("images/Screenshot_20240910-101122.png",55%) == D === Formule notevoli $ C_(min) = "Cox" dot L_(min)^2 dot ("SP" + "SN") \ ln(2) dot R_("eq") dot C_"INV" <= t \ "Resistenza equivalente pull-up" space R_("eq P") &= t_("LH")/(ln(2) dot C_(min)) wide R_("eq P") = dfrac(t_"LH",ln(2) dot C_"INV") \ "Resistenza equivalente pull-down" space R_("eq N") &= t_("HL")/(ln(2) dot C_(min)) wide R_("eq N") = dfrac(t_"HL",ln(2) dot C_"INV") \ R_(P n) &= (R_("eq P") - dfrac(R_("RIF" P),S_P) dot N )/K \ "Per percorsi critici" space R_P &= R_("eq P")/K\ S_(P) &= R_("RIF" P)/(R P) $ *Note:* - $ln(2) = 0,69$ - la $S_P$ che compare nella formula di $R_(P n)$ è sempre quella del percorso critico - $t_("LH")$ è il tempo di salita e $t_("HL")$ è il tempo di discesa. In generale negli esercizi se chiede di "dimensionare affinché il tempo di salita al nodo $X$ sia inferiore o uguale a $Y p s$" vuol dire che prenderemo $t_("LH") = Y$. - $p s$ sono pico secondi - quando non vengono dati SP e SN utilizzare le altre formule della resistenza equivalente === Regole generali per la rete di pull-up e pull-down Abbiamo questa rete #cfigure("images/240909_18h24m35s_screenshot.png",30%) Conoscendo la funzione $O$, e sapendo che $X = overline(O)$: - la rete di pull-up sarà uguale a la $X$, senza il negato e con somma e prodotto invertiti - la rete di pull-down sarà uguale a la $X$ senza il negato - gli elementi in serie sono il prodotto booleano degli elementi - gli elementi in parallelo sono la somma booleana deli elementi Se la $O = overline(A overline(C) + C overline(A) + B overline(D))$, allora $ X = overline(O) &= overline( overline(A overline(C)) dot overline(C overline(A)) dot overline(B overline(D)) ) \ &=overline( (overline(A) + C) dot (overline(C) + A) dot (overline(B) + D) ) $ Rete di pull-up: $ overline(A) C + overline(C) A + overline(B) D $ Rete di pull-down: $ (overline(A) + C) dot (overline(C) + A) dot (overline(B) + D) $ #cfigure("images/240909_18h34m03s_screenshot.png",40%) === Esame 14/06/2023 + Della rete in figura si calcoli l'espressione booleana al nodo O. + Dimensionare i transistori pMOS affinché il tempo di salita al nodo F sia inferiore o uguale a 90ps. Ottimizzare il progetto. Si tenga conto che i transistori dell'inverter di uscita hanno le seguenti geometrie : Sp = 200, Sn = 100. + Progettare la PDN #cfigure("images/2024-08-02-17-44-29.png", 40%) *Parametri tecnologici:*\ $ &R_("RIF" P) = 10 k ohm space "si riferisce alla rete di pull-up" \ &R_("RIF" N) = 5 k ohm space "si riferisce alla rete di pull-down"\ &"Cox" = 7 f\F \/ mu m^2\ &L_(min) = 0,25 mu m\ &"Vdd" = 3V $ *N.B.* I #text(fill: red)[numeri rossi] indicano la dimensione massima che possono assumere i transistor\ Per prima cosa si calcola $C_(min)$ $ C_(min) &= "Cox" dot L_(min)^2 dot ("SP" + "SN") \ &= 7 f\F \/ mu m^2 dot (0,25 mu m)^2 dot (200 + 100) \ &= 131,35 f F $ Poi la resistenza equivalente $ R_("eq P") = t_("LH")/(ln(2) dot C_(min)) &= (90 thin p s)/(0,69 dot 131,25 thin f F) \ &=(90 dot 10^(-12) s)/(0,69 dot 131,25 dot 10^(-15))\ &=0,99378 dot 10^3 thin ohm \ &=993,79 thin ohm\ &= 994 thin ohm $ Per *dimensionare* si divide $R_("eq P")$ per il numero di transistor nel percorso critico.\ *Percorso critico:* percorso da $V_(c c)$ all'estremità in cui ci sono più transistor in serie (quando si considera il maggior numero di transistor in serie questi possono avere paralleli). Il percorso critico è anche il percorso con NMOS maggiore. + *Espressione booleana* *Regole:* - Gli elementi in serie sono il prodotto booleano degli elementi - Gli elementi in parallelo sono la somma booleana deli elementi PD := rete di pull-down \ PU := rete di pull-up Rete di pull-up al nodo $F$: $ P U = ((C dot B) + overline(A)) dot C + A dot overline(C) = F $ La rete di pull-down si calcola invertendo somma e prodotto e negando poi tutta l'espressione Scriviamo $F$ in forma negata $ F &= overline( (((C + B) dot overline(A)) + C) dot (A + overline(C))) $ allora $ O = overline(F) &= overline( overline( (((C + B) dot overline(A)) + C) dot (A + overline(C))) ) \ &= overline( ((( overline(C) dot overline(B)) +A) dot overline(C)) + (overline(A) dot C)) $ + *Dimensionare i transistor* *Primo caso peggiore* Si calcola la $R P$, che solo per il percorso critico vale $(R_("eq P"))/("nMOS")$. In questo caso il percorso critico è $X B C$; la $X$ sta a significare che il valore di $A$ non ci interessa. $ R_(P) &= (994 thin ohm)/3\ &=331,33 thin ohm \ &= 331 thin ohm $ Quindi ora calcoliamo la $S P$ con la formula $ S_P = (R_("RIF P"))/(R_P) &= (10 thin k ohm)/(331 thin ohm)\ &= 30,21\ &= 31 $ *N.B.* Arrotondare sempre all'intero successivo *Secondo caso peggiore* Per ottimizzare un percorso non critico si ha una formula che varia in base alle caratteristiche del percorso stesso $ R_P = (R_("eq P") - dfrac(R_("RIF" P),S P) dot N )/K $ dove $N$ è il numero di MOS del percorso critico che interessano anche un percorso non critico e $K$ è il numero di MOS del percorso non critico cosiddetti "nuovi", cioè che non fanno parte del percorso critico. Inoltre $K+N$ è il numero di MOS del percorso non critico; quando si devono calcolare $K$ e $N$ di solito si calcola prima $K$ e poi si ricava $N$ dall'ultima formula. In questo caso consideriamo $A X overline(C)$. Abbiamo 2 pMOS nuovi e nessun pMOS del percorso critico, quindi $N=0$ e $K=2$ $ R_(P 2) = (R_("eq P") - cancel(dfrac(R_("RIF" P),S P) dot overbrace(N, 0)) )/K &= 994/2 thin ohm\ &= 497 thin ohm $ $ S P_2 = (R_("RIF P"))/(R_(P 2)) &= (10000 thin ohm)/(497 thin ohm)\ &=20,12\ &=21 $ *Terzo caso* Consideriamo il percorso $overline(A) thin overline(B) C$. Abbiamo un nMOS nuovo e un nMOS del percorso critico, quindi $N=1$ e $K=1$.\ *N.B.* Bisogna specificare $overline(B)$ e non $X$ perché si deve considerare solo il percorso di $overline(A) C$, e se $B$ fosse accesso il percorso sarebbe diverso. $ R_(P 3) = (R_("eq P") - dfrac(R_("RIF" P),S P) dot N)/K &= (994 thin ohm - dfrac(10000 thin ohm,31) dot 1)/1\ &=994 thin ohm - 323 thin ohm \ &= 671 thin ohm $ $ S P_2 = (R_("RIF P"))/(R_(P 2)) &= (10000 thin ohm)/(671 thin ohm)\ &=14,9\ &=15 $ *Nota:* le $S_P$ trovate denotano la dimensione massima dei transistori che interessano il percorso; in particolare si assegna prima la dimensione ai transistori presenti nel percorso critico, poi agli altri, in modo che il valore trovato per un transistori del percorso critico sia dominante rispetto al valore trovato per lo stesso transistore per un percorso non critico. + *Progettare la PDN* La formula della rete di pull-down è la seguente (prima l'abbiamo calcolata scrivendola in forma negata) $ P D = (((C+B) dot overline(A)) + C) dot (A+overline(C)) $ quindi, seguendo le regole dell'algebra booleana, la rete può essere rappresentata come segue #cfigure("images/Screenshot_20240806-182202.png",40%) === Esame 12/06/2024 + Determinare l'espressione booleana al nodo O + Dimensionare i transistori nMOS e pMOS in modo che i tempi di salita e discesa, al nodo F, siano inferiori o uguali a $100 thin p s$. Si ottimizzi il progetto per minimizzare l'area occupata da tutti i transistori. Si tenga conto che i transistori dell'inverter di uscita hanno le seguenti geometrie : $S_P=300$, $S_n= 150$. *Parametri tecnologici:* $ R_("rif" p) &= 10 thin k ohm \ R_("rif" n) &= 5 thin k ohm \ C_(o x) &= 7 thin f F \/mu m^2 \ L_(min) &= 0,25 thin mu m \ V_(C C) &= 3,3 V $ #cfigure("images/2024-08-07-16-26-24.png", 45%) + *Espressione booleana* $ "PD" = ( (C+B) dot (A+D) dot (B+ overline(C)) ) dot "CLK" + overline("CLK") $ Nota: Il CLK non negato è in serie con il resto del circuito della rete di pull-down, quello negato è in parallelo a tutta la rete di pull-down. $ "F" = overline("PD")\ "O" = overline("F") = overline(overline("PD")) \ "O" = overline(overline("PD")) $ quindi $ "O" &= overline(overline(( (C+B) dot (A+D) dot (B+ overline(C)) ) dot "CLK" + overline("CLK"))) \ &= overline(( (overline(C) dot overline(B)) + (overline(A) dot overline(D)) + (overline(B) dot C) + overline("CLK") ) dot "CLK" ) $ + *Dimensionare transistori nMOS e pMOS* - Rete pull-up\ C'è solo un CLK nella rete di pull-up, quindi $K=1$ $ space space R_P = dfrac(R_("eq" P), K) = 736 thin ohm space S_P = dfrac(R_("RIF" P), R_P) &= dfrac(10000 thin ohm, 736 thin ohm)\ &= 13,58\ &= 14 $ - Rete pull-down In questo caso ci sono diversi percorsi critici: - $A B C overline(D)$ - $overline(A) B C D$ - $A B overline(C) overline(D)$ - $overline(A) B overline(C) D$ Il numeri di MOS in un percorso non è sempre un intero, infatti, se ci sono dei transistor in parallelo, il numero di MOS corrispondente è uguale a $dfrac(1,"numero di transistor in parallelo")$ #cfigure("images/Screenshot_20240807-163312.png", 70%) Quindi per tutti i percorsi critici individuati $K=3,5$ $ R_N = dfrac(R_("eq" N),K) &= dfrac(736 thin ohm,3.5) &space S_N = dfrac(R_("RIF" N), R_N) &= dfrac(5000 thin ohm,210 thin ohm) \ &= 210 thin ohm &space &=24 $ Tutti i transistori della rete pull-down avranno quindi dimensione 24 #cfigure("images/2024-08-07-18-12-47.png", 50%) === Esame 28/01/2021 2) $ t_"LH" = t_"HL" = 100 p s $ $ R_("EQ"_N) = dfrac(t_"HL", ln (2) dot C_"INV") &= dfrac(100 dot 10^(-12) s , 0.69 dot 90 dot 10^(-15) ) \ &= 1610 ohm $ *Primo caso peggiore - percorso critico $bold( overline(A) B C overline(D) "CLK" )$* In questo caso $K = 4$ (numero di nMOS) $ R_N = R_"EQ"_N/K &= dfrac( 1610 ohm , 4 ) &space space S_N &= dfrac( 5000 ohm , 402.5 ohm ) \ &= 402.5 ohm & &=12.43 tilde.equiv 13 $ *Secondo caso peggiore $bold( A overline(B) overline(C) D "CLK" )$* $ K = 2, N = 1$ $ R_N_2 = dfrac( R_"EQ"_N - R_"RIF"_N/S_N dot N,K ) &= dfrac( 1610 ohm - dfrac( 5000 ohm,13 ), 2 ) &space space S_N &= dfrac( 5000 ohm , 612.7 ohm ) \ &= 612.7 ohm & &= 8.16 tilde.equiv 9 $ *Terzo caso peggiore $bold( A B overline(C) D "CLK" )$* Per passare per D bisogna "aprire" anche A, ma in questo modo la corrente, tra il percorso BD e il percorso A in parallelo, sceglie sempre di passare da A, perché fa un solo salto, e non passa mai da D. Per questo diamo a D la dimensione minima $ D = 1 $
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/literature-review/lsp.typ
typst
#import "/components/glossary.typ": gls == Language Server Protocol (LSP) In this section, we discuss the evolution of computer programming and the various development tools that have been used to enhance developer productivity. Among these tools, editors and #gls("ides") have become particularly prominent. Today, developers have a vast array of #gls("ides"), text editors, and source code editors to choose from. Given the importance of editing experience and tool familiarity, users often exhibit a strong preference for specific tools and are hesitant to switch. To address this challenge, tooling vendors began to support multiple programming and configuration languages @bib-lsp. #figure( image("/diagrams/generated/lsp/pre-lsp.svg", width: 80%), caption: [Language provider and tooling vendor relationship], ) <fig-pre-lsp> @fig-pre-lsp illustrates the traditional relationship between language providers and tooling vendors. When a tooling vendor implements language features such as diagnostics, auto-completions, and code navigation for a specific programming language, it requires significant effort. Different tools often employ disparate #gls("apis") to support these features, necessitating the consumption of programming language #gls("apis") for semantic and syntactic information. This frequently leads to redundant code implementation. To address this inefficiency, Microsoft introduced the #gls("lsp", mode: "full") as a standardized communication mechanism between language clients and language servers. Language servers, which provide language-specific intelligence, can be reused by multiple clients, eliminating the need for redundant implementation efforts. #figure( image("/diagrams/generated/lsp/lsp.svg", width: 80%), caption: [Language Server Protocol], ) <fig-lsp> @fig-lsp illustrates how a text editor, by implementing the #gls("lsp"), can support intelligent features for multiple programming languages. This capability is achieved by establishing a standardized communication channel between the editor and language-specific servers. The following subsections will delve deeper into the intricacies of the #gls("lsp"). === JSON-RPC The underlying base protocol of #gls("lsp") is built upon #gls("json-rpc") version 2.0. The #gls("lsp") two main components: the header and the content. These components will be elaborated on in the subsequent subsection @bib-jsonrpc. #gls("json-rpc") defines a set of #gls("json") data structures along with their associated rules. The specification outlines two primary data structures: - *Request object*: A client initiates a #gls("rpc") by sending a request object to the server. - *Response object*: The server responds to the client's #gls("rpc") call with a response object. ==== Request Object #figure( ```json { "jsonrpc": "2.0", "method": "textDocument/completion", "params": { "textDocument": { "uri": "file:///Users/user/hello/test.ungram" }, "position": { "line": 59, "character": 0 }, "context": { "triggerKind": 1 } }, "id": 10 } ```, caption: [Auto-completion Request Body Sent from Client to Language Server], ) <lst-req-cmp> @lst-req-cmp presents an example of a #gls("json-rpc") request sent from a client (editor/IDE) to a Language Server to request auto-completions at a specific position. The request object comprises the following fields: - *jsonrpc*: Specifies the #gls("json-rpc") protocol version used for communication. - *method*: Identifies the method to be invoked. Method names beginning with "RPC" are reserved for internal protocol methods and extensions. - *params*: Optional parameters for the method invocation. These parameters can be named or positional. - *id*: A unique identifier assigned by the client to correlate the request with its corresponding response. This field is optional and, if present, must be a string, number, or null. The request object can also be defined without the `id` field, in which case it represents a notification. Unlike requests, the server MUST NOT send a response to a notification. #figure( ```json { "jsonrpc": "2.0", "method": "textDocument/didOpen", "params": { "textDocument": { "uri": "file:///Users/user/hello/test.ungram", "languageId": "ballerina", "version": 1 } } } ```, caption: [DidOpen Notification Sent from the Client to the Language Server], ) <lst-req-open> @lst-req-open exemplifies a `textDocument/didOpen` notification sent from a client to a Language Server to inform the server about an opened document in the editor. ==== Response Object #figure( ```json { "jsonrpc": "2.0", "method": "textDocument/hover", "result": { "contents": { "kind": "markdown", "value": "Get a string result.\n \n \n--- \n \n### Returns \nstringReturned string value" } }, "id": 140 } ```, caption: [Hover Response Sent from the Language Server to the Client], ) <lst-res-hover> The response object contains the following fields. - *jsonrpc*: This is the #gls("json-rpc") protocol version used for the communication. - *result*: The result value is determined by the server as a response to a corresponding request method. This field MUST be included in a success scenario and MUST NOT be included in the error scenario. - *error*: While the result field is included in the success scenario, the error field is included in the erroneous scenario. In a response object, either the result or error fields MUST include and MUST NOT include both fields in the same response. - *id*: This is the identifier value of the response, and this should be the same as the id of the correlating request object. #figure( ```json { "jsonrpc": "2.0", "error": { "code": -32601, "message": "Method not found", "data": {} }, "id": "1" } ```, caption: [Method Not Found Error], ) <lst-res-err> @lst-res-err is an example error response sent for a request with a method that is not supported by the client or the server. An error object contains the following fields. - *code*: This value MUST be an integer value and represents the error type that occurred. We can read more on the error codes in the #gls("json-rpc") Specification. - *message*: This value SHOULD be a single sentence to represent the description of the error. - *data*: This optional field holds additional information about the error, and the value can be either primitive or structured. ==== Batch Batches allow the clients to send multiple requests to the server. Except for the notifications, the server MUST send back response objects to each of the request objects. The order of the response objects can differ from the order of the requests, and the requests and the corresponding responses should be correlated with the `id` @bib-jsonrpc. === Base Protocol The base protocol defines the header part and the content part. The header part consists of header fields, and the content part adheres to the #gls("json-rpc") format as described in the earlier section. The following is an example message sent from a client to a Language Server: #figure( ```json Content-Length: ...\r\n \r\n { "jsonrpc": "2.0", "id": 1, "method": ..., "params": { ... } } ```, caption: [Example of a Base Protocol message sent from a client to a Language Server], ) As per the example, the header part and the content part are separated by "\\r\\n". The header part and the content part have the following characteristics. ==== Header Part - The header field and the header value are separated by ": ". - A header field ends with a "\\r\\n". - The #gls("lsp") supports the `Content-Length` and the `Content-Type` header fields. ==== Content Part - This follows #gls("json-rpc") 2.0, and the `jsonrpc` field is set to 2.0 always. - #gls("utf8", mode: "short") is the default encoding. === Communication Model The #gls("lsp") is transport agnostic, allowing for communication over various protocols such as standard input/output or WebSocket. The protocol defines two primary interaction patterns: requests and notifications. Requests are client-initiated messages that expect a corresponding response from the server. Each request is uniquely identified by an `id` property to enable correlation. Notifications, on the other hand, are one-way messages sent by either the client or the server without requiring a response @bib-lsp. #figure( image("/diagrams/generated/lsp/lsp-seq-basis.svg", width: 80%), caption: [A sample use case of how the server initialization and handshaking are happening], ) The initial communication between the client and server is established through the `initialize` request. The client sends an `InitializeRequest` containing essential information such as process #gls("id"), root #gls("uri"), and client capabilities. The server responds with an `InitializeResult` that acknowledges the connection and provides server capabilities. Any requests sent before the `initialize` request or notifications sent before the server's response to the `initialize` request are considered invalid and may result in errors. This initialization phase is crucial for setting up the communication channel and exchanging necessary information between the client and server. Once the initialization sequence, consisting of the `initialize` request and its corresponding response, is complete, the client typically sends an `initialized` notification to signal readiness. Subsequently, the client informs the server about opened documents using the `textDocument/didOpen` notification. In response to this, the server might send `textDocument/publishDiagnostics` notifications to provide initial code analysis results. It's essential to note that notifications, unlike requests, do not expect a response. The #gls("lsp") places the responsibility of managing the server's lifecycle on the client. This implies that the client is tasked with initiating the server process, handling its communication, and ultimately terminating it when necessary. This architectural decision provides clients with greater control over server resource management and allows for more flexible integration strategies. Each message within the #gls("lsp") is identified by a unique method name, conforming to the #gls("json-rpc") protocol specification. While general messages follow standard naming conventions, most #gls("lsp") methods incorporate specific prefixes to categorize their functionality. ==== General Messages General messages, such as `initialize`, `initialized`, and `shutdown`, are core to the #gls("lsp") lifecycle and do not require a specific namespace prefix. These fundamental methods establish the initial connection and termination of the language server. ==== Prefix "\$/" Methods prefixed with `$/` are considered client or server specific extensions to the core LSP protocol. Examples include `$/cancelRequest` for canceling ongoing requests and `$/progress` for reporting progress updates. Implementations are not obligated to support these methods, and their usage should be carefully considered to avoid compatibility issues. ==== Prefix "window/" Methods prefixed with `window/` are designed to interact with the client's user interface. For instance, the `showMessage` notification displays a message within the editor's UI. These methods, including `showMessage`, `showMessageRequest`, and `logMessage`, will be explored in greater detail in subsequent chapters. ==== Prefix "telemetry/" Telemetry events, sent from the server to the client, provide insights into server-side operations. The `telemetry/event` method is used for this purpose. These events offer valuable information for monitoring, troubleshooting, and performance analysis. ==== Prefix "workspace/" Methods prefixed with `workspace/` pertain to workspace-level operations. The `workspace/applyEdit` request, for instance, allows the server to suggest and apply changes to multiple text documents within the workspace. Conversely, the `workspace/didChangeConfiguration` notification informs the server of changes to the workspace's configuration settings. These methods, along with others like `workspace/symbol` for workspace-wide symbol search, offer powerful capabilities for managing and understanding codebases. A deeper exploration of these workspace-related methods and their usage scenarios will be provided in subsequent chapters. ==== Prefix "textDocument/" Methods prefixed with `textDocument/` are associated with specific text documents. To identify the target document, a `uri` property is included within the method's parameters. For instance, the `textDocument/didOpen` notification provides the URI of the newly opened document. When positional information is required, such as for the `textDocument/definition` request, the `position` property within the parameters specifies the location within the document. These document-centric methods form the foundation for most language-aware features provided by language servers. The #gls("lsp") does not enforce strict ordering for requests, responses, and notifications. While clients and servers can process messages sequentially for simplicity, concurrent handling is also permissible. The `id` property is essential for correlating requests with their corresponding responses. To ensure correct behavior, implementations should consider the semantic dependencies between requests. For instance, a `textDocument/format` request might influence the results of a subsequent `textDocument/definition` request due to potential code changes. Therefore, careful handling of request and response ordering is crucial in certain scenarios.
https://github.com/imlasky/TOMLresume
https://raw.githubusercontent.com/imlasky/TOMLresume/main/README.md
markdown
# TOML Resume Create a nice looking resume with just some [TOML](https://toml.io). ## How to run yourself 1. Install [Typst](https://typst.app) 2. Open a new terminal window and `cd frontend && npm install` 3. Then `npm run dev` 4. Open a new terminal tab and `cd backend && python -m venv .env` 5. `source .env/bin/activate && pip install -r requirements.txt` 6. `uvicorn main:app --host 0.0.0.0 --port 80 --reload`
https://github.com/skriptum/diatypst
https://raw.githubusercontent.com/skriptum/diatypst/main/example/example.typ
typst
MIT License
#import "../src/lib.typ": * #show: slides.with( title: "Diatypst", // Required subtitle: "easy slides in typst", date: "01.07.2024", authors: ("<NAME>"), ) #outline() = First Section == First Slide Terms created with ```typc / Term: Definition``` / *Term*: Definition A code block ```python // Example Code print("Hello World!") ``` a table = Second Section == Summary #align(center+horizon)[_Le Fin_]
https://github.com/rabotaem-incorporated/algebra-conspect-1course
https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/04-linear-algebra/04-determinants.typ
typst
Other
#import "../../utils/core.typ": * == Определители #ticket[Определение определителя. Определитель транспонированной матрицы] #notice[ Мы знаем, что матрицы тесно связаны с системами линейных уравнений и мы хотим знать, когда системы разрешимы единственным образом, когда не имеют решений, и когда имеют бесконечно много решений. ] #def[ Системы линейных уравнений подразделяются на: - _Несовместные_ --- не имеют решений, - _Совместные определенные_ --- имеют единственное решение, - _Совместные неопределенные_ --- имеют бесконечно много решений. ] #example[ Рассмотрим систему с двумя неизвестными в общем случае. $ cases( a_(11) x_1 + a_(12) x_2 = b_1, a_(21) x_1 + a_(22) x_2 = b_2, ) $ Оказывается, что она совместима и определена тогда и только тогда, когда $ a_11 a_22 - a_21 a_12 != 0 $ Отсюда вытекает понятие определителя матрицы 2 на 2: $ det(a_11, a_12; a_21, a_22) = a_11 a_22 - a_21 a_12 $ ] #def[ Пусть $A in M_n (K)$, $K$ --- поле, $A = (a_(i j))$ _Определителем_ или _детерминантом_ $A$ называется $ Det(A) = abs(A) = limits(sum)_(sigma in S_n) sgn(sigma) a_(1 sigma_1) a_(2 sigma_2) ... a_(n sigma_n). $ ] #props[ 1. $det(A) = det(A^T)$ ] #proof[ $ det(A^T) = sum_(sigma in S_n) sgn sigma dot.c product_(i = 1)^n a_(underbrace(sigma(i) i, #[отраженные\ координаты])) &=\ sum_(sigma in S_n) sgn sigma dot.c product_(i = 1)^n a_(underbrace(i sigma^(-1)(i), #[то же самое\ в другом порядке])) &=\ sum_(sigma in S_n) sgn underbrace(sigma^(-1), #[то же самое\ в другом порядке]) dot.c product_(i = 1)^n a_(i sigma^(-1)(i)) &=\ sum_(sigma in S_n) sgn sigma dot.c product_(i = 1)^n a_(i sigma(i)) &= det(A).\ $ ] #ticket[Линейность определителя по строкам и столбцам] #props[ 2. $A = mat(delim: "[", A_1; dots.v; A_i' + A_i''; dots.v; A_n) ==> det(A) = det(A_1; dots.v; A_i'; dots.v; A_n) + det(A_1; dots.v; A_i''; dots.v; A_n)$ 3. $A = mat(delim: "[", A_1; dots.v; alpha A_i; dots.v; A_n) ==> det(A) = alpha det(A_1; dots.v; A_i; dots.v; A_n)$ 4. $A = mat(delim: "[", alpha A_1; dots.v; alpha A_i; dots.v; alpha A_n) ==> det(A) = alpha^n det(A_1; dots.v; A_i; dots.v; A_n)$ ] #proof[ 2. суммируем два определителя по $a_(i phi(i))$ 3. выносим $alpha$ за знак суммы из $a_(i phi(i))$ 4. через пункт 3 ] #ticket[Кососимметричность определителя по строкам и столбцам] #props[ 5. $A = mat(delim: "[", A_1; dots.v; A_n), A_i = A_j ==> det(A) = 0$ 6. $A = mat(delim: "[", A_1; dots.v; A_i; dots.v; A_n), B = mat(delim: "[", A_1; dots.v; A_i + alpha A_j; dots.v; A_n) ==> det(A) = det(B)$ 7. $A = mat(delim: "[", A_1; dots.v; A_i; dots.v; A_j; dots.v; A_n), B = mat(delim: "[", A_1; dots.v; A_j; dots.v; A_i; dots.v; A_n) ==> det(A) = -det(B)$ ] #proof[ 5. на любую перестановку $phi$ найдется парная, где поменяны $i$ и $j$, и определитель будет противоположным 6. $ det(B) = det(A) + alpha dot det(mat(delim: "[", A_1; dots.v; A_j; dots.v; A_j; dots.v; A_n)) = det(A) $ 7. аналогично пункту 5 ]
https://github.com/chillcicada/typst-dotenv
https://raw.githubusercontent.com/chillcicada/typst-dotenv/main/example/example.typ
typst
MIT License
#set page(width: auto, height: auto) #import "../lib.typ": parse_dotenv ```txt #import "../lib.typ": parse_dotenv #parse_dotenv("FOO = bar # this is a comment") ``` It will be parsed as: #parse_dotenv("FOO = bar # this is a comment") ````txt #let env_code = ```ini # this is a comment FOO = bar # this is also a comment ``` #let env = parse_dotenv(env_code) ```` #let env_code = ```ini # this is a comment FOO = bar # this is also a comment ``` #let env = parse_dotenv(env_code) The `env` will be: #env Or you can read the content from a .env file: ```txt // The path is relative to the current file #let env_raw = read("/.env") #let env = parse_dotenv(env_raw) ``` The `env` will be: #let env_raw = read("/.env") #let env = parse_dotenv(env_raw) #env
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/bugs/ts-intro.typ
typst
Apache License 2.0
by #text(fill: rgb("#3c9123"), "server") and #text(fill: blue, "browser"), there would be a data flow like this:
https://github.com/r8vnhill/apunte-bibliotecas-de-software
https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit1/Input.typ
typst
== Manejo de Entrada de Usuario en Kotlin La entrada de usuario es fundamental para los programas interactivos. Kotlin ofrece métodos convenientes y seguros para leer la entrada desde la consola, adaptándose a diversas necesidades de manejo de entrada. === Funciones de Lectura en Kotlin - *`readlnOrNull()`*: Esta función es la recomendada para leer una línea de entrada. Devuelve un `String?`, que será `null` si no hay más datos disponibles (por ejemplo, si el usuario no introduce nada y presiona Enter). Es segura porque permite manejar los casos de nulos de forma explícita y evita excepciones innecesarias. - *`readln()`*: Esta función ha sido deprecada en versiones recientes de Kotlin debido a que lanza una excepción si no hay más entrada disponible, lo cual puede conducir a interrupciones no manejadas en el flujo del programa. Se recomienda usar `readlnOrNull()` para evitar estos problemas y escribir un código más robusto y predecible. === Ejemplo de Uso de `readlnOrNull()` A continuación, se muestra cómo utilizar `readlnOrNull()` para leer nombres de usuario de manera segura, terminando cuando el usuario no ingresa ningún dato: ```kotlin fun main() { println("Introduce nombres. Presiona solo Enter para terminar.") while (true) { println("Ingresa un nombre:") val input = readlnOrNull() if (input.isNullOrEmpty()) { println("No se ingresó ningún nombre. Terminando el programa.") break // Interrumpimos el ciclo } else { println("Nombre ingresado: $input") } } } ``` *Explicación del Código*: - *Loop Infinito*: Se usa un ciclo `while(true)` para pedir repetidamente al usuario que ingrese datos. - *Lectura Segura*: `readlnOrNull()` se usa para leer la entrada. Si el usuario no introduce nada y presiona Enter, `input` será `null` o vacío, y el programa imprimirá un mensaje de salida y se terminará. - *Manejo de Entrada Válida*: Si el usuario proporciona una entrada, el programa la muestra y continúa pidiendo más nombres.
https://github.com/Meisenheimer/Notes
https://raw.githubusercontent.com/Meisenheimer/Notes/main/src/Graph.typ
typst
MIT License
#import "@local/math:1.0.0": * = Graph == Shortest Path == Matching == Network Flow == Tree
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/Presentations/Midpoint/flo-inspired.typ
typst
#import "@preview/polylux:0.3.1": * #polylux-slide[ = Flo inspired #v(1fr) - Blocks are distributed on canvas #v(1fr) - Connections are made with arrows #v(1fr) - Composition of one function at a time #v(1fr) - Parameters are defined in separate dialog #v(1fr) - Block types are displayed when hovering over a block #v(1fr) ] #polylux-slide[ = Simple Addition #grid( columns: 2, [ #v(1fr) - Function-block can only have one parameter #v(1fr) - Currying is shown with :apply blocks that "depend" on their main block #v(1fr) - Last block of a function (output) can be marked as function result #v(1fr) ], [ #image("static/flo-inspired-addition.png") ] ) ] #polylux-slide[ = Even One to Ten #grid( columns: 2, [ #v(1fr) - Parameter of "even" is auto-filled from list in filter function (symbolized by the color) #v(1fr) - Output block of "even" is ignored since the function is used as parameter #v(1fr) - Pre-defined list-construction block for list of numbers in range #v(1fr) ], [ #image("static/flo-inspired-evenOneToTen.png") ] ) ] #polylux-slide[ = Map-Add-5 #grid( columns: 2, [ #v(1fr) - Second parameter of plus-function is auto-filled from list in map function #v(1fr) ], [ #image("static/flo-inspired-mapAdd5.png") ] ) ] #polylux-slide[ = Product #v(1fr) - Match-block for pattern matching - One result per match-case - Recursion by usage of "product" block in definition of product #v(1fr) #image("static/flo-inspired-product.png", height: 65%) ]
https://github.com/KaiserY/mdbook-typst-pdf
https://raw.githubusercontent.com/KaiserY/mdbook-typst-pdf/main/README.md
markdown
Apache License 2.0
# mdbook-typst-pdf [中文版说明](README-cn.md) A [mdBook](https://github.com/rust-lang/mdBook) backend for generate pdf (through [typst](https://github.com/typst/typst)). For now the primary use case is convert [Rust 程序设计语言 简体中文版](https://kaisery.github.io/trpl-zh-cn) to PDF. It should work for other mdbook project, if not welcome to fire an issue. ## Installation - `cargo install mdbook-typst-pdf` - Or download from [releases](https://github.com/KaiserY/mdbook-typst-pdf/releases) ## Usage Add follow `[output.typst-pdf]` section to `book.toml` then `mdbook build` ```toml [book] ... [output.html] ... [output.typst-pdf] pdf = true # false for generate typ file only custom_template = "template.typ" # filename for custom typst template for advanced styling section-number = true # true for generate chapter head numbering chapter_no_pagebreak = true # true for not add pagebreak after chapter ``` ## Custom template see [src/assets/template.typ](https://github.com/KaiserY/mdbook-typst-pdf/blob/main/src/assets/template.typ) file for more details, for now there are two placeholders: - `MDBOOK_TYPST_PDF_TITLE` for title - `/**** MDBOOK_TYPST_PDF_PLACEHOLDER ****/` for content ## Demo PDF [Rust 程序设计语言 简体中文版.pdf](https://kaisery.github.io/trpl-zh-cn/Rust%20%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E8%AF%AD%E8%A8%80%20%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87%E7%89%88.pdf) ## Related projects - https://github.com/typst/typst - https://github.com/rust-lang/mdBook - https://github.com/lbeckman314/mdbook-latex - https://github.com/LegNeato/mdbook-typst
https://github.com/josephmullins/josephmullins.github.io
https://raw.githubusercontent.com/josephmullins/josephmullins.github.io/main/Mullins_CV.typ
typst
#import "@preview/basic-resume:0.1.3": * // Put your personal information here, replacing mine #let name = "<NAME>" #let location = "San Diego, CA" #let email = "mullinsj at umn dot edu" #let github = "github.com/josephmullins" #let linkedin = "linkedin.com/in/stuxf" #let phone = "+1 (347) 301-7771" #let personal-site = "josephlyonmullins.com" #let position = "Assistant Professor" #let inst = "University of Minnesota" #let dept = "Department of Economics" #show: resume.with( author: name, // All the lines below are optional. // For example, if you want to to hide your phone number: // feel free to comment those lines out and they will not show. email: email, github: github, phone: phone, personal-site: personal-site, accent-color: "#26428b", font: "Futura", ) /* * Lines that start with == are formatted into section headings * You can use the specific formatting functions if needed * The following formatting functions are listed below * #edu(dates: "", degree: "", gpa: "", institution: "", location: "") * #work(company: "", dates: "", location: "", title: "") * #project(dates: "", name: "", role: "", url: "") * #extracurriculars(activity: "", dates: "") * There are also the following generic functions that don't apply any formatting * #generic-two-by-two(top-left: "", top-right: "", bottom-left: "", bottom-right: "") * #generic-one-by-two(left: "", right: "") */ == Education #edu( institution: "New York University", dates: dates-helper(start-date: "2009", end-date: "2016"), degree: "Phd, Economics", ) Thesis title: "Behavioral Models of Child Development" #edu( institution: "University of Queensland", dates: dates-helper(start-date: "2004", end-date: "2009"), degree: "Bachelor of Economics (Hons)" ) #edu( institution: "University of Queensland", dates: dates-helper(start-date: "2004", end-date: "2009"), degree: "Bachelor of Arts, Double Major Mathematics" ) == Employment #work( title: "Assistant Professor", company: "University of Minnesota", dates: dates-helper(start-date: "2018", end-date: "Present"), ) Classes: - Applied Econometrics (PhD) - Advanced Topics in Labor Economics (PhD) - Introduction to Econometrics (Undergraduate) #work( title: "Assistant Professor", company: "University of Western Ontario", dates: dates-helper(start-date: "2016", end-date: "2018"), ) Classes: - Intermediate Econometrics (Undergraduate) - Applied Microeconometrics (Phd) #work( title: "Research Assistant", company: "New York University", dates: dates-helper(start-date: "2011", end-date: "2013"), ) #work( title: "Teaching Assistant", company: "New York University", dates: dates-helper(start-date: "2010", end-date: "2013"), ) Classes: - Econometrics I (PhD) - Econometrics II (PhD) - Introductory Microeconomics (Undergrad) == Working Papers / Under Revision + #cite(<CashTrasnfers>,form: "full") + #cite(<CLMP>,form: "full") + #cite(<FlinnMullins>, form: "full") + #cite(<MancinoMullins>,form: "full") == Publications + #cite(<MetaAnalysis>,form: "full") + #cite(<BFM>,form:"full") + #cite(<ier>,form: "full") == Refereeing Quarterly Journal of Economics, Journal of Political Economy, American Economic Review, Econometrica, Review of Economic Studies, International Economic Review, Journal of Labor Economics, Review of Eco- nomic Dynamics, Journal of Public Economics, European Economic Review, Scandinavian Journal of Economics, Labour Economics, American Economic Journal: Policy, Canadian Journal of Economics, Portuguese Economic Journal, Journal of Monetary Economics, Economic Journal, Theoretical Economics == Presentations and Seminars === 2024 OzMac: Australian Macroeconomic Workshop (keynote address),MEA Annual Meeting, SED Annual Meeting, University of Nebraska === 2023 AEA Annual Meeting, Junior Micro/Macro Labor Workshop at Columbia Business School, St Louis Fed, SED Annual Meeting, Duke, U Nebraska, CEHD (Chicago) === 2022 Stanford, SUNY Stony Brook, Rice U, U Montreal, U Essex, Paris School of Economics, Toulouse School of Economics, Barcelona Summer Forum - Structural Microeconometrics, Barcelona Summer Forum - Macro of Labour Markets, Melbourne University === 2021 University of Wisconsin - Madison, Dynamic Structural Econometrics Workshop (Bonn), Barcelona GSE Summer Forum Workshop on Structural Microeconometrics, SITE work- shop on Labor Markets, Virtual Australian Macro Seminar, MEA Annual Meeting === 2020 Search and Matching Virtual Congress, NBER Summer Institute Session on Children, Boston College === 2019 Workshop on “Aging, Family and Social Insurance” at University of Bergen, Workshop on Earnings, Risk, and Insurance at Institute for Fiscal Studies (discussant), NYU Workshop on Search and Matching, Penn State, UNC-Chapel Hill, Washington University in St Louis === 2018 Barcelona GSE Summer Forum, Vancouver School of Economics, Rochester University, Uni- versity of Pennsylvania, University of Oregon, University of Toronto, Dale Mortensen Con- ference on Search Frictions === 2017 Barcelona GSE Summer Forum, UM-MSU-UWO Labour Day, SoLE Annual Meetings, Queen’s University, Washington University in St Louis, Cowles Summer Conference: Struc- tural Microeconomics, University of Minnesota, York University === 2016 Barcelona GSE Summer Forum, NYU, McMaster University === 2015 SED Annual Meeting, Econometric Society World Congress == Academic Honors and Awards - Best Referee Award, Review of Economic Dynamics, 2021 - Excellence in Refereeing, Labour Economics, 2017 - Excellence in Refereeing, Labour Economics, 2016 - IES-PIRT Fellowship, 2014-2016 - MacCracken Fellowship, 2009-2014 - AEC Group Prize for Most Outstanding Overall Achievement, Honours Class, 2008 - ACCC Prize for Most Outstanding Microeconomics Thesis, 2008 - Prime Minister's Award for Academic Excellence, 2003 #show bibliography: none #bibliography("bibliography.bib", style: "chicago-author-date")
https://github.com/EstebanMunoz/typst-template-auxiliar
https://raw.githubusercontent.com/EstebanMunoz/typst-template-auxiliar/main/template/main.typ
typst
MIT No Attribution
#import "@local/fcfm-auxiliar:0.1.0": conf, subfigures, today // Parámetros para la configuración del documento. Descomentar aquellas que se quieran usar #let document-params = ( "title": "Título de clase auxiliar", "course-name": "Nombre curso", "course-code": "AB1234", "teachers": ("Profesor 1",), "auxiliaries": ("Auxiliar 1",), "assistants": ("Ayudante 1",), "date": today, "university": "Universidad de Chile", "faculty": "Facultad de Ciencias Físicas y Matemáticas", "department": "Departamento de Ingeniería Eléctrica", "logo": box(height: 1.57cm, image("assets/logos/die.svg")), ) // Aplicación de la configuración del documento #show: doc => conf(..document-params, doc) ////////// COMIENZO DEL DOCUMENTO ////////// + + +
https://github.com/storopoli/invoice
https://raw.githubusercontent.com/storopoli/invoice/main/invoice-maker.typ
typst
MIT License
#let nbh = "‑" // Truncate a number to 2 decimal places // and add trailing zeros if necessary // E.g. 1.234 -> 1.23, 1.2 -> 1.20 #let add-zeros = (num) => { // Can't use trunc and fract due to rounding errors let frags = str(num).split(".") let (intp, decp) = if frags.len() == 2 { frags } else { (num, "00") } str(intp) + "." + (str(decp) + "00").slice(0, 2) } #let parse-date = (date-str) => { let parts = date-str.split("-") if parts.len() != 3 { panic( "Invalid date string: " + date-str + "\n" + "Expected format: YYYY-MM-DD" ) } datetime( year: int(parts.at(0)), month: int(parts.at(1)), day: int(parts.at(2)), ) } #let TODO = box( inset: (x: 0.5em), outset: (y: 0.2em), radius: 0.2em, fill: rgb(255,180,170), )[ #text( size: 0.8em, weight: 600, fill: rgb(100,68,64) )[TODO] ] #let horizontalrule = [ #v(8mm) #line( start: (20%,0%), end: (80%,0%), stroke: 0.8pt + gray, ) #v(8mm) ] #let signature-line = line(length: 5cm, stroke: 0.4pt) #let endnote(num, contents) = [ #stack(dir: ltr, spacing: 3pt, super[#num], contents) ] #let languages = ( en: ( id: "en", country: "US", recipient: "Recipient", biller: "Biller", invoice: "Invoice", cancellation-invoice: "Cancellation Invoice", cancellation-notice: (id, issuing-date) => [ As agreed, you will receive a credit note for the invoice *#id* dated *#issuing-date*. ], invoice-id: "Invoice ID", issuing-date: "Issuing Date", delivery-date: "Delivery Date", items: "Items", closing: "Thank you for the good cooperation!", number: "№", date: "Date", description: "Description", duration: "Duration", quantity: "Quantity", price: "Price", total-time: "Total working time", subtotal: "Subtotal", discount-of: "Discount of", vat: "Taxes of", reverse-charge: "Reverse Charge", total: "Total", due-text: val => [Please transfer the money onto following bank account due to *#val*:], owner: "Account Owner", iban: "IBAN", swift: "SWIFT", ), ) #let invoice( language: "en", country: none, title: none, banner-image: none, invoice-id: none, cancellation-id: none, issuing-date: none, delivery-date: none, due-date: none, biller: (:), recipient: (:), keywords: (), hourly-rate: none, styling: (:), // font, font-size, margin (sets defaults below) items: (), discount: none, vat: 0.19, data: none, doc, ) = { // Set styling defaults styling.font = styling.at("font", default: "Liberation Sans") styling.font-size = styling.at("font-size", default: 11pt) styling.margin = styling.at("margin", default: ( top: 20mm, right: 25mm, bottom: 20mm, left: 25mm, )) language = if data != none { data.at("language", default: language) } else { language } // Translations let t = if type(language) == str { languages.at(language) } else if type(language) == dictionary { language } else { panic("Language must be either a string or a dictionary.") } if data != none { language = data.at("language", default: language) country = data.at("country", default: t.country) title = data.at("title", default: title) banner-image = data.at("banner-image", default: banner-image) invoice-id = data.at("invoice-id", default: invoice-id) cancellation-id = data.at("cancellation-id", default: cancellation-id) issuing-date = data.at("issuing-date", default: issuing-date) delivery-date = data.at("delivery-date", default: delivery-date) due-date = data.at("due-date", default: due-date) biller = data.at("biller", default: biller) recipient = data.at("recipient", default: recipient) keywords = data.at("keywords", default: keywords) hourly-rate = data.at("hourly-rate", default: hourly-rate) styling = data.at("styling", default: styling) items = data.at("items", default: items) discount = data.at("discount", default: discount) vat = data.at("vat", default: vat) } let signature = "" let issuing-date = if issuing-date != none { issuing-date } else { datetime.today().display("[year]-[month]-[day]") } set document( title: title, keywords: keywords, date: parse-date(issuing-date), ) set page( margin: styling.margin, numbering: none, ) set par(justify: true) set text( lang: t.id, font: if styling.font != none { styling.font } else { () }, size: styling.font-size, ) set table(stroke: none) // Offset page top margin for banner image [#pad(top: -20mm, banner-image)] align(center)[#block(inset: 2em)[ #text(weight: "bold", size: 2em)[ #(if title != none { title } else { if cancellation-id != none { t.cancellation-invoice } else { t.invoice } }) ] ]] let invoice-id-norm = if invoice-id != none { if cancellation-id != none { cancellation-id } else { invoice-id } } else { TODO // TODO: Reactivate after Typst supports hour, minute, and second // datetime // .today() // .display("[year]-[month]-[day]t[hour][minute][second]") } let delivery-date = if delivery-date != none { delivery-date } else { TODO } align(center, table( columns: 2, align: (right, left), inset: 4pt, [#t.invoice-id:], [*#invoice-id-norm*], [#t.issuing-date:], [*#issuing-date*], [#t.delivery-date:], [*#delivery-date*], ) ) v(2em) box(height: 10em)[ #columns(2, gutter: 4em)[ === #t.recipient #v(0.5em) #recipient.name \ #{if "title" in recipient { [#recipient.title \ ] }} #recipient.address.city #recipient.address.postal-code \ #recipient.address.street === #t.biller #v(0.5em) #biller.name \ #{if "title" in biller { [#biller.title \ ] }} #biller.address.city #biller.address.postal-code \ #biller.address.street \ Tax ID: #biller.vat-id ] ] if cancellation-id != none { (t.cancellation-notice)(invoice-id, issuing-date) } [== #t.items] v(1em) let getRowTotal = row => { if row.at("dur-min", default: 0) == 0 { row.price * row.at("quantity", default: 1) } else { calc.round(hourly-rate * (row.dur-min / 60), digits: 2) } } let cancel-neg = if cancellation-id != none { -1 } else { 1 } table( columns: (auto, auto, 1fr, auto, auto, auto), align: (col, row) => if row == 0 { (right,left,left,center,center,center,center,).at(col) } else { (right,left,left,right,right,right,right,).at(col) }, inset: 6pt, table.header( // TODO: Add after https://github.com/typst/typst/issues/3734 // align: (right,left,left,center,center,center,center,), table.hline(stroke: 0.5pt), [*#t.number*], [*#t.date*], [*#t.description*], [*#t.quantity*], [*#t.price*\ #text(size: 0.8em)[( \$ )]], [*#t.total*\ #text(size: 0.8em)[( \$ )]], table.hline(stroke: 0.5pt), ), ..items .enumerate() .map(((index, row)) => { ( row.at("number", default: index + 1), row.date, row.description, str(row.at("quantity", default: "")), str(add-zeros(cancel-neg * row.at("price", default: calc.round(hourly-rate, digits: 2)) )), str(add-zeros(cancel-neg * getRowTotal(row))), ) }) .flatten() .map(str), table.hline(stroke: 0.5pt), ) let sub-total = items .map(getRowTotal) .sum() let discount-value = if discount == none { 0 } else { if (discount.type == "fixed") { discount.value } else if discount.type == "proportionate" { sub-total * discount.value } else { panic(["#discount.type" is no valid discount type]) } } let discount-label = if discount == none { 0 } else { if (discount.type == "fixed") { "\$ " + str(discount.value) } else if discount.type == "proportionate" { str(discount.value * 100) + " %" } else { panic(["#discount.type" is no valid discount type]) } } let tax = 0 let total = sub-total - discount-value + tax let table-entries = ( if (discount-value != 0) or (vat != 0) { ([#t.subtotal:], [\$ #{add-zeros(cancel-neg * sub-total)}]) }, if discount-value != 0 { ( [#t.discount-of #discount-label #{if discount.reason != "" { "(" + discount.reason + ")" }}], [\$ -#add-zeros(cancel-neg * discount-value)] ) }, ( [*#t.total*:], [*\$ #add-zeros(cancel-neg * total)*] ), ) .filter(entry => entry != none) let grayish = luma(245) align(right, table( columns: 2, fill: (col, row) => // if last row if row == table-entries.len() - 1 { grayish } else { none }, stroke: (col, row) => // if last row if row == table-entries.len() - 1 { (y: 0.5pt, x: 0pt) } else { none }, ..table-entries .flatten(), ) ) v(1em) if cancellation-id == none { let due-date = if due-date != none { due-date } else { (parse-date(issuing-date) + duration(days: 14)) .display("[year]-[month]-[day]") } (t.due-text)(due-date) v(1em) align(center)[ #table( fill: grayish, // stroke: 1pt + blue, // columns: 2, // TODO: Doesn't work for unknown reason columns: (8em, auto), inset: (col, row) => if col == 0 { if row == 0 { (top: 1.2em, right: 0.6em, bottom: 0.6em) } else { (top: 0.6em, right: 0.6em, bottom: 1.2em) } } else { if row == 0 { (top: 1.2em, right: 2em, bottom: 0.6em, left: 0.6em) } else { (top: 0.6em, right: 2em, bottom: 1.2em, left: 0.6em) } }, align: (col, row) => (right,left,).at(col), table.hline(stroke: 0.5pt), [#t.owner:], [*#biller.name*], [#t.iban:], [*#biller.iban*], [#t.swift], [*#biller.swift*], table.hline(stroke: 0.5pt), ) ] v(1em) t.closing } else { v(1em) align(center, strong(t.closing)) } doc }
https://github.com/mariuslb/thesis
https://raw.githubusercontent.com/mariuslb/thesis/main/content/removed.typ
typst
== Analysemethodik Um aussagekräftige und sinnvolle Ergebnisse bei der Datenanalyse zu erzielen, wird der *Data Science Lifecycle* als Struktur genutzt. Dieser Lifecycle besteht aus mehreren Phasen: Business Understanding, Data Mining, Data Cleaning, Data Exploration, Feature Engineering, Predictive Modeling und Data Visualization. Jede Phase ist entscheidend, um die gesammelten Fahrdaten systematisch zu aggregieren und zu analysieren. + *Business Unterstanding*: Der erste Schritt im Data Science Lifecycle ist das Verständnis des Geschäftskontexts und der Ziele der Analyse. In dieser Untersuchung ist das Ziel, die Effizienz und Nachhaltigkeit von Elektrofahrzeugen (EVs) im Vergleich zu Fahrzeugen mit Verbrennungsmotoren (ICEs) zu bewerten. Dies wird durch die Analyse von Fahrdaten realisiert, die in Hamburg aufgezeichnet wurden. Die zentralen Fragestellungen betreffen die Energieeffizienz unter realen Fahrbedingungen und den Vergleich mit den Normwerten des Worldwide Harmonized Light Vehicles Test Procedure (WLTP). + *Data Mining*: In der Data Mining-Phase werden die Fahrdaten gesammelt und aufbereitet. Für diese Untersuchung wurden Fahrdaten sowohl von einem Elektrofahrzeug (Mokka E) als auch von einem Fahrzeug mit Verbrennungsmotor (Golf 8) in Hamburg erhoben. Die Datenerhebung erfolgte werktags über zwei Tage, wobei jeweils 30 Fahrten pro Fahrzeug aufgezeichnet wurden. Diese Fahrdaten umfassen unter anderem Zeitstempel, geografische Koordinaten, Geschwindigkeit, zurückgelegte Distanz, Höhe, Beschleunigung sowie Kraftstoffverbrauch und CO2-Emissionen. + *Data Cleaning*: Die Datenbereinigung ist ein kritischer Schritt, um die Qualität der Daten sicherzustellen. Hierbei werden Fehler und Inkonsistenzen in den Rohdaten beseitigt. Dies umfasst: - Entfernung von Ausreißern: Identifikation und Entfernung von Datenpunkten, die signifikant von der Norm abweichen. - Behandlung fehlender Werte: Interpolation oder Entfernung von Datensätzen mit fehlenden Werten. - Korrektur fehlerhafter Daten: Überprüfung und Korrektur von Datenpunkten, die durch Messfehler oder andere Anomalien entstanden sind. + *Data Exploration*: Nach der Datenbereinigung folgt die Datenexploration, bei der die Daten visuell und statistisch untersucht werden. Ziel ist es, erste Muster und Zusammenhänge in den Daten zu erkennen. Hierbei werden unter anderem Verteilungen, Korrelationen und Zeitreihenanalysen durchgeführt, um ein besseres Verständnis der Daten zu erlangen. + *Feature Engineering*: Im Feature Engineering werden neue Merkmale (Features) aus den vorhandenen Daten abgeleitet, die für die Analyse relevant sind. Beispiele für solche Features sind: - Durchschnittliche Geschwindigkeit: Berechnung der durchschnittlichen Geschwindigkeit für jede Fahrt. - Beschleunigungsprofile: Analyse der Beschleunigungs- und Verzögerungsmuster. - Energieverbrauch pro Kilometer: Berechnung des Energieverbrauchs pro zurückgelegtem Kilometer. + *Predictive Modeling*: In der Phase des Predictive Modeling werden statistische Modelle erstellt, um Vorhersagen und Analysen durchzuführen. Hierbei werden verschiedene Modellierungsansätze wie Regressionsanalyse, Varianzanalysen oder Hypothesentests verwendet, um signifikante Unterschiede und Zusammenhänge in den Daten zu identifizieren. + *Data Visualization*: Abschließend werden die Ergebnisse der Analyse visualisiert, um sie anschaulich darzustellen und leichter interpretieren zu können. Dies umfasst die Erstellung von Diagrammen, Grafiken und Karten, die die wesentlichen Erkenntnisse verdeutlichen. Die Visualisierung unterstützt dabei, die Ergebnisse effektiv zu kommunizieren und die Implikationen für die Nutzung von Elektrofahrzeugen im Alltag zu verstehen. Durch die Anwendung des Data Science Lifecycles auf die Fahrdaten wird eine strukturierte und systematische Analyse ermöglicht, die fundierte und aussagekräftige Ergebnisse liefert. #pagebreak() == 04 === Regression (wird komplett überarbeitet) In diesem Kapitel wird eine detaillierte Analyse des Energieverbrauchs von Elektrofahrzeugen (EVs) und Verbrennungsmotorfahrzeugen (ICEs) durchgeführt. Dabei wird der Einfluss verschiedener Faktoren auf den Energieverbrauch untersucht, um ein besseres Verständnis der Effizienzunterschiede zwischen den beiden Fahrzeugtypen zu gewinnen. ==== Deskriptive Statistiken Zunächst werden die deskriptiven Statistiken für den Energieverbrauch, die Durchschnittsgeschwindigkeit und die zurückgelegte Distanz für die beiden Fahrzeugtypen dargestellt. Die folgende Tabelle zeigt die mittleren Werte für diese Variablen: #figure( ```R Vehicle_Type Energy_kWh_mean Speed_kmh_mean Distance_km_mean <fct> <dbl> <dbl> <dbl> 1 Golf 0.00154 28.3 0.00850 2 Mokka e 0.00152 31.1 0.00929 ```, caption: [Deskriptive Statistiken] ) ==== Visualisierung der Verteilung Energieverbrauchs Die folgende Abbildung zeigt einen Boxplot des Energieverbrauchs für die beiden Fahrzeugtypen. Hierbei wird die Verteilung des Energieverbrauchs für den VW Golf 8 und den Opel Mokka E verglichen. #figure( image("../img/comparison-energy.png", width: 80%), caption: [Vergleich des Energieverbrauchs beider Fahrzeugtypen], ) - Der mittlere Energieverbrauch ist bei beiden Fahrzeugtypen ähnlich, wobei der Opel Mokka E einen etwas niedrigeren Energieverbrauch aufweist. - Die Verteilung der Energieverbrauchswerte zeigt, dass es beim VW Golf 8 mehr Ausreißer gibt, was auf eine größere Variabilität im Energieverbrauch hinweist. *Verteilung des Energieverbrauchs nach Geschwindigkeit* #grid( columns: 2, gutter: 5pt, figure( image("../img/verteilung-golf.png"), caption: [Verteilung Golf], ), figure( image("../img/verteilung-mokka.png"), caption: [Verteilung Mokka], ) ) ==== Correlation Funnel für die Auswahl wichtiger Variablen für das Modell: #figure( image("../img/correlation-ziel-energy.png", width: 80%), caption: [Verteilung Mokka], ) ==== Regressionsanalyse Um die Einflussfaktoren auf den Energieverbrauch genauer zu untersuchen, wurde eine lineare Regressionsanalyse durchgeführt. Die abhängige Variable ist der Energieverbrauch (kWh), während die unabhängigen Variablen der Fahrzeugtyp, die Geschwindigkeit, die Beschleunigung und die zurückgelegte Distanz sind. #figure( ```R energy_model <- lm(Energy_kWh ~ Vehicle_Type + Speed_kmh + Acceleration.m.s.2. + Distance_km, data = combined_data) ```, caption: [ModellFormel] ) #figure( ``` Call: lm(formula = Energy_kWh ~ Vehicle_Type + Speed_kmh + Acceleration.m.s.2. + Distance_km, data = combined_data) Residuals: Min 1Q Median 3Q Max -0.029941 -0.000958 -0.000316 0.000650 0.047272 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 5.692e-04 1.248e-05 45.61 <2e-16 *** Vehicle_TypeMokka e -1.153e-04 1.142e-05 -10.10 <2e-16 *** Speed_kmh 7.170e-06 3.416e-07 20.99 <2e-16 *** Acceleration.m.s.2. 1.504e-03 6.411e-06 234.62 <2e-16 *** Distance_km 8.979e-02 7.655e-04 117.29 <2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.001688 on 99038 degrees of freedom Multiple R-squared: 0.4563, Adjusted R-squared: 0.4563 F-statistic: 2.078e+04 on 4 and 99038 DF, p-value: < 2.2e-16 ```, caption: [Modellformel und Ausgabe] ) - Der Intercept-Wert ist (5.692 \times 10^{-4}), was der Grundverbrauch ohne Einfluss der erklärenden Variablen darstellt. - Der Koeffizient für den Fahrzeugtyp (Mokka e) ist negativ und signifikant ((p < 2e-16)), was bedeutet, dass der Mokka e im Durchschnitt einen geringeren Energieverbrauch hat als der Golf. - Die Geschwindigkeit ((Speed_kmh)) und Beschleunigung (Acceleration.m.s.2.) haben positive und signifikante Effekte auf den Energieverbrauch, was darauf hinweist, dass höhere Geschwindigkeiten und häufigere Beschleunigungen zu einem höheren Energieverbrauch führen. - Die zurückgelegte Distanz (Distance\_km) hat ebenfalls einen positiven und signifikanten Einfluss auf den Energieverbrauch. #figure( image("../img/model-plot.png", width: 80%), caption: [Diagnoseplots des Regressionsmodells], ) todo: zu regression Inhalt komplett überarbeiten === Random Forest (einbauen!) === Neuronales Netwzerk (einbauen) === Gradient Boosting Machines (GBM) todo: einbauen === Schlussfolgerungen Die Regressionsanalyse bestätigt, dass der Fahrzeugtyp, die Geschwindigkeit, die Beschleunigung und die zurückgelegte Distanz signifikante Einflussfaktoren auf den Energieverbrauch sind. Der Opel Mokka E zeigt im Durchschnitt einen geringeren Energieverbrauch als der VW Golf 8, was die Hypothese unterstützt, dass Elektrofahrzeuge effizienter im Energieverbrauch sind. Vorschlag: Für zukünftige Analysen wäre es hilfreich, weitere erklärende Variablen zu berücksichtigen und möglicherweise nicht-lineare Modelle oder Interaktionseffekte zu untersuchen, um ein noch präziseres Modell des Energieverbrauchs zu entwickeln. === wltp-Ergebnisse Die Ergebnisse der Analysen sind in den folgenden Abbildungen dargestellt. Die Balkendiagramme zeigen den Vergleich des Energieverbrauchs zwischen den realen Fahrbedingungen und den WLTP-Normwerten für beide Fahrzeugtypen und verschiedene Geschwindigkeitskategorien. VW Golf 8 2.0 TDI - Extra High Speed: real 4.5 kWh/100km, WLTP 4.5 kWh/100km - High Speed: real 3.7 kWh/100km, WLTP 3.7 kWh/100km - Low Speed: real 6.58 kWh/100km, WLTP 6.2 kWh/100km - Medium Speed: real 9.87 kWh/100km, WLTP 4.3 kWh/100km #figure( image("../img/wltp-golf.png", width: 80%), caption: [WLTP Vergleich Golf], ) Opel Mokka e - Extra High Speed: real 20.22 kWh/100km, WLTP 20.22 kWh/100km - High Speed: real 17.8 kWh/100km, WLTP 17.8 kWh/100km - Low Speed: real 17.16 kWh/100km, WLTP 15.8 kWh/100km - Medium Speed: real 21.35 kWh/100km, WLTP 16.2 kWh/100km #figure( image("../img/wltp-mokka.png", width: 80%), caption: [Diagnoseplots des Regressionsmodells], ) === Diskussion der Ergebnisse Signifikante Diskrepanzen Die Analyse zeigt signifikante Diskrepanzen zwischen den realen Energieverbrauchswerten und den WLTP-Normwerten, insbesondere bei niedrigen und mittleren Geschwindigkeiten. Diese Diskrepanzen deuten darauf hin, dass die WLTP-Werte nicht immer die realen Fahrbedingungen adäquat widerspiegeln. VW Golf 8 2.0 TDI - Niedrige und mittlere Geschwindigkeiten: Die realen Verbrauchswerte zeigen eine signifikant höhere Abweichung von den WLTP-Werten, was auf Ineffizienzen des Fahrzeugs bei unterschiedlichen Fahrbedingungen hinweist. Dies könnte auf Faktoren wie variierende Fahrstile, Verkehrsbedingungen und Umweltfaktoren zurückzuführen sein . - Hohe und sehr hohe Geschwindigkeiten: Die realen und WLTP-Werte stimmen weitgehend überein, was auf eine bessere Leistung des Fahrzeugs unter diesen Bedingungen hindeutet . <NAME> e - Niedrige und mittlere Geschwindigkeiten: Auch hier sind die Diskrepanzen deutlich ausgeprägt, wobei die realen Verbrauchswerte höher sind als die WLTP-Werte. Dies könnte auf die höhere Empfindlichkeit von Elektrofahrzeugen gegenüber variablen Fahrbedingungen hinweisen, insbesondere bei niedrigen Geschwindigkeiten und häufigen Beschleunigungs- und Bremsmanövern . - Hohe und sehr hohe Geschwindigkeiten: Der Unterschied zwischen den realen und WLTP-Werten ist weniger signifikant, was auf eine effizientere Nutzung der Energie bei höheren Geschwindigkeiten hinweist . == Analysemethodik Die Analyse der erhobenen Fahrdaten erfolgt in zwei Schwerpunkten, die den Hypothesen H1 und H2 entsprechen. Für H1 steht die Untersuchung der Energie- und Beschleunigungsperformance im Vordergrund, während für H2 die Einteilung der Fahrdaten in WLTP-Kategorien und die Analyse der Abweichungen zwischen Soll- und Realverbrauch relevant sind.
https://github.com/Mc-Zen/quill
https://raw.githubusercontent.com/Mc-Zen/quill/main/examples/teleportation.typ
typst
MIT License
#import "../src/quill.typ": * #quantum-circuit( lstick($|psi〉$), ctrl(1), gate($H$), 1, ctrl(2), meter(), [\ ], lstick($|beta_00〉$, n: 2), targ(), 1, ctrl(1), 1, meter(), [\ ], 3, gate($X$), gate($Z$), midstick($|psi〉$), setwire(0) )
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/docs/tinymist/frontend/vscode.typ
typst
Apache License 2.0
#import "/docs/tinymist/frontend/mod.typ": * #show: book-page.with(title: "Tinymist VS Code Extension") A VS Code or VS Codium extension for Typst. You can find the extension on: - Night versions available at #link("https://github.com/Myriad-Dreamin/tinymist/actions")[GitHub Actions];. - Stable versions available at #link("https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist")[Visual Studio Marketplace];. - Stable versions available at #link("https://open-vsx.org/extension/myriad-dreamin/tinymist")[Open VSX];. == Features <features> See #link("https://github.com/Myriad-Dreamin/tinymist#features")[Tinymist Features] for a list of features. == Usage Tips <usage-tips> === Initializing with a Template <initializing-with-a-template> To initialize a Typst project: - Use command `Typst init template` (tinymist.initTemplate) to initialize a new Typst project based on a template. - Use command `Typst show template` (tinymist.showTemplateGallery) to show available Typst templates for picking up a template to initialize. 🎉 If your template contains only a single file, you can also insert the template content in place with command: - Use command `Typst template in place` (tinymist.initTemplateInPlace) and input a template specifier for initialization. === Configuring LSP-enhanced formatters <configuring-lsp-enhanced-formatters> + Open settings. + Search for "Tinymist Formatter" and modify the value. - Use `"formatterMode": "typstyle"` for #link("https://github.com/Enter-tainer/typstyle")[typstyle];. - Use `"formatterMode": "typstfmt"` for #link("https://github.com/astrale-sharp/typstfmt")[typstfmt];. Tips: to enable formatting on save, you should add extra settings for typst language: ```json { "[typst]": { "editor.formatOnSave": true } } ``` === Configuring/Using Tinymist’s Activity Bar (Sidebar) <configuringusing-tinymists-activity-bar-sidebar> If you don’t like the activity bar, you can right-click on the activity bar and uncheck "Tinymist" to hide it. ==== Symbol View <symbol-view> - Search symbols by keywords, descriptions, or handwriting. - See symbols grouped by categories. - Click on a symbol, then it will be inserted into the editor. ==== Preview Command <preview-command> Open command palette (Ctrl+Shift+P), and type `>Typst Preview:`. You can also use the shortcut (Ctrl+K V). ==== Theme-aware template (previewing) <theme-aware-template-previewing> In short, there is a `sys.inputs` item added to the compiler when your document is under the context of _user editing or previewing task_. You can use it to configure your template: ```typ #let preview-args = json.decode(sys.inputs.at("x-preview", default: "{}")) // One is previewing the document. #let is-preview = sys.inputs.has("x-preview") // `dark` or `light` #let preview-theme = preview-args.at("theme", default: "light") ``` For details, please check #link("https://myriad-dreamin.github.io/tinymist/feature/preview.html#label-sys.inputs")[Preview’s sys.inputs];. === Configuring path to search fonts <configuring-path-to-search-fonts> To configure path to search fonts: + Open settings. - File -\> Preferences -\> Settings (Linux, Windows). - Code -\> Preferences -\> Settings (Mac). + Search for "Tinymist Font Paths" for providing paths to search fonts order-by-order. + Search for "Tinymist System Fonts" for disabling system fonts to be searched, which is useful for reproducible rendering your PDF documents. + Reload the window or restart the vscode editor to make the settings take effect. *Note:* you must provide absolute paths. *Note:* you can use vscode variables in the settings, see #link("https://www.npmjs.com/package/vscode-variables")[vscode-variables] for more information. === Configuring path to root directory <configuring-path-to-root-directory> To configure the root path resolved for Typst compiler: + Open settings. + Search for "Tinymist Root Path" and modify the value. + Reload the window or restart the vscode editor to make the settings take effect. *Note:* you must provide absolute paths. === Compiling PDF <compiling-pdf> This extension compiles to PDF, but it doesn’t have a PDF viewer yet. To view the output as you work, install a PDF viewer extension, such as `vscode-pdf`. To find a way to compile PDF: - Click the code len `Export PDF` at the top of document, or use command `Typst Show PDF ...`, to show the current document to PDF. - Use command `Typst Export PDF` to export the current document to PDF. - There are code lens buttons at the start of the document to export your document to PDF or other formats. To configure when PDFs are compiled: + Open settings. + Search for "Tinymist Export PDF". + Change the "Export PDF" setting. - `onSave` makes a PDF after saving the Typst file. - `onType` makes PDF files live, as you type. - `never` disables PDF compilation. - `onDocumentHasTitle` makes a PDF when the document has a title and, as you save. To configure where PDFs are saved: + Open settings. + Search for "Tinymist Output Path". + Change the "Output Path" setting. This is the path pattern to store artifacts, you can use `$root` or `$dir` or `$name` to do magic configuration - e.g. `$root/$dir/$name` (default) for `$root/path/to/main.pdf`. - e.g. `$root/target/$dir/$name` for `$root/target/path/to/main.pdf`. - e.g. `$root/target/foo` for `$root/target/foo.pdf`. This will ensure that the output is always output to `target/foo.pdf`. *Note:* the output path should be substituted as an absolute path. === Exporting to Other Formats <exporting-to-other-formats> You can export your documents to various other formats by lsp as well. Currently, the following formats are supported: - Official svg, png, and pdf. - Unofficial html, md (typlite), and txt - Query Results (into json, yaml, or txt), and pdfpc (by `typst query --selector <pdfpc-file>`, for #link("https://touying-typ.github.io/touying/")[Touying];) See #link("https://myriad-dreamin.github.io/tinymist/feature/export.html")[Docs: Exporting Documents] for more information. === Working with Multiple-File Projects <working-with-multiple-file-projects> You can pin a main file by command. - Use command `Typst Pin Main` (tinymist.pinMainToCurrent) to set the current file as the main file. - Use command `Typst Unpin Main` (tinymist.unpinMain) to unset the main file. #note-box[ `tinymist.pinMain` is a stateful command, and tinymist doesn't remember it between sessions (closing and opening the editor). ] === Passing Extra CLI Arguments <passing-extra-cli-arguments> There is a *global* configuration `tinymist.typstExtraArgs` to pass extra arguments to tinymist LSP, like what you usually do with `typst-cli` CLI. For example, you can set it to `["--input=awa=1", "--input=abaaba=2", "main.typ"]` to configure `sys.inputs` and entry for compiler, which is equivalent to make LSP run like a `typst-cli` with such arguments: ``` typst watch --input=awa=1 --input=abaaba=2 main.typ ``` Supported arguments: - entry file: The last string in the array will be treated as the entry file. - This is used to specify the *default* entry file for the compiler, which may be overridden by other settings. - `--input`: Add a string key-value pair visible through `sys.inputs`. - `--font-path` (environment variable: `TYPST_FONT_PATHS`), Font paths, maybe overriden by `tinymist.fontPaths`. - `--ignore-system-fonts`: Ensures system fonts won’t be searched, maybe overriden by `tinymist.systemFonts`. - `--creation-timestamp` (environment variable: `SOURCE_DATE_EPOCH`): The document’s creation date formatted as a #link("https://reproducible-builds.org/specs/source-date-epoch/")[UNIX timestamp];. *Note:* Fix entry to `main.typ` may help multiple-file projects but you may loss diagnostics and autocompletions in unrelated files. *Note:* the arguments has quite low priority, and that may be overridden by other settings. == Contributing <contributing> You can submit issues or make PRs to #link("https://github.com/Myriad-Dreamin/tinymist")[GitHub];.
https://github.com/0x546974616e/typst-resume
https://raw.githubusercontent.com/0x546974616e/typst-resume/main/template/heading.typ
typst
#import "./globals.typ": colors, spacing #let h2(content, color: colors.fg2) = { block( align( left + horizon, stack( dir: ltr, spacing: spacing.medium, rect( width: 7pt, height: 7pt, fill: color, ), // rect heading( level: 2, text( fill: color, upper(content), ) // text ), // heading ) // stack ) // align ) // block } #let h3(content, color: colors.fg1) = { heading( level: 3, text( fill: color, weight: 500, upper(content) ) // text ) // heading } #let h4(value) = text( weight: 500, fill: colors.fg1, if type(value) == "content" { return value } else { str(value) } )
https://github.com/lucifer1004/leetcode.typ
https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/problems/p0009.typ
typst
#import "../helpers.typ": * #import "../solutions/s0009.typ": * = Palindrome Number Given an integer `x`, return `true` if `x` is a *palindrome*, and `false` otherwise. #let palindrome-number(x) = { // Solve the problem here } #testcases( palindrome-number, palindrome-number-ref, ( (x: 121), (x: -121), (x: 10), ) )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/minimalbc/0.0.1/README.md
markdown
Apache License 2.0
# minimalbc This repository provides a Typst template for creating sleek and minimalist professional business cards. The function, **minimalbc**, allows you to customize the majority of the business card's elements. By default, the layout is horizontal. However, it can be easily switched to a vertical layout by passing the value true to the flip argument in the minimalbc function. Here’s an example of how to use the minimalbc function: ```Typst #import "@preview/minimalbc:0.1.0": minimalbc #show: minimalbc.with( // possible geo_size options: eu, us, jp , cn geo_size: "eu", flip:true, company_name: "company name", name: "<NAME>", role: "role", telephone_number: "+000 00 000000", email_address: "<EMAIL>", website: "example.com", company_logo: image("company_logo.png"), bg_color: "ffffff", ) ``` When compiled, this example produces a PDF file named 'your filename'.pdf (see example.pdf). Feel free to download and use this as a starting point for your own business cards.
https://github.com/cohenasaf/Teoria-Informazione-Trasmissione
https://raw.githubusercontent.com/cohenasaf/Teoria-Informazione-Trasmissione/main/appunti.typ
typst
// Setup #import "template.typ": project #show: project.with( title: "Teoria dell'informazione e della trasmissione" ) #pagebreak() // Appunti // Lezione 06/10/2023 #include "2023-10-06.typ"
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/table_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test alignment with array. #table( columns: (1fr, 1fr, 1fr), align: (left, center, right), [A], [B], [C] ) // Test empty array. #set align(center) #table( columns: (1fr, 1fr, 1fr), align: (), [A], [B], [C] )
https://github.com/wuespace/vos
https://raw.githubusercontent.com/wuespace/vos/main/vo/carevo.typ
typst
#import "@preview/delegis:0.3.0": * #show: delegis.with( // Metadata title: "Vereinsordnung zu Vertrauenspersonen des WüSpace e. V.", abbreviation: "CareVO", resolution: "4. Beschluss der Mitgliederversammlung vom 03.07.2024, 2024/MV-4", in-effect: "03.07.2024", draft: false, // Template logo: image("wuespace.svg", alt: "WüSpace e. V."), ) /// Usage // // "§ 123abc Section title" for a section "§ 123abc" with the title "Section title" // "#section[§ 123abc][Section title]" for the same section // "#s~" for sentence numbers in multi-sentence paragraphs // (normal Typst headings) such as "= ABC" for grouping sections together // /// #unnumbered(level: 1, outlined: false)[Vorbemerkung] Fußnoten dienen als redaktionelle Anmerkungen oder Interpretationshilfen und sind nicht selbst Teil der Beschlussfassung. #v(2em) #outline() = Allgemeiner Teil § 1 Offenheit und Toleranz WüSpace heißt alle Menschen willkommen und toleriert keine Form gruppenbezogener Menschenfeindlichkeit. § 2 Vertrauenspersonen Zur Sicherstellung einer offenen Kultur gibt es Vertrauenspersonen. = Aufgaben und Mittel § 3 Aufgaben der Vertrauenspersonen (1) #s~Die Vertrauenspersonen fungieren beratend gegenüber dem Vorstandes und als vorstandsunabhängige Ansprechpersonen für die Vereinsmitglieder. #s~Die Vertrauenspersonen setzen sich darüber hinaus aktiv ein für + ein gutes Vereinsklima, + Diversität, + Inklusivität und + Gleichberechtigung. (2) Die Vertrauenspersonen bieten keine + Therapie, + Diagnosen oder + offizielle Schreiben an. #footnote[ In diesen Fällen sollen die Vertrauenspersonen an die zuständigen Stellen weiterleiten. ] § 4 Ansprechstelle für Mitglieder (1) Als vorstandsunabhängige Ansprechstelle für die Vereinsmitglieder fungieren die Vertrauenspersonen insbesondere bei: + Überarbeitung; + Vorschlägen für mehr Inklusivitaet im Verein; + Sorgen; + Gesprächsbedarf; + zwischenmenschlichen Problemen, wie zum Beispiel + Mobbing und + Streit. #footnote[ Die Vertrauenspersonen sollen als neutrale Vermittler*innen agieren. ] (2) #s~Die beauftragten Personen werden in den Vereinsraeumen sowie im Online-Wiki vereinsöffentlich sichtbar bekanntgegeben, damit sie im Problemfall kontaktiert werden können, ohne den Umweg über andere Personen zu nehmen. #s~Die Vertrauenspersonen bemühen sich, aktiv am Vereinsleben teilzunehmen, um Präsenz zu zeigen. (3) #s~Informationen, die einer Vertrauensperson im Vertrauen mitgeteilt wurden, dürfen nur nach explizitem Einverständnis der betroffenen Person weitergegeben werden. #s~Hiervon kann in begründeten Einzelfällen abgewichen werden, falls davon auszugehen ist, dass dem Verein oder seinen Mitgliedern anderenfalls rechtliche oder gesundheitliche Risiken drohen. (4) Kommen die Vertrauenspersonen an ihre fachlichen oder persönlichen Grenzen, so bemühen sie sich, die betroffenen Personen an die zuständigen Stellen weiterzuleiten. § 5 Aktives Engagement Die Vertrauenspersonen bemühen sich aktiv, das Vereinsklima positiv zu beeinflussen und gruppenbezogener Menschenfeindlichkeit und Ausgrenzung vorzubeugen. § 6 Beratung des Vorstands Die Vertrauenspersonen beraten den Vorstand in den unter ihre Zuständigkeit fallenden Themen. = Amtszeit § 7 Amtszeit der Vertrauenspersonen (1) Die Vertrauenspersonen werden durch Beschluss des Vorstands oder der Mitgliederversammlung mit sofortiger Wirkung ernannt. (2) Voraussetzung ist die aktive Vereinsmitgliedschaft und eine formlose Versicherung, nach bestem Wissen und Gewissen den Vorgaben entsprechend zu arbeiten. (3) #s~Die Amtszeit endet mit Erklärung des Rücktritts gegenüber des Vorstands oder auf Beschluss der Mitgliederversammlung oder des Vorstands. § 8 Bericht an die Mitgliederversammlung (1) Die Vertrauenspersonen erstatten der Mitgliederversammlung über ihre Arbeit Bericht. (2) Die Geheimhaltungsverpflichtungen gemäß §~4 Absatz 3 bleiben von der Berichtspflicht unberührt. = Schlussbestimmungen § 9 Inkrafttreten Diese Vereinsordnung tritt mit Beschluss der Mitgliederversammlung zum 03.07.2024 in Kraft und ergänzt die Satzung gemäß §~37 der Satzung.
https://github.com/lsmenicucci/typst-pkgs
https://raw.githubusercontent.com/lsmenicucci/typst-pkgs/main/mechanics/diagrams.typ
typst
#import "@preview/cetz:0.2.2" // drawing #let vector(c1, c2) = { import cetz.draw: * set-style(mark: (end:(symbol:"stealth", fill: black))) cetz.draw.line(c1, c2) set-style(mark: (end:())) } // Draw a inclined plane // - x0, y0: point 1 // - x1, y1: point 2 // - angle: angle of the inclined plane #let incl-plane(r0, r1, angle, ..extras) = { import cetz.draw: * import calc: * let (x0, y0) = r0 let (x1, y1) = r1 let dx = float(x1 - x0) let y2 = y1 + dx * tan(angle) line((x0, y0), (x1, y1)) line((x1, y1), (x1, y2)) line((x0, y0), (x1, y2)) let arc_rad = 1.0 move-to(r0) arc((rel:(arc_rad , 0)), start: 0deg, stop: angle, name: "angle") let p = arc_rad + 0.25 let px = x0 + p*cos(angle/2) let py = y0 + p*sin(angle/2) content((px, py), $theta$, anchor: "west") // draw extras translate((x0, y0)) // draw algle rotate(angle) for e in extras.pos() { e } rotate(-angle) translate((-x0, -y0)) } #let measure(c1, c2, label, offset: 0.25, invert: false) = { import cetz.draw: * import calc: * get-ctx(ctx => { let (ctx, r1, r2) = cetz.coordinate.resolve(ctx, c1, c2) set-style( mark: (end: (symbol:"stealth", fill: black), start: (symbol:"stealth", fill: black))) line(r1, r2) let (x1, y1) = (r1.at(0), r1.at(1)) let (x2, y2) = (r2.at(0), r2.at(1)) let mid = ((x1 + x2)/2, (y1 + y2)/2) let angle = cetz.vector.angle2(r1, r2) + 90deg if invert { angle = angle + 180deg } move-to(mid) content((rel: (radius: offset, angle:angle)), label) set-style(mark: (end:none, start: none)) }) } #let angle(c, angl, label, radius: 1.0) = { import cetz.draw: * import calc: * set-origin(c) let lx = (radius + 0.4)*cos(angl) let ly = (radius + 0.2)*sin(angl) arc((radius, 0), start: 0deg, stop: angl, name: "angle") content((lx, ly), label, anchor: "north-west") } #let coordsys(origin, x_name, y_name, angle: 0) = { import cetz.draw: * import calc: * translate(origin) rotate(angle) vector((0,0), (1, 0)) content((1.1,0), x_name, anchor:"west") vector((0,0), (0, 1)) content((0.0,1.15), y_name, anchor:"south") if angle != 0 { line((0,0), (1,0)) } rotate(-angle) rotate(180deg) translate(origin) rotate(180deg) } #let spring(c1, c2, n, width: 0.2, alpha: 0.7) = { import cetz.draw: * import calc: * get-ctx(ctx => { let (ctx, r1, r2) = cetz.coordinate.resolve(ctx, c1, c2) let dx = r2.at(0) - r1.at(0) let dy = r2.at(1) - r1.at(1) let angle = atan(dy/dx) let dl = sqrt(dx*dx + dy*dy)/(n + 3) // draw spring wiggles let x = 2*dl let y = 0 let points = () points.push((x - 2*dl, y)) points.push((x - dl - alpha*dl, y)) for i in range(n + 1) { let p1 = (x - dl/2 , y - width) let p2 = (x + alpha*dl, y) let p3 = (x , y + width) let p4 = (x - alpha*dl, y) if i < n { points = points + (p1, p2, p3, p4) }else{ points = points + (p1, p2) points.push((x + dl, y)) } x = x + dl } // draw translate(r1) rotate(angle) hobby(..points, closed: false) rotate(-angle) translate((-r1.at(0), -r1.at(1))) }) } // draw a pandulum #let pendulum(c, l, angle, ..extras) = { import cetz.draw: * import calc: * get-ctx(ctx => { let (ctx, p) = cetz.coordinate.resolve(ctx, c) let x = p.at(0) let y = p.at(1) let x1 = x + l*sin(angle) let y1 = y - l*cos(angle) circle((x, y), radius: 0.1em, fill: black) line((x, y), (x1, y1)) translate((x1, y1)) if extras.pos().len() > 0 { for e in extras.pos() { e } }else { // draw default ball circle((0, 0), radius: 0.1, fill: black) } translate((-x1, -y1)) }) }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/root-05.typ
typst
Other
// Test shorthand. $ √2^3 = sqrt(2^3) $ $ √(x+y) quad ∛x quad ∜x $ $ (√2+3) = (sqrt(2)+3) $
https://github.com/max-niederman/CS250
https://raw.githubusercontent.com/max-niederman/CS250/main/symbols.typ
typst
#import "./lib.typ": * #show: common.with(title: "CS 250 Symbol Reference") #table( columns: (auto, auto, 1fr, 1fr), [Symbol], [Example], [Name], [Read As], $'$, $Q'$, [negation], [not], $and$, $P and Q$, [conjunction], [and], $or$, $P or Q$, [disjunction], [or], $=>$, $P => Q$, [implication], [implies], $<=>$, $P <=> Q$, [equivalence], [if and only if], $forall$, $forall x in X, P(x)$, [universal quantifier], [for all], $exists$, $exists x in X, P(x)$, [existential quantifier], [there exists], $in$, $x in X$, [set membership], [in], $emptyset$, $emptyset$, [empty set], [the empty set], $union$, $X union Y$, [union], [union], $sect$, $X sect Y$, [intersection], [intersection], $union.big$, $union.big_(x in X) S(x)$, [infinite union], [union], $sect.big$, $sect.big_(x in X) S(x)$, [infinite intersection], [intersection], $times$, $X times Y$, [cartesian product], [cross], $-$, $X - Y$, [set difference], [minus], $subset.eq$, $X subset.eq Y$, [subset], [is a subset of], $supset.eq$, $X supset.eq Y$, [superset], [is a superset of], $subset$, $X subset Y$, [proper subset], [is a proper subset of], $supset$, $X supset Y$, [proper superset], [is a proper superset of], $log$, $log_b x$, [logarithm], [logarithm], $!$, $k!$, [factorial], [factorial], )
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Physique_Cours_6.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: "Physique Cours 6", authors: ( "<NAME>", ), date: "8 Novembre, 2023", ) #set heading(numbering: "1.1.") + D’après le théorème de l’énergie cinétique : $E_c eq 1 / 2 m v^2$ où $E_c$ est l’énergie cinétique, $m$ la masse et $v$ la vitesse. L’énergie cinétique acquise par l’électron est égale à l’opposé de la variation d’énergie potentielle électrique : $E_c eq minus lr((e Delta V))$ avec $Delta V eq minus 2 comma 0 times 10^3 upright(V)$ la tension appliquée. En combinant les deux équations et en utilisant les données numériques, on obtient : $ 1 / 2 m_e v^2 eq minus e Delta V $ $ 1 / 2 times 9 comma 11 times 10^(minus 31) upright(k g) times v^2 eq minus lr((1 comma 6 times 10^(minus 19) upright(C) times lr((minus 2000 upright(V))))) $ $ v^2 eq frac(minus 2 lr((e Delta V)), m_e) $ $ v eq 2 comma 5 times 10^7 upright(m slash s) $ La vitesse de l’électron accéléré par une tension de -2,0 kV est donc de 5,93×10^6 m/s.a #block[ #set enum(numbering: "1.", start: 2) + D’après le théorème de l’énergie cinétique : $Delta E_c eq 1 / 2 m lr((v_B^2 minus v_A^2)) eq sum_i W_(A arrow.r B) lr((arrow(F_i)))$ où $E_c$ est l’énergie cinétique, $m$ la masse et $v$ la vitesse. ] $ W_(A arrow.r B) lr((arrow(P))) eq m times g times lr((z_A minus z_B)) eq 9.45 times 10^2 upright(J) $ $ 1 / 2 m lr((v_B^2 minus v_A^2)) eq W_(A arrow.r B) lr((arrow(P))) $ $ v_B^2 eq frac(2 W_(A arrow.r B) lr((arrow(P))), m) plus v_A^2 $ $ v_B eq sqrt(frac(2 times 9 comma 45 times 10^2 plus lr((35))^2 m, m)) $ $ v_B eq frac(1.89 ast.basic 10^3, m) plus 1225 $ D’après la conservation de l’énergie mécanique: $ Delta E_m eq 0 eq Delta E_c plus Delta E_p $ $ Delta E_c eq minus Delta E_p $ $ 1 / 2 m lr((v_B^2 minus v_A^2)) eq minus lr((minus m times g times lr((z_A minus z_B)))) $ $ v_B^2 eq frac(2 m g lr((z_A minus z_B)), m) plus v_A^2 $ $ v_B eq frac(1.89 ast.basic 10^3, m) plus 1225 $
https://github.com/Xendergo/wasm-session
https://raw.githubusercontent.com/Xendergo/wasm-session/main/wasm.typ
typst
Creative Commons Zero v1.0 Universal
#import "@local/henrys-typst-utils:0.1.0" : * #import "@preview/polylux:0.3.1": * #import code-theme: * #show: code-theme #title-slide(title: [How 2 Webassembly], author: [<NAME>], note: [Go to *TODO: PUT GITHUB LINK HERE* and follow the setup instructions if you want to follow along]) #mono-slide(title: [What am I talking about?], content:[ - What is webassembly? - How can I use it? - But I'm a crazy person! How do I \*really\* use it? ]) #split-slide(title: [What am I not talking about?], content: [ - Leptos - Yew - Blazor - Vugu - etc. ], picture: { set text(size: 18pt) ```rust // Stolen from the Leptos book #[component] fn App() -> impl IntoView { let (count, set_count) = create_signal(0); view! { <button on:click=move |_| { set_count(3); } > "Click me: " {move || count()} </button> } }```}) #split-slide(title: [How do websites work?], content: [ - HTML: Hypertext Markup Language - What to show - Requests resources - CSS: Cascading Style Sheets - How the website should look - Javascript - What the website should do ], picture: { set text(18pt) [index.html:] ```html <!doctype html> <html> <head> <title>Mandelbrot</title> </head> <body> <canvas id="canvas" width="800" height="600"></canvas> <script type="module" src="sketch.js"></script> </body> </html> ``` }) #split-slide(title: [What problems does Webassembly solve?], content: [ #pdfpc.speaker-note("") - Javascript is a bad language - Cursed - No type checking - Slow - Running stuff on the web that was not meant for the web ], picture: { image("slideshow-images/js-strongtyped.png") set text(25pt) ```javascript "0" == 0 // true 0 == [] // true "0" == [] // false??? ``` }, content-width: 1.2fr) #mono-slide(title: [What is Webassembly?], content: [ - Similar to assembly/machine code - Compilation target for other languages - Small instruction set - Interfaces with Javascript - Needs Javascript glue code - No access to the standard library ]) #mono-slide(title: [Demo 1!], content: [ - Mandelbrot set - You should already have everything set up if you want to follow along ], ) #mono-slide(title: [Now observe this Meme], content: box(align(center, image("slideshow-images/earthquack.png")), width: 100%, height: 83%)) #mono-slide(title: [I know what you're thinking...], content: { set text(40pt) v(20%) uncover(2, grid(rows: 3, gutter: 25pt, [W], [A], [T]) ) }) #mono-slide(title: [And you'd be right!], content: { set text(40pt) v(20%) grid(rows: 3, gutter: 25pt, [Web], [Assembly], [Text]) }) #split-slide(title: [Sections], content: [ - Globally accessable stuff - Memory - Globals - Imports - Exports - Functions - etc. ], picture: [ #set text(15pt) ```wat (module (memory (import "js" "mem") 1) (global $end_of_input (import "js" "endOfInput") i32) (import "console" "log" (func $log (param i32) (result i32))) (import "js" "parseNum" (func $parse_num (param i32) (result i32))) (func (export "solve") (result i32) ; ... ) ) ``` ]) #mono-slide(title: [Instructions/Execution], content: [ - Small instruction set - Mix of stack and register based - Higher level control flow constructs ]) #mono-slide(title: [Demo!], content: [ https://adventofcode.com/2023/day/4 ])
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CU/postna_triod/1_generated/0_all/Tyzden1.typ
typst
#import "../../../all.typ": * #show: book = 1. #translation.at("TYZDEN") #include "../Tyzden1/1_Pondelok.typ" #pagebreak() #include "../Tyzden1/7_Nedela.typ" #pagebreak()
https://github.com/coco33920/agh-public
https://raw.githubusercontent.com/coco33920/agh-public/gh-pages/index.md
markdown
# Welcome to the Website Repository of my public stories ## Introduction You can here find the pdfs of all my public stories up-to-date with the ScribbleHub publication! If you prefer webnovels presentation here is the [AGH](https://www.scribblehub.com/series/444395/a-galactic-hrt/) SH page and here is the [AWB](https://www.scribblehub.com/series/427680/a-witchy-best-friend/) page. NB * AGH = A Galactic HRT * AWB = A Witchy Best Friend * SQS = Space Queer Station ## Status * AGH : Hiatus. * AWB : Completed, last chapter: A Witchy Lover. * SQS : Completed, last chapter: Part 2. ## PDFs ### AGH You can download here the up-to-date PDFs (A4-double page optimize or not) and see the HTML versions The PDFs are available on the repository [REPO](https://github.com/coco33920/agh-public/pdfs/). You can access them on this website with the following links * Main Up-To-Date with SH (EN) [PDF](pdfs/agh.pdf) ### AWB You can here download the up-to-date PDFs (A4-double page optimize or not) and see the HTML versions The PDFs are available on the repository [REPO](https://github.com/coco33920/agh-public/pdfs/). You can access them on this website with the following links * Completed (EN) [PDF](pdfs/awb.pdf) ### SQS The PDF version only is available * Completed (EN) [PDF](pdfs/sqs.pdf) ## Typst * AGH Typst File [Typst](pdfs/agh.typ) * AWB Typst File [Typst](pdfs/awb.typ) * SQS Typst File [Typst](pdfs/sqs.typ) ## HTML This website primary usage is to access to the HTML version of the stories * AGH HTML Version [HTML](web/agh/index.html) *last updated December 3rd, 2023*
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/linear/components/toc.typ
typst
The Unlicense
#import "../../../utils.typ" #import "../entry-types.typ": * /// Prints the table of contents. /// /// *Example Usage* /// ```typ /// #create-frontmatter-entry(title: "Table of Contents")[ /// #components.toc() /// ] /// ``` #let toc = utils.make-toc(( _, body, appendix, ) => { let previous-date let toc = stack( dir: ttb, spacing: 0.3em, ..for entry in body { let date-content = if entry.date == previous-date { } else { box( inset: 5pt, fill: white, entry.date.display("[day]/[month]/[year]"), ) } previous-date = entry.date ( [ // Single line content #box( baseline: 0.35em, width: 5em, )[ #set align(center) #date-content ] #h(1em) #box( fill: entry-type-metadata.at(entry.type), inset: ( x: .4em, y: .6em, ), baseline: 25%, )[#entry.title #h(1.4em)] #h(1em) #box( width: 1fr, line( length: 100%, start: ( 0pt, -.35em, ), ), ) #h(1em) #entry.page-number ], ) }, ) let height = measure(toc).height box[ #place( top + left, dx: 2.5em, dy: 1em, line( angle: 90deg, length: height - 12pt, ), ) #toc ] })
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/053%20-%20Wilds%20of%20Eldraine/002_Episode%202%3A%20Wandering%20Knight%2C%20Budding%20Hero.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 2: Wandering Knight, Budding Hero", set_name: "Wilds of Eldraine", story_date: datetime(day: 09, month: 08, year: 2023), author: "<NAME>", doc ) Across the valleys and into the wilds ventures Rowan Kenrith. Atop a stout horse, with a sharp blade hanging at her hip and sparks dancing from her fingertips, she journeys wherever the winds guide her. Gladly the smallfolk take her into their homes, offering what little they have; gladly does Rowan accept their kindness. In the small hours of the night, when they ask her why she is awake, she asks if they've heard where she might find a cure for the Wicked Slumber. "Are you certain you don't long for it?" asked Royse, whose fine weaves even the fae have come to covet. Rowan has stayed in palaces less well-appointed than Royse's home. The fae bestow gifts upon creators of beauty, it seems. "You look like you could use the rest." "Rest isn't of any use to me," Rowan answered. Royse, eyes flashing in the dark, tutted beneath her breath. "Rest will come for you, whether you like it or not. Best to face it on your own terms," she said. "But if you are determined to continue in your quest, brave knight, there is a castle not far from here. Its lord died long ago—longer ago than your kind remember." "My kind?" Rowan's grip tightened on her sword. Royse only smiled. The moonlight played upon her skin and the glamor broke, revealing eight eyes, two chittering mandibles, eight arms hidden beneath her stole. Little wonder her weaving fascinated humans and fae alike. "You're—" Rowan started. Royse set her two human hands on her knees. "I have promised you shelter and given you food; we are not enemies." Rowan relaxed her grip. She did not sleep that night, but she did learn a little of weaving. In the morning, Royse pointed the way to the castle, wishing Rowan good fortune on her journey. Its crumbling walls and ancient parapets now welcome her. Dust cakes her lungs the farther in she goes. Undead servants rise to meet her blade. Heart hardened against such sights, she slays them, their innards slicking the stone floors. When at last she finds the library, its shelves stand empty. There are no alembics here, no cauldrons for potion crafting, no lost secrets—only whatever the looters have left behind. After all that she has done to get here, all the blood she has spilled—nothing. Alone in the abandoned castle, <NAME> becomes a storm. She imagines what her brother would say if he saw her here, and this only drives her further into a rage. By the time she realizes she has begun to weep, her body is already shaking and weary. Against all reason there is a bed in this place, untouched by the ravages of looting. When she collapses upon it, she realizes the truth of Royse's words: rest will come, one way or another. The dream swallows her. Once more she walks through the doors of this castle—but they are whole, the wood polished and new. Within the halls there are bards and dancers. Fair women and handsome men lead her further. A fit squire removes her armor so smoothly she forgets she'd ever worn it. A warm robe is draped over her shoulders, a tankard of mead placed in her hand. Pulled along by such delights, she finds herself before a feasting table. Her father and mother stand at the head. Hale, hearty, faces radiant in the golden light of the castle, they spread their arms toward her. "Rowan, you made it," Linden says. Rowan's chest goes tight. There they are, just as she remembers them—no scars save those they earned in her youth, no bloody wounds. They are so #emph[happy] . She drops the mead, running to them full tilt. Her father lifts her off her feet and spins her. Her mother smooths her hair and dabs away the tears at the corners of Rowan's eyes. "You've come so far to see us," says Linden. "We're so proud of you." Her mouth opens again and again, but she cannot speak. "You've need of our council, don't you?" her father asks. Wordless, she nods. He takes the crown from his head and places it atop her own. "Come to Castle Ardenvale. Your blood awaits you there." She wakes, alone in the dusty castle. Sunlight filters in through the broken windows. She must have slept the whole night through. Alone, surrounded by death and cold, she allows herself another chance to weep. For when it is over, she will do as her father asked of her. She will go to Castle Ardenvale. #figure(image("002_Episode 2: Wandering Knight, Budding Hero/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "Um. Excuse me, sir, but have you seen any witches lately?" This man, like all the others Kellan has asked before him, laughs. "Oh, aye, there's one down the way. Sells the best pies in Edgewall. Tell her Duncan sent you." He's kind enough to toss over a coin. Kellan tucks it away in a pouch, his shoulders slumping, his spirits bruised but not broken. This is only the first step on his journey, right? There are so many people in Edgewall. One of them's bound to know something. All he has to do is keep at it. With a grunt of effort, he adjusts the pack on his shoulders and makes his way down the long, ambling street. All his life his mother's told him stories of places like this—of dwarves, fauns, knights, and mages. They didn't feel real until now. Across the street from the pie shop, an elven woman sells enchanted wooden songbirds. Up ahead, a Verdant Knight speaks to a smith. There are banners and baubles everywhere the eye can land. He nods to himself as he walks, decided. There's no better place to live than here. Already he can see the line at the shop doubled and tripled up. They really must make great pies—but there's no way she's a real witch. His mother always told him that cooking is the closest most people can get, though, so maybe the woman who runs it will know something. Kellan plants himself at the end of the line. As he waits, his eyes wander over the messengers running from one end to the other, the bard playing his lute. He hums along. A group of children in leaf-wrought clothes toss pinecones back and forth in a fit of laughter and giggles. Kellan grins, watching them. But then he sees the sleeping man standing under the eaves of a shop, a swirl of violet around him. His eyes are closed, his mouth open; as he sways, drool falls on his armor. This must be the Slumber the merchant told them about on his last visit. Seeing it in person is a strange thing. How long's he been like that? There's a touch of rust where his spit hits his armor. Why doesn't anyone help him? Worse, someone in a hurry bumps into the sleeper. The sleeper jerks, falls over—and no one helps him up. Kellan can't let that stand. He takes a step toward the fallen knight. A hand on his wrist snaps him from his thoughts. He looks up to its owner and finds a girl in a red cloak, her brows furrowed. "You might not want to do that." Kellan draws his hand back. "Why not? He needs help." The girl winces. "You're the kid who keeps asking people about witches?" Kellan puts on a hero's voice, or tries to, but the crack undoes him. "I might be. Depends on who's doing the, uh, asking." The girl laughs and shakes her head. She takes his hand again and starts tugging him along. "All right, hero, you're coming with me." "What? What about—Hey! What about that man?" Kellan asks. "The Wicked Slumber spreads, though no one's really sure how," she answers. "If you touch him it might get you, too. That's if the witches don't get you first." Kellan looks over his shoulder at the sleeper. As the girl tugs him into an alley, someone slips a wooden baking spatula under the man. With a little effort he is upright once more. Whatever relief Kellan feels is mitigated by his surprise once he realizes what the girl's just said. "Wait. They're after me?" The girl looks both ways down the alley before speaking. "They're going to be, if you keep asking questions like that. Don't you know you shouldn't draw a witch's attention?" "Do you know a lot about witches?" he asks. "If you do, I could really use your help. I just got here, so I don't know a lot, but I've got a quest to finish." "A quest?" she says, giving him a quick assessment. "You've got a quest. You don't even have a sword." "Heroes don't need swords," he says. He leaves out that the only sword his stepfather owned was rusty, so he couldn't bring it. "Besides, I got these from my lord, and they said they're just as good as any blade. These mean I'm a real hero!" He brandishes the pair of basket hilts—Talion's parting gift. Old wood has grown to mimic the worked steel of human smithing, with a peculiar glow proclaiming their unearthly provenance. They're sure to impress #emph[anyone] . But the girl isn't just anyone, and she regards them with only a raised brow. "Whenever someone insists that something's real, it means it isn't." She sighs. "Anyway, I wouldn't be of much help. You've got to go out to Dunbarrow. My brother, Peter, he knows every inch of that place like the back of his hand. #emph[He ] could help you." Kellan stows his hilts with a bashful sort of gratitude. "Could you take me to him?" The girl's expression clouds under the brim of her cloak. "I haven't seen him in days. I thought maybe you'd seen him, since you're from out of town." "Oh," Kellan says softly. "I'm sorry. I didn't know. I, um, I don't think I met any Peters along the way here." "Figures," says the girl. She turns. "Well. I wish you all the best on your quest, hero. If you see my brother, tell him Ruby's waiting for him back at home." Kellan, shorter than her by half a head, shuffles after her. "Wait! You can tell him yourself if you come with me." She stops. When she turns this time, her brow is raised. "#emph[You're] going to find him?" "I might," says Kellan. "You said Dunbarrow's where all the witches are. You've been there, haven't you?" Ruby dusts off her shoulder. "Once or twice." "I bet it's more than that," Kellan says. "If you can help me find the witch I'm looking for, then maybe my liege can help you find your brother." Ruby tilts her head. "And just who is your liege, anyway?" Oh no. He can't say it's the Lord of the Fae. That's no way to earn anyone's trust. But he can't lie, either. Kellan's cheeks go hot. "They don't like people talking about them very much," he says. It's true enough, right? "But they're helping me find my father. That's what I get for finishing the quest—a chance to know who he is. So I'm sure they'll help you with your brother." A pause. Ruby's studying him. He tries to stand tall. "You're sure your liege can help?" Kellan nods. "Sure as sheep's wool." Ruby frowns for a second, then nods, the tension leaving her shoulders. "All right. I guess someone's got to look out for you, and it might as well be me." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Over the heaths and through the barrow in search of witches they go. From the stories his mother told him, Kellan expected the wilds to be prettier than this. Maybe it's the aftermath of the war. Ruby tells him that the sharp metallic aberrations dotting the countryside are Phyrexian remnants, hacked apart after the Slumber stopped them in their tracks. "Those things used to be alive?" he asks her. "If you can call it alive," she answers. "You really don't know?" Stopping by one of them—what looks to be some kind of walking battering ram—she shows him the oil oozing from within it, the face with its two weeping eyes. Kellan turns away, preferring the twisted trees of Dunbarrow to the twisted body of the invader. "Where'd they come from?" "Somewhere else, says the Boy King," Ruby explains. "Some other Realm." "There are other Realms?" As they walk together through the woods, he does his best to keep the ignoble corpse behind him, focusing instead on the flitting shapes of pixies, the black streaks of birds overhead, on darting stoats. "What are they like?" "I don't know," Ruby answers. "If they have those things in them, though, I'm fine without visiting the place. Besides, I'd never go anywhere without my brother." Kellan nods. "I'd never go anywhere without my family, either. Anywhere, you know. #emph[Else.] " Ruby quirks a brow at him. "Even if it was for your quest?" He lets that one lie, unwilling to even consider it. Ruby clears a fallen bough with surprising ease, then helps Kellan to do the same. When his feet hit the earth, water splashes onto her shoes. She yelps. Somewhere in the woods around them a pixie laughs. Since time immemorial it has been impolite to laugh at a struggling girl. It is the purview of a hero to defend such damsels. Kellan frowns and prepares to shout the impish thing away—until Ruby picks up an apple from her basket and flings it hard as a giant flinging a boulder, as fast as a crossbow bolt. The pixie yelps in misery. Ruby pouts. "They're #emph[so ] annoying," she says, continuing along the unmarked path as if she hadn't displayed such talents. Kellan, awestruck, can only follow. "King's wounds, what a shot!" She stops just to stare at him for saying such a thing. "King's wounds. Really?" she says. "It's just an apple. I'm sure you can do a lot more with those fancy swords your liege has given you." It takes concerted effort not to trip when she says this, though there are no brambles in sight. He tries to think of something to say, or what the best way to tell her he has no idea how to turn the hilts into anything useful, but the words are as tricksy as the pixie Ruby so easily dispatched. All he manages is an unsure #emph[hmm] . But it makes little difference, for at that moment an arrow whistles past his face, nicking the tip of his nose before striking the tree nearest him. Kellan covers his face in alarm. Are those war drums he's hearing, or his own frantic pulse? Though fear's gotten the better of him, Ruby is quick to act as ever. She tackles Kellan into a blackberry bush. His mother's weaving keeps him safe from the thorns thirsty for blood—and the leaves keep him safe from their assailant. "King's wounds, what is #emph[that] ?" Ruby whispers. Beyond the border of the thicket they can see him: the man in wolf armor. Beneath the mail, a blood red gambeson seems an omen of wounds to come. The bow that shot the near-fatal arrow is as wicked as the thorns of the bush; at his hip hangs a sword as long as Kellan's legs. The snarling metal maw of a wolf conceals all but his burning eyes. And he is staring right at them. Kellan's throat is tight. He saw a knight for the first time only hours ago—what is this thing? The Wolf Knight strides toward them. "Run!" Kellan shouts. Ruby doesn't need to be told twice. Throwing themselves from the bush they scrabble to their feet and dash ahead. A wordless howl from the Wolf Knight peals through the forest; crows flee from their nests in terror. Even the pixies who tormented them earlier have cleared away. Another arrow whistles over Kellan's shoulder. "Now would be a great time for those magic swords," Ruby shouts. "We can't keep running forever!" Kellan swallows. Pressure mounts within his chest. He can't lie to her—but the hilts aren't swords, either. They're just ... hilts. Talion said they'd help refine his abilities. Of course, in all the time he's traveled with them, he hasn't been able to do anything except punch things a little harder, or ... Well, it's better than nothing. Turning toward the Wolf Knight, Kellan hurls one of the hilts as hard as he can. It bounces uselessly off his armor—then flies back to Kellan's hand. "Oops," he says. "What was—All right. All right, okay. I've got this. Follow me," Ruby calls. Her groan hurts, but he can't blame her. It would be great if he #emph[did] know how to use them. He could probably slice clean through an oak tree with a fae-wrought blade, but as it stands ... he's kind of a joke. "I'm sorry, I'm still learn—wait, what're those?" As they run beneath the massive body of a dead invader, they come upon half a dozen ... creatures. If a toddler's malformed drawing of a wolf were given form, muscle, and fang, it might resemble one of these beings. Their forelegs and haunches are dense with power, their muzzles slick with blood. "Witchstalkers!" Ruby answers. "You're not magical, right?" Kellan winces. "I, uh, I'm not sure!" "Well, it's time to find out," Ruby says. He expects her to stop, or hide, or lead the witchstalkers back toward the Wolf Knight, but Ruby does no such thing. She runs toward the pack of witchstalkers, weaving between them, her cloak dragging past their faces. By the time she's cleared them, she's wearing a giddy smile beneath the hood. Easy enough for her to do. There's a pit in Kellan's stomach as he looks at the witchstalkers. His lord's gifts, or his father's blood, might doom him should he risk it. But he has his mother's love to keep him safe—a thick cloak that's fought off plenty so far. He throws up his own hood. If Ruby can do it, Kellan can, too. Hard as he can, he runs between the gathered witchstalkers. He's halfway through before he realizes the high-pitched yelling he hears is coming from his own mouth, a sound between the wail of a ghost and the laugh of a child at play. Every beat of his heart feels stolen and glorious. Though he doesn't linger to see if the creatures will attack him, when he clears the pack, he still finds himself doubling over with relief. They didn't bite him. Not even a nibble. He laughs in earnest. He did it! He really did it. His first brush with adventure! Ruby offers Kellan a hand up and he takes it, looking back the way they came. The Wolf Knight's stepped into the clearing. #figure(image("002_Episode 2: Wandering Knight, Budding Hero/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "Come on, come on ..." whispers Ruby. "He's got to be magical!" Two youths, hoarding their breath like a dragon hoards gems, stare down the Wolf Knight. Their pursuer, in turn, lets out another wordless howl. The witchstalkers answer. As one their heads perk and they turn toward the Wolf Knight, their growls resonating in Kellan's chest. The Wolf Knight runs into the woods as the witchstalkers give chase. "I think we're safe," he says, huffing. He grins. "You did it, Ruby!" She stares at the witchstalkers as they take off. It looks like she can't believe she's still standing. "Yeah, I guess I did," she says. Relieved, Kellan turns and notices the cabin for the first time. He's not sure how neither of them saw it before now. Maybe this is what his mother meant whenever she talked about the chaos of a melee—when you're busy trying to make sure you get out of something alive, you aren't always paying attention to the horizon. Still, it's hard to miss. The house is thorny and black, as if made from blackberry brambles, standing twice as tall as those back home. Violet windows pulse with light from within. All around the house there is a thicket of violet mist. "Ruby," Kellan says, taking her hand to get her attention. "Look! That's the witch's house, it's got to be." It takes her only a glance to agree with him. "I'll be damned, you're right," she says. "What should we do?" "Those windows are huge. We can try and peek inside, then figure out how we're going to defeat her," Kellan says. He hopes Ruby won't ask for more details than that. Luckily, she doesn't. The two of them slink through the twisting trees and thick bushes toward the house. Burrs cling to Kellan's cloak; he thinks of each one as a well-wish from his father. He's so close to finishing this first witch off. Will Talion give him a hint? Maybe a riddle? The thought of discovering more is as tempting as fresh fruit on a hot summer day. The brush allows them to get right beneath the lowest of the witch's windows. Here at the bottom the glass is thick, distorting the two figures in the cabin. One, Kellan thinks, is the witch: she walks in a broad circle around a large darkness in the center of the room. Smoke rises from whatever it is she's guarding. The other figure is slumped over, their back to the window. "A real cauldron," Kellan mumbles. "I wonder what she's using it for ..." "Eating people," answers Ruby readily. "I've heard a couple rumors that there was someone nearby boiling people's bones into stew. And that's definitely a cauldron, and she's definitely got someone tied up ..." "Witches don't eat people," Kellan says. "My mom was almost a witch, and she'd never do anything like that." "Have you considered that maybe that's why she's #emph[almost] a witch, not #emph[is ] a witch?" Ruby asks. She tugs on his cloak. "Get down, I think she's coming." She is. The witch's pacing around her bubbling cauldron brings her toward them now. Kellan and Ruby duck beneath the windowsill in time to avoid her gaze, but only just. Even through the glass her eyes are wicked and piercing, a violet not unlike the glow surrounding them. "So, what's the plan?" Ruby asks. Kellan puts a hand to his chin as if he's considering one. The deception, such as it is, lasts a second at most. Then he shrugs. "We're going to play it by ear." "What?" Ruby hisses, eyes narrowing. "You can't be serious. That's a real live witch in there!" "We aren't going to be able to win with magic, and we don't have any weapons," Kellan says. He slinks around the corner of the cabin, careful to keep from touching the cursed plumes of smoke along the ground. "And I've got this new friend who taught me the value of improvising." "Improvising's one thing, but this is asking for trouble," Ruby says, following him anyway. Kellan waves at her to stay put. He points to his eyes, then to the window. "Let me know when she's facing away from the door," he says. Ruby frowns, but stays put beneath the window. Meanwhile, Kellan leans an ear against the door. From within he hears a keening song. Delivered without much care for rhythm or melody, the singer is nonetheless enthralled with the sound of her own voice. #emph["When I was hungry a knight wandered in, wild at heart and covered in tin ..."] A knight? She's going to eat a #emph[knight] ? #emph["How easy it was to beat her, in truth! But how hard to eat her without breaking a tooth!"] Sweat rolls down Kellan's brow. Ruby was right. This isn't any normal witch—she's nothing like his mother. If they don't act fast, that knight's probably going to die. But what to do? He doesn't have much time to think. From around the corner, he sees a blur of red—another apple thrown by his new friend. A fine signal, he thinks. Until he hears the apple #emph[thunk] against metal. A glance over his shoulder is all he can afford—but he already knows what he's going to see. The Wolf Knight. Had he already fought off the witchstalkers? Yes—that's his shape slinking through the mists, covered in blood. He can't leave Ruby outside with him, and he can't let that witch eat the knight. If he saves the knight inside, maybe she can fight off the one outside. And maybe when the witch is gone, the Wolf Knight will just ... fade away. That's what happened to conjured guardians in stories, anyway. Kellan plucks a burr from his cloak. "Dad, if you're listening," he says, "please make me brave enough to do this." He doesn't wait for an answer, because he knows he can't. He just has to have faith that it worked. Kellan opens the door, quiet and quick. As a mouse slinking through a cat's domain, he scurries over to the center of the room where the witch continues her awful song. Lashed to a rod near the bubbling cauldron is a rugged woman clad in armor, her right arm made from solid wood. Bleary and delirious, she locks eyes with him. Kellan can see the hope in her when she does that. #emph["Oh, brave knight, what shall I do? Boil and bubble, broth and brew—oh brave knight, I'll make you a stew!"] The witch is so preoccupied with stirring her foul smelling brew that she has not yet noticed him. She stands before the cauldron, leveling a crooked finger at the knight. For once she drops the sing-song. "But what spice to use, hm? I don't suppose you know what you taste best with, do you?" "Die in a fire," the knight spits. She glances at Kellan, then gives him a covert nod. The witch, however, turns back toward the cauldron. She shakes her head, then reaches into her pocket. "That isn't very kind. I need this fire for cooking you. There's an art to this, you know. I can't just throw anything in there and hope it'll end up gourmet." Whatever's in that bag she dumps in makes Kellan want to vomit, but he keeps it together. He has a job to do—and he has an opening here. Like the rams on his farm, he lowers his head and charges. "You're the one that's cooked!" Kellan answers. #figure(image("002_Episode 2: Wandering Knight, Budding Hero/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) He hears the witch howl when he slams into her, and he hears her scream as she falls into the cauldron, but he tries not to think about the implications of any of it. A puff of black smoke rises, the smell so acrid it brings tears to his eyes. Kellan runs toward the knight. There'll be time to think about what he's done later—right now, he needs to make sure Ruby's safe. And the best way to do that is to free this woman. "Can you fight?" he asks, hands working the knots around her wrists. One of her arms, he notices, is made of a strange, pliable wood that struggles just like flesh and muscle. "Grrkh ... If you get me ... my hammer." It isn't an answer that fills him with confidence, but it's what he's got. The ropes fall away. He scans the chaotic mess of the cabin in search of a war hammer—there. It's slumped against a counter covered in all manner of viscera and gore, with jars labeled "Eye of Newt" and "Toe of Frog." As he runs for the hammer, Ruby dashes in through the door. "He's almost here!" "The knight's going to save us," Kellan says. He can't lift the hammer, but he can drag it over. "She can still fight!" He hands the hammer to the knight, who stands. Or tries to. But Kellan learns here an important lesson: not all knights can be heroes all the time. This one is far too exhausted, far too beaten. She collapses back into her ignoble seat. Kellan's heart is somewhere in his throat when the Wolf Knight walks through the door. Covered in blood, his sword freshly used. Had they come all this way only to—? "Get up!" Kellan says, shoving the knight. "You can do this, come on! You used to defend the Realm!" "That was a long time ago," the knight mumbles. Yet once more she tries to stand—and once more she falls. The Wolf Knight stops at the threshold. Ruby hurls a jar of something foul. Clay shatters against his armor. He turns toward her. "Ruby," bellows the Wolf Knight. "I've finally found you." Ruby's eyes go wide. She stands from her hiding spot, lowers her hood. The Wolf Knight doffs his helm. Beneath is the face of a grizzled woodsman, his beard thick and his hair unkempt—yet his eyes are kind, and his smile warm. He spreads his arms. "Ruby, it's me." "Peter!" Ruby shouts. She runs to him, and he is there to meet her, lifting her up and spinning her around before he sets her down on her feet. "What happened? Are you all right?" "I don't know. I've never seen this place before today. I went out hunting, and there was this awful song," he says. "This is a witch's cabin, isn't it? She must have enchanted me. I'm so sorry I scared you, but I'm happy you're safe." Ruby throws her arms around him. "Don't worry," she says. "I'll forgive you for that if you forgive me for siccing the witchstalkers on you." He tousles her hair. "I'd expect no less from you. You always were the clever one in the family," he says. Then, he turns toward Kellan and the knight. "You there—boy. You helped my sister, didn't you? Whatever you ask of me, only speak it, and I will grant it, if it's within my power to do so." "She did most of the work," he says. "But ... if you want to help, I have to get the cauldron to my liege. They said I needed to show them I'd ..." "Say no more. You need someone to carry it, and I shall," Peter says. His eyes fall on the injured knight and he winces. "I must have caused you great harm. My apologies." The knight groans. "Wasn't a fair fight, between you and that crone." "Stay here. Once we've moved the cauldron to its destination, Ruby and I can make you a healing salve. There are plenty of ingredients here, and I think I remember something of herblore." If the knight has any counterargument, her mind is too addled with pain to make it. Peter enlists Ruby and Kellan's help with the cauldron; the two of them together hold up one side, while he lifts the other, bearing the majority of the weight. Kellan tries not to think about what's sloshing around inside. Together they're able to move it through the threshold—but instead of the violet mists, Talion's court greets them on the other side. This time, the Kindly Lord does not make themself visible. Kellan knows they are present only when familiar music plays around them. There are no pleasantries this time: their advice is quick and to the point. "#emph[Hylda is the next witch you seek. Her magic is great, her skill yet greater; she has concealed herself from my eyes. But consult the mirror Indrelon, and you may yet find her] . #emph[Torn from Castle Vantress by <NAME>, it now lies far from its home. Worry not, my wisdom will save you the trouble of hunting it down.] #emph[A beanstalk grows not half a day's ride from here. Climb it, and you shall find the mirror at its peak] ." No sooner have they finished speaking than the court disappears, forgotten as a dream. The trio stands once more before the cabin. Ruby's staring at him. "Your liege is the fae king," she says. "Is that ... does that upset you?" Kellan says. "I was going to ask if you wanted to come. I could really use your help. Both of you." "I'd be of no help to you, wounded as I am," Peter says. "I'll not be in fighting shape for days yet." Ruby looks from Kellan to Peter and back again. She sighs. "You helped me find my brother, so I'll help. But let's rest for a while. We can tend to the knight's wounds and figure out what it is we're going to do." Kellan's fingers are shaking. "But ... do you hate that I'm working with the fae?" He's surprised how much Ruby's scoff sets him at ease. "Are you kidding? That just means you're braver than I thought." And that? That, he can live with.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/pintorita/0.1.0/lib.typ
typst
Apache License 2.0
#import "./pintorita.typ": render
https://github.com/jbro/supernote-templates
https://raw.githubusercontent.com/jbro/supernote-templates/main/title-page.typ
typst
The Unlicense
#import "include/a5x-template.typ": template #show: doc => template(doc) #import "include/elements.typ": titled-box, task-lines, note-lines, week-box #set align(center) #box(width: 100%)[ #box(width: 90%)[ #v(10mm) #note-lines(1) #v(10pt) #note-lines(1) #v(20mm) #let g=30pt #let l=8 #box(width: l*g, height: l*g)[ #for x in array.range(1, l) { for y in array.range(1, l) [ #place(line(start: (x*g, 0pt), end: (x*g, y*g+g), stroke: gray)) #place(line(start: (0pt, y*g), end: (x*g+g, y*g), stroke: gray)) ] } ] #v(20mm) #let f="Routed Gothic" #text("Engineering\n", font: f, size: 34pt, style: "italic") #text("Notebook", font: f, size: 56pt, style: "italic") ] ]
https://github.com/touying-typ/touying
https://raw.githubusercontent.com/touying-typ/touying/main/examples/aqua-zh.typ
typst
MIT License
#import "../lib.typ": * #import themes.aqua: * #show: aqua-theme.with( aspect-ratio: "16-9", config-info( title: [标题], subtitle: [副标题], author: [作者], date: datetime.today(), institution: [机构], ), ) #set text(lang: "zh") #title-slide() #outline-slide() = 第一节 == 小标题 #slide[ #lorem(40) ] #slide[ #lorem(40) ] == 总结 #slide(self => [ #align(center + horizon)[ #set text(size: 3em, weight: "bold", self.colors.primary) THANKS FOR ALL 敬请指正! ] ])
https://github.com/ecrax/packages
https://raw.githubusercontent.com/ecrax/packages/main/README.md
markdown
# Packages > A collection of my own packages for Typst To use the packages, clone this repo at one of the following locations: - `$XDG_DATA_HOME` or `~/.local/share` on Linux - `~/Library/Application Support` on macOS - `%APPDATA%` on Windows and import it using the `local` namespace: ``` #import "@local/mypkg:1.0.0": * ```
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/closure-09.typ
typst
Other
// Don't leak environment. #{ // Error: 16-17 unknown variable: x let func() = x let x = "hi" func() }
https://github.com/bigskysoftware/hypermedia-systems-book
https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/lib/style.typ
typst
Other
#import "./definitions.typ": * #import "./code-callouts.typ": code-with-callouts #let inside-cover(title, authors) = page( header: none, )[ #set align(start + horizon) #set par(leading: 10pt, justify: false) #show heading: set text(size: 3em, font: display-font) #skew( -0.174, // -10deg upper( text(style: "oblique", heading(level: 1, outlined: false, title)), ), ) #box(height: 1em) #set text(font: secondary-font) #grid(gutter: 1em, columns: authors.len() * (auto,), ..authors) ] #let page-header() = context { counter(footnote).update(0) set text(font: secondary-font, size: 10pt) let h1 = query(<heading-here>) .any(h => h.location().page() == here().page()) if not h1 { let reference-title(title, numbering-style) = [ #if title.numbering != none [ #numbering(numbering-style, counter(heading).at(title.location()).last()) ] #title.body ] if calc.odd(here().page()) [ // verso #set align(end) #let titles = query(heading.where(level: 1).or(heading.where(level: 2)).before(here())) #if titles.len() > 0 [#reference-title(titles.last(), "1.") #sym.dot.c] #counter(page).display() ] else [ // recto #counter(page).display() #let titles = query(heading.where(level: 1).before(here())) #if titles.len() > 0 [#sym.dot.c #reference-title(titles.last(), "I.")] ] } } #let hypermedia-systems-book(title, authors: (), frontmatter: []) = content => [ #set text(font: body-font, size: 12pt, lang: "en") #set par(leading: .5em) #show raw: set text(font: mono-font) #show raw.where(block: false): set text(size: 11 * 1em / 12) // 11pt in 12pt body #show raw.where(block: true): set text(size: 9pt) #show heading.where(level: 1): set text(font: display-font, size: 24pt) #show heading.where(level: 2): set text(font: display-font, size: 20pt) #show heading.where(level: 3): set text(font: secondary-font) #show heading.where(level: 4): set text(font: secondary-font) #show heading.where(level: 5): set text(font: secondary-font) #show heading.where(level: 6): set text(font: secondary-font) #set par(justify: true, first-line-indent: 1em, leading: leading) #show par: set block(spacing: leading) #show list: set par(justify: false) #show list: set block(spacing: 0pt, inset: 0pt) #set list( indent: 1em, body-indent: .6em, spacing: 5pt, ) #set enum( numbering: (..args) => { set text(font: secondary-font, number-type: "old-style") box(width: 1em, { numbering("1.", ..args) h(.5em) }) }, indent: 1em, body-indent: 0pt, number-align: start, ) #set terms(hanging-indent: 1em) #show terms: it => { set par(first-line-indent: 0pt); it } #set quote(block: true) #show quote: set block(spacing: 1em) #show quote: set text(style: "italic") // #show quote.attribution: set text(style: "normal") #set image(fit: "contain", width: 50%) #show figure: it => { show figure.caption: align.with(if it.kind == raw { start } else { center }) show figure.caption: set text(font: secondary-font, size: 10pt) it } #set figure(placement: auto) #show figure.where(kind: raw): it => { show raw.where(block: true): set block(width: 100%, stroke: none, spacing: 0pt) block( inset: (x: 1em, y: .5em + leading), spacing: 0pt, width: 100%, { if it.caption != none { set text(size: 11pt, font: secondary-font) pad(it.caption, top: 0pt, bottom: .5em) v(-.5em) } it.body } ) } #show raw.where(block: true): code-with-callouts #show link: it => { if type(it.dest) != str or it.body == text(it.dest) { it } else { it.body footnote(it.dest) } } #set page( width: 8.5in, height: 11in, margin: (inside: 1.75in, outside: 1in, top: 1in, bottom: 1.25in), header: page-header(), ) #set document(title: title, author: authors) // #region FRONTMATTER #[ #inside-cover(title, authors) #frontmatter #page([], header: none, footer: none) #pagebreak(to: "odd") = Contents #set par(first-line-indent: 0pt, justify: false) #show linebreak: [] #show outline.entry: it => { show regex("\\d"): text.with(number-width: "tabular") show grid: set block(spacing: 0pt) box( inset: (left: (it.level - 1) * 1em), grid( columns: (1fr, auto), column-gutter: 1em, par( it.body, hanging-indent: (it.level) * 12pt + 3pt ), it.page, ) ) } #outline(indent: 1em, depth: 4, title: none)<table-of-contents> ] // #endregion FRONTMATTER // #region BODY #[ // Chapter count #let chapter-counter = counter("chapter") #show heading.where(level: 2): it => [ #if it.at("numbering") != none { chapter-counter.step() } #chapter-heading(it) ] #show heading.where(level: 1): it => [ #part-heading(it) // Override heading counter so chapter numbers don't reset with each part. // TODO: this doesn't work on the first heading in each part #locate(loc => counter(heading).update((..args) => (args.pos().at(0), chapter-counter.at(loc).last()))) ] #set heading( supplement: it => ([Part], [Chapter]).at( it.at("depth", default: 2) - 1, default: [Section]), numbering: (..bits) => if bits.pos().len() < 2 { // Show part number only on parts. numbering("I.", ..bits) } else { // Discard part number otherwise. numbering("1.1.", ..bits.pos().slice(1)) }, ) #content ] // #endregion BODY // #region BACKMATTER #[ #show heading.where(level: 1): chapter-heading = Index #columns(2, gutter: 2em, { set text(font: secondary-font, size: .9em) set par(first-line-indent: 0pt) show heading: none make-index() }) ] // #endregion BACKMATTER ]
https://github.com/SillyFreak/typst-packages-old
https://raw.githubusercontent.com/SillyFreak/typst-packages-old/main/crudo/src/lib.typ
typst
MIT License
/// _raw-to-lines_: extract lines and properties from a `raw` element. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.r2l(```txt /// first line /// second line /// ```) /// ````) /// /// Note that even though you will usually want to use this on raw _blocks_, /// this is not a necessity: /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.r2l( /// raw("first line\nsecond line") /// ) /// ````) /// /// - raw-block (content): a single `raw` element /// -> array #let r2l(raw-block) = { let (text, ..fields) = raw-block.fields() (text.split("\n"), fields) } /// _lines-to-raw_: convert lines into a `raw` element. Properties for the created element can be /// passed as parameters. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.l2r( /// ("first line", "second line") /// ) /// ````) /// /// Note that even though you will usually want to construct raw _blocks_, /// this is not assumed. To create blocks, pass the appropriate parameter: /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.l2r( /// ("first line", "second line"), /// block: true, /// ) /// ````) /// /// - lines (array): an array of strings /// - ..properties (arguments): properties for constructing the new `raw` element /// -> content #let l2r(lines, ..properties) = { raw(lines.join("\n"), ..properties) } /// Transforms all lines of a raw element and creates a new one with the lines. All properties of /// the element (e.g. `block` and `lang`) are preserved. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.transform( /// ```typc /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// lines => lines.filter(l => { /// // only preserve non-comment lines /// not l.starts-with(regex("\s*//")) /// }) /// ) /// ````) /// /// - raw-block (content): a single `raw` element /// - mapper (function): a function that takes an array of strings and returns a new one /// -> content #let transform(raw-block, mapper) = { let (lines, fields) = r2l(raw-block) lines = mapper(lines) l2r(lines, ..fields) } /// Maps individual lines of a raw element and creates a new one with the lines. All properties of /// the element (e.g. `block` and `lang`) are preserved. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.map( /// ```typc /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// line => line.trim() /// ) /// ````) /// /// - raw-block (content): a single `raw` element /// - mapper (function): a function that takes a string and returns a new one /// -> content #let map(raw-block, mapper) = { transform(raw-block, lines => lines.map(mapper)) } /// Filters lines of a raw element and creates a new one with the lines. All properties of the /// element (e.g. `block` and `lang`) are preserved. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.filter( /// ```typc /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// l => not l.starts-with(regex("\s*//")) /// ) /// ````) /// /// - raw-block (content): a single `raw` element /// - test (function): a function that takes a string and returns a new one /// -> content #let filter(raw-block, test) = { transform(raw-block, lines => lines.filter(test)) } /// Slices lines of a raw element and creates a new one with the lines. All properties of the /// element (e.g. `block` and `lang`) are preserved. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.slice( /// ```typc /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// 1, 3, /// ) /// ````) /// /// - raw-block (content): a single `raw` element /// - ..args (arguments): the same arguments as accepted by /// #link("https://typst.app/docs/reference/foundations/array/#definitions-slice")[`array.slice()`] /// -> content #let slice(raw-block, ..args) = { transform(raw-block, lines => lines.slice(..args)) } /// Extracts lines of a raw element similar to how e.g. printers select page ranges. All properties /// of the element (e.g. `block` and `lang`) are preserved. /// /// This function is comparable to @@slice() but doesn't have the the option to specify the _number_ /// of selected lines via `count`. On the other hand, multiple ranges of pages can be selected, and /// indices are one-based by default, which may be more natural for line numbers. /// /// Lines are selected by any number of parameters. Each parameter can take either of three forms: /// - a single number: that line is included in the output /// - an array of numbers: these lines are included in the output (a major usecase being `range()` /// -- but beware that `range()` uses an exclusive end index) /// - a string containing numbers (e.g. `1`) and inclusive ranges (e.g. `1-2`) separated by commas. /// Whitespace is allowed. /// /// All three kinds of parameters can be mixed, and lines can be selected any number of times and in /// any order. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.lines( /// ```typc /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// 2, "1,3-4", range(2, 4), /// ) /// ````) /// /// - raw-block (content): a single `raw` element /// - ..line-numbers (arguments): any number of line number specifiers, as described above /// - zero-based (boolean): whether the supplied numbers are one-based line numbers or zero-based /// indices /// -> content #let lines(raw-block, ..line-numbers, zero-based: false) = { assert(line-numbers.named().len() == 0, message: "only positional arguments can be given") let line-numbers = line-numbers.pos() let offset = if zero-based { 0 } else { -1 } transform(raw-block, lines => { let l(num) = lines.at(num + offset) for spec in line-numbers { if type(spec) == int { // make an array with a single line number spec = (spec,) } else if type(spec) == str { // convert the string into an array with a single line number spec = { for part in spec.split(",") { let bounds = part.split("-").map(str.trim) if bounds.len() == 1 { // a single page - already in an array bounds.map(int) } else if bounds.len() == 2 { // a page range let (lower, upper) = bounds.map(int) // make it inclusive array.range(lower, upper + 1) } else { panic("invalid page range: " + spec) } } } } assert(type(spec) == array, message: "page range must be an int, array, or a string") spec.map(l) } }) } /// Joins lines of multiple raw elements and creates a new one with the lines. All properties of the /// `main` element (e.g. `block` and `lang`) are preserved. /// /// #example(ratio: 1.1, scale-preview: 100%, ```` /// crudo.join( /// ```java /// let foo() = { /// // some comment /// ... do something ... /// } /// ```, /// ```typc /// let bar() = { /// // some comment /// ... do something ... /// } /// ```, /// main: -1, /// ) /// ````) /// /// - ..raw-blocks (content): any number of `raw` elements /// - main (function): the index of the `raw` element of which properties should be preserved. /// Negative indices count from the back. /// -> content #let join(..raw-blocks, main: 0) = { assert(raw-blocks.named().len() == 0, message: "only positional arguments can be given") let raw-blocks = raw-blocks.pos() let contents = raw-blocks.map(r2l) let lines = contents.map(c => c.at(0)).join() let fields = contents.at(main).at(1) l2r(lines, ..fields) }
https://github.com/Nrosa01/TFG-2023-2024-UCM
https://raw.githubusercontent.com/Nrosa01/TFG-2023-2024-UCM/main/Memoria%20Typst/template.typ
typst
// 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: "", titleEng: "", degree: "", course: "", abstract: [], authors: (), directors: (), date: none, body, ) = { // Set the document's basic properties. set document(author: authors, title: title) set page(numbering: "1", number-align: center) set text(font: "New Computer Modern", lang: "es", hyphenate: false) show math.equation: set text(weight: 400) // Set paragraph spacing. show par: set block(above: 1.2em, below: 1.2em) set heading(numbering: "1.1") set par(leading: 0.75em) align(center + horizon)[ #block(text(weight: 1000, 1.5em, course)) #block(text(weight: 700, 1.0em, rgb(77,77,77), degree)) #v(2.2em, weak: true) // Title row. #align(center)[ #rect(stroke: (top: 1pt, bottom: 1pt), inset: 20pt)[ #block(text(weight: 700, 1.5em, title)) #v(10pt) #block(text(weight: 700, 1.0em, rgb(77,77,77), titleEng)) ] #v(2.2em, weak: true) // #date ] #pad( align(center)[ #image("images/escudoUCM.svg", width: 25%) #v(-0.5em, weak: true) Universidad Complutense de Madrid ] ) #v(2.5em, weak: true) // Author information. Alumnos #pad( x: 2em, stack(spacing: 8pt, ..authors.map(author => align(center, strong(author)))) ) Dirección #pad( x: 2em, stack(spacing: 8pt, ..directors.map(author => align(center, strong(author)))) ) #align(center)[ #v(1.5em, weak: true) #date ] // Abstract. // #pad( // x: 2em, // top: 1em, // bottom: 1.5em, // align(center)[ // #heading( // outlined: false, // numbering: none, // text(0.85em, smallcaps[Abstract]), // ) // #abstract // ], // ) ] pagebreak() // Main body. set par(justify: true) body }
https://github.com/Bi0T1N/typst-iconic-salmon-svg
https://raw.githubusercontent.com/Bi0T1N/typst-iconic-salmon-svg/main/examples/minimal_example.typ
typst
MIT License
// #import "@preview/iconic-salmon-svg:1.0.0": github-info, gitlab-info #import "../iconic-salmon-svg.typ": github-info, gitlab-info This project was created by #github-info("Bi0T1N"). You can also find me on #gitlab-info("GitLab", rgb("#811052"), url: "https://gitlab.com/Bi0T1N").
https://github.com/chamik/gympl-skripta
https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-dila/10-bila-nemoc.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/helper.typ": dilo, replika #dilo("Bílá nemoc", "nemoc", "<NAME>", "", "Meziválečná lit.", [ČS -- První republika], "1937", "drama", "válečná tragédie") #columns(2, gutter: 1em)[ *Téma*\ touha pro zastavení války, varování před nacismem *Motivy*\ individualita, touha po moci/slávě *Časoprostor*\ autorova současnost, místo neurčité (symbolika a původ však naznačuje Německo a Česko) *Postavy* \ _<NAME> (Dědina)_ - naivní, snaží se zastavit válku (ref. na R. U. R @rur[]) \ _Maršál_ - voják, protipól Galéna, diktátor (připodobnění <NAME>i) \ _<NAME>_ - přítel Maršála, výrobce zbraní \ _Sigelius_ - dvorní rada, touží po slávě *Kompozice*\ chronologická, tragický konec // *Vypravěč* *Jazykové prostředky*\ spisovná čeština, dialogy, cizí slova, nářečí, knižní slovní zásoba // TODO: co tam dělá Sigelius?? tu postavu si ani nepamatuju xd *Obsah*#footnote[V původní verzi hry Dr. G. posílá recept na lék svému příteli do zahraničí, takže naděje na konci zůstává. Dneska se to takhle ale už nehraje.]\ V zemi se rozmohla smrtelná bílá nemoc, na kterou našel lék mladý doktor Galén. Ten na začátku léčí pouze chudé; když nemoc chytí zbrojař Krüg, odmítne ho vyléčit, pokud Maršál neuzavře mír; nesvolí a Krüg se zoufalství spáchá sebevraždu. #colbreak() Nakonec nemoc chytne i Maršál a po přemlouvání se rozhodne za svůj život mír uzavřít. Na cestě do paláce je však Galén zastaven pro-válečným davem, kterým je ušlapán. Válka vypukne. *Literárně historický kontext*\ Zfilmováno Hugem Haasem už v roce vydání. Působí jako varování před rozpínáním nacistického Německa. *Autor*\ <NAME>, dramatik a spisovatel. <NAME> <NAME>. Člen skupiny Pátečníci. Dobrý přítel <NAME> herečky <NAME>. Zemřel pár měsíců před okupací roku 1938.#footnote[Nejspíš pro jeho dobro; po abdikaci Edvarda Beneše se stal defakto symbolem první republiky a tak trochu obětním beránkem.] Jeho práce poukazuje na přílišnou rychlost lidského pokroku, kritizuje fašismus, podporuje pacifismus. *Další díla*\ Válka s mloky -- próza, antiutopie\ <NAME>. (@rur[]) -- varování před zneužitím technologií\ <NAME> -- úvaha nad nesmrtelností ] #pagebreak() *Ukázka* #table(columns: 2, stroke: none, ..replika("", [_Ulice._]), ..replika("", [_Zástup lidí s prapory. Zpěv. Do toho volání: Ať žije maršál! Ať žije válka! Sláva maršálovi!_]), ..replika([Syn z prvního aktu], [A všichni najednou: Ať žije válka!]), ..replika([Zástup], [Ať žije válka!]), ..replika([Syn], [Nás vede maršál!]), ..replika([Zástup], [Nás vede maršál!]), ..replika([Syn], [Ať žije maršál!]), ..replika([Zástup], [Maršál! Maršál!]), ..replika("", [_(Houkání auta, které si nemůže zástupem prorazit cestu.)_]), ..replika([Dr. Galén], [_(vyběhne s kufříkem v ruce)_ Doběhnu pěšky... Dovolte prosím... Prosím vás, pusťte mě... někdo mě čeká...]), ..replika([Syn], [Občané, volejte: Ať žije maršál! Ať žije válka!]), ..replika([Dr. Galén], [Ne! Válka ne! Nesmí být žádná válka! Poslyšte, ne, válka nesmí být!]), ..replika([Výkřiky], [Co to říkal? -- Zrádce! -- Zbabělec! -- Mažte ho!]), ..replika([Dr. Galén], [Musí být mír! Pusťte mne -- Já jdu k maršálovi --]), ..replika([Výkřiky], [Urazil maršála! -- Na lucernu! -- Zabte ho!]), ..replika("", [_(Hlučící zástup se zavře kolem Dr. Galéna. Zmatená vřava.)_]), ..replika("", [_(Zástup se rozestupuje. Na zemi leží Dr. Galén a jeho kufřík.)_]), ..replika([Syn], [_(kopne do něho)_ Vstávej, potvoro! Koukej mazat, nebo --]), ..replika([Jeden ze zástupu], [_(klekne k ležícímu)_ Počkat, občane. Ono je po něm.]), ..replika([Syn], [Žádná škoda. O jednoho zrádce míň. Sláva maršálovi!]), ..replika([Zástup], [Ať žije maršál! Maršál! Mar-šál!]), ..replika([Syn], [_(otevře kufřík)_ Hele, byl to nějaký doktor! _(Rozbíjí lahvičky s léky a dupe na ně.)_ Tak! Ať žije válka! Ať žije maršál!]), ..replika([Zástup], [_(valí se dál)_ Maršál! Mar-šál! Ať – žije – maršál!]), ..replika("", [_Opona._]), ) #pagebreak()
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/build-drivetrain.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: "Build: Drivetrain", type: "build", date: datetime(year: 2023, month: 7, day: 14), author: "<NAME>", witness: "Violet Ridge", ) Once we completed our CAD design of our robot, we were able to begin building it. Due to most of our team being on vacation at this time, Alan was the only one building on the drivetrain. This made progress slower than it should have been. #grid( columns: (1fr, 1fr), gutter: 20pt, [ = 2023/07/14 1. Cut full length C-channel down to 30 holes in order to make the long bars on the side. 2. Added the bearings to the C-channel 3. Cut 5 hole long C-channel for the motor and gear mounts 4. Mounted the 5 hole C-channel to the 30 hole C-channel. ], image("/assets/drivetrain/build-log/1.jpg"), image("/assets/drivetrain/build-log/2.jpg"), [ = 2023/07/15 1. Cut the rest of the 5 long C-channels 2. Mounted and braced them to the 30 long C-channels ], [ = 2023/07/21 1. Cut 3 30 long C-channels to serve as the perpendicular braces 2. Mounted the 30 long C-channels to the other 30 long C-channels from before #admonition( type: "note", [ We did not have the required 84 tooth gears and 4" omni wheels required to finish the drivetrain, so we'll have to wait till they arrive. ], ) ], image("/assets/drivetrain/build-log/3.jpg"), image("/assets/drivetrain/build-log/4.jpg"), [ = 2023/07/22 1. Mounted gears to frame 2. Mounted wheels to drivetrain 3. Filled axles with the correct amount of spacers 4. Added mount points for quick swap motors #admonition( type: "note", [ We did not have the required 48 tooth gears to be able to finish the drivetrain, so we'll have to wait till next meeting to for them to arrive. ], ) ], [ = 2023/07/29 1. Mounted remaining gears 2. Mounted remaining motors 3. Mounted battery, brain, and radio to temporary locations. #admonition( type: "build", )[ The drivetrain is finally completed, meaning that we can now move on to testing. ] ], image("/assets/drivetrain/build-log/5.jpg"), )
https://github.com/akshaybabloo/CV
https://raw.githubusercontent.com/akshaybabloo/CV/master/resume.typ
typst
MIT License
#let data = yaml("data.yaml") #let darkblue = rgb(0, 0, 128) #let mediumblue = rgb(64, 97, 158) /// Adds a section title and a line underneath /// /// - title (string): the title of the section /// -> content #let section(title)={ v(15pt) set text(weight: "bold") text(title, size: 12pt, fill: mediumblue) linebreak() v(-6pt) line(length: 100%, stroke: mediumblue) v(2pt) } /// Adds a link to the document with an underline /// /// - dest (string): the destination of the link /// - label (string): the label of the link /// -> content #let linker(dest, label)={ underline(text(link(dest)[#label], fill: mediumblue), offset: 2pt) } #{ set text(font: "Roboto", size: 9pt, fallback: true) set align(center) // Personal Information text(data.name, fill: darkblue, size: 30pt) linebreak() v(2pt) let count = 0 let info_length = data.additional_info.len() for (key, value) in data.additional_info { if "phone_number" == key { text([#data.additional_info.phone_number], size: 10pt) if count < info_length - 1 [ | ] } if "linkedin" == key { text([#linker( data.additional_info.linkedin, data.additional_info.linkedin.replace("https://", ""), )], fill: mediumblue, size: 10pt) if count < info_length - 1 [ | ] } if "github" == key { text([#linker( data.additional_info.github, data.additional_info.github.replace("https://", ""), )], fill: mediumblue, size: 10pt) if count < info_length - 1 [ | ] } if "website" == key { text([#linker( data.additional_info.website, data.additional_info.website.replace("https://", ""), )], fill: mediumblue, size: 10pt) if count < info_length - 1 [ | ] } if "email" == key { text( [#linker("mailto:" + data.additional_info.email, data.additional_info.email)], fill: mediumblue, size: 10pt, ) if count < info_length - 1 [ | ] } count += 1 } set align(left) set par(justify: true) // Personal Statement if "personal_statement" in data { section("Personal Statement") text(data.personal_statement) } // Core Competencies if "competencies" in data { section("Core Competencies") table( columns: (auto, auto), align: horizon, stroke: 0.5pt, ..for competencies in data.competencies { ([#competencies.name], [#competencies.competencies.join(", ")]) }, ) } // Work Experience if "experience" in data { section("Work Experience") table( columns: (90pt, auto), align: start, stroke: none, column-gutter: 25pt, row-gutter: 10pt, ..for work in data.experience { (text(work.start_date + " - " + work.end_date, style: "italic"), [ *#work.title at #work.company* \ #emph(work.location) \ #eval(work.description, mode: "markup") #if work.technologies.len() > 0 [ #v(-3pt) *Technologies:* #work.technologies.join(", ") ] ]) }, ) } // Education if "education" in data { section("Education") for education in data.education { [ *#education.course* \ #education.institution \ #emph(education.location) \ #emph(education.start_date + " - " + education.end_date) #v(5pt) ] } } // Key skills and characteristics if "skills" in data { section("Key Skills and Characteristics") for skill in data.skills { [- #skill] } } // Activities and Interests if "activities" in data { section("Activities and Interests") for activity in data.activities { [- #activity] } } // References if "references" in data { section("References") for reference in data.references { [ *#reference.name* \ #reference.position \ #emph(reference.company) \ #underline( text(link("mailto:" + reference.email)[#reference.email], fill: mediumblue), offset: 2pt, ) \ #reference.phone #v(5pt) ] } } }
https://github.com/diogro/memorial
https://raw.githubusercontent.com/diogro/memorial/master/UFSCAR-2024/plano_trabalho.typ
typst
#align(left + horizon, text(35pt, font: "Skolar Sans PE TEST", weight: "extrabold")[ *Plano de Trabalho de Ensino, Pesquisa e Extensão* ]) #align(left, text(20pt, font: "Skolar Sans PE TEST", weight: "bold")[ *Concurso de Professor Adjunto A no Departamento de Genética e Evolução* ]) #align(left, text(15pt, font: "Skolar Sans PE TEST", weight: "bold")[ #v(0.65pt) Universidade Federal de São Carlos #v(15pt) <NAME> <EMAIL> ]) #set text( font: "Skolar PE TEST", size: 12pt, lang: "por", region: "br" ) #set page( paper: "a4", header:[ #set text(9pt, font: "Skolar PE TEST") Plano de Trabalho #h(1fr) <NAME> ], numbering: "1", ) #show outline.entry.where( level: 1 ): it => { v(11pt, weak: true) strong(it) } #pagebreak() #v(10pt) #outline(fill: none, indent: 2em, title: "Conteúdo", depth: 2) #v(100pt) #align(center, text(13pt)[ *Apresentação* ]) Apresento este plano de trabalho atendendo ao Edital 01623.12 publicado pela reitoria da Universidade Federal de São Carlos no Diário Oficial da União de 3 de Novembro de 2023, referente ao concurso para o cargo de professor adjunto A na área Genética Evolutiva junto ao Departamento de Genética e Evolução da Universidade Federal de São Carlos. #pagebreak() #show par: set block(spacing: 1em) #set par( leading: 1em, first-line-indent: 1em, justify: true ) #show heading: it => { block[#it.body] v(0.3em) } = Pesquisa == Apresentação Os organismos não evoluem como uma coleção de caracteres independentes, mas como uma unidade estruturada e coesa, e essa estrutura impõe restrições à mudança evolutiva. Essas restrições podem surgir por várias mecanísmos relacionados à arquitetura genética e ao desenvolvimento. Por exemplo, a pleiotropia, quando um locus influencia a variação de mais de um caráter, é uma causa onipresente de restrições genéticas. Isso acontece pois a pleiotropia causa covariância genética entre caracteres, vinculando suas respostas evolutivas.#footnote[Aqui, caráter ou caracteres pode se referir a qualquer fenótipo complexo que possa ser medido em uma escala contínua, como peso corporal, comprimentos esqueléticos, ou expressão gênica]. A seleção em um caráter pode alterar as frequências alélicas nos loci pleiotrópicos, resultando em respostas fenotípicas em ambas os caracteres, mesmo que apenas um caráter estivesse sob seleção. Esse tipo de resposta pode até fazer com que as caracteres evoluam na direção oposta da pressão seletiva atuando sobre elas, dependendo da força de seleção em cada caráter e do padrão de covariância genética entre eles. Da mesma forma, mudanças na frequência alélica devido à deriva também terão efeitos fenotípicos que dependem do padrão pleiotrópico da arquitetura genética, alterando conjuntos de caracteres simultaneamente. Da mesma forma, desenvolvimento compartilhado pode vincular a variação entre diferentes partes de um organismo, e também restringir a mudança evolutiva. **O tema condutor do meu trabalho é a interação entre restrições genéticas e desenvolvimentais e forças evolutivas, como seleção natural e deriva genética. Compreender o efeito dessas restrições sobre a covariância genética e a mudança evolutiva é relevante não apenas para o estudo da adaptação em curto prazo, mas também para o tratamento de doenças, para o melhoramento seletivo de espécies de interesse econômico, e para o estudo de padrões macroevolutivos de longo prazo. Neste projeto, apresentamos uma visão integrativa de como quantificar entender as perturbações fisiológicas decorrentes dessas pressões ambientais e seletivas. Organismos estão sujeitos a diversos tipos de stress, decorrentes de atividade antrópica, pressões ambientais, aquecimento global, mudanças climáticas, perda dos seus habitats, competição por recursos escassos, entre outros. Todos esse processos induzem processos plásticos e adaptativos em populações naturais, alterando a distribuição dos caracteres fenotípicos e a aptidão dos indivíduos. Caracteres moleculares, metabólicos, fisiológicos, morfológicos, tem seu desempenho e aptidão derivados, em parte, da interação com outros caracteres. O nível ótimo de expressão de um gene depende criticamente da expressão de outros genes para que seu papel possa ser desempenhado com sucesso. O balanço entre a expressão de todos os genes num organismo leva a um determinado padrão de co-expressão, que pode ser capturado a partir das correlações entre os níveis de expressão genética entre indivíduos. Essa mesma regra se aplica para todos os outros tipos de caracteres. Alterações ocasionadas por stress podem levar a disrupção entre esses padrões de co-expressão fenotípicos, levando a um processo que chamamos de decoerência @Lea2019-pq. A decoerência entre caracteres se manifesta como um estado fisiológico com menor aptidão, podendo levar a uma série de complicações. - Uma resposta plástica ou adaptativa, que muda algum conjunto de caracteres fenotípicos em um indivíduo, pode levar a uma desarticulação entre diferentes caracteres. - Alterações ocasionadas por stress podem levar a disrupção entre esses padrões de co-expressão fenotípicos, levando a um processo que batizamos de decoerência. - A decoerência entre caracteres se manifesta como um estado fisiológico com menor aptidão, podendo levar a uma série de complicações. == Objetivos 1. Caracterizar o padrão de decoerência em populações expostas a diferentes tipos de stress. Relacionar esse padrão com as respostas plasticas e adpatativas ao stress sofrido. 2. Utilizar mapeamento genético para entender a arquitetura genética do padrão de docoerência a um stress ambiental. 3. Desenvolver métodos estatísticos para a detecção e interpretação dos padrão de decoerência, com foco no desenvolvimento de métodos de clustering que possam ajudar a interpretar padrões de decoerência. == Metodologia = Extensão == A Pandemia e o Observatório Covid-19 BR Em março de 2020, fui convidado pelo Prof. <NAME> a participar de um projeto de modelagem epidemiológica que ele estava coordenando, o Observatório Covid-19 BR#footnote[#link("https://covid19br.github.io/")]. O objetivo do projeto era produzir projeções de curto prazo para a evolução da pandemia da covid-19 no Brasil, usando modelos epidemiológicos e dados de internações por sindrome respiratória aguda grave do SIVEP-GRIPE#footnote[#link("http://info.gripe.fiocruz.br/")] e posteriormente do eSUS notifica#footnote[#link("https://datasus.saude.gov.br/notifica/")]. O projeto era uma colaboração entre pesquisadores do Departamento de Ecologia do IB-USP, do Instituto de Física Teórica da UNESP, do Departamento de Matemática da Universidade Federal do ABC e de dezenas de outras universidades e institutos em vários países#footnote[#link("https://covid19br.github.io/sobre")]. O projeto foi um sucesso, e as projeções do Observatório Covid-19 BR foram amplamente divulgadas na mídia e utilizadas por diversos órgãos públicos e privados para planejar ações de combate à pandemia. Minha participação foi centrada no desenvolvimento de métodos para a estimação de parâmetros epidemiológicos a partir dos dados de internações, e na análise dos dados de internações para entender a dinâmica da pandemia no Brasil. Sem nenhum tipo de tratamento estatístico, os dados de internação fornecem uma visão da pandemia que pode estar até 40 dias fora de compasso com a realidade. O principal produto do Observatório do qual que participei diretamente foi um conjunto de métodos para _nowcasting_, ou seja, entender o estado atual da pandemia corrigindo para o problema do atraso na atualização dos dados. Vejo experiências de extensão dessa natureza como um braço fundamental da universidade pública, permitindo a aplicação do conhecimento científico em prol da sociedade. == Curso de extensão em Ecologia Quantitativa Durante meu pós-doutorado em Princeton, mantive minha dedicação a em formar alunos no Brasil participando do Programa de Formação em Ecologia Quantitativa#footnote[#link("https://serrapilheira.org/programa-de-formacao-em-ecologia-quantitativa/")], uma iniciativa do Instituto Serrapilheira que visa capacitar alunos de mestrado em métodos quantitativos modernos. Participei como instrutor de um curso de extensão em Modelagem Estatística, organizado em 2023 pelo Prof. <NAME>. Nesse curso, apresentei aos alunos os principais conceitos de modelagem estatística, com foco em modelos lineares e generalizados, e mostrei como implementar esses modelos na prática. A partir de 2024, eu assumo a coordenação desse curso de modelagem estatística, em parceria com a Dr. <NAME>, da _Re.Green_#footnote[#link("https://re.green/")], uma ONG focada em conservação. Acredito que essa iniciativa pioneira é um exemplo de como a inicitiva privada pode dialogar com a academia para contribuir com a expansão da internacionalização e com a formação de pesquisadores capacitados para lidar com os grandes desafios da conservação da biodiversidade, principalmente fora do eixo Sul-Sudeste do Brasil, e pretendo continuar atuando nesse programa. Um produto importante desse curso foi a produção de video-aulas#footnote[#link("https://www.youtube.com/watch?v=b2PyeRu53OU&list=PLg0_ydgtbHGH0rWavkwJ3BfXf9p0kfH3w&ab_channel=ICTP-SAIFR")] e um material didático #footnote[#link("https://statistical-modeling.github.io/2024/")] que foi disponibilizado publicamente, e que pode ser utilizado de forma livre. Acredito que a produção de material didático de qualidade é uma forma de democratizar o acesso ao conhecimento e de expandir o impacto de nossas ações de extensão. = Ensino Durante minha trajetória acadêmica, sempre procurei dedicar tempo ao ensino, seja contribuindo como monitor em disciplinas de graduação e pós-graduação ou oferecendo disciplinas, cursos e _workshops_. Essas monitorias foram muito importantes na minha formação, me permitindo ter contato com áreas e métodos diferentes daqueles com que eu trabalhava no laboratório. Acredito que essas experiências foram cruciais para me proporcionar uma visão holística e integrativa de perguntas biológicas, expandindo minha visão para além das escalas do organismo e das populações que me são mais familiares. Participei como monitor de várias disciplinas do Departamento de Ecologia do IB-USP, como programação em R, modelos estatísticos, e o Curso de Campo da Mata Atlântica. Contribuí também com as disciplinas do Departamento de Genética e Biologia Evolutiva, atuando como monitor da disciplina de Biologia Evolutiva ao longo de vários anos, tendo escrito com a Dra. <NAME> uma apostila para a disciplina#footnote[#link("https://github.com/lem-usp/apostila-bio-evol/blob/master/apostila-Bio312.pdf?raw=true").]. Também produzi todo o material de aula prática em R#footnote[#link("https://diogro.github.io/BioEvol/").] para a a disciplina de Biologia Evolutiva. Participei também como monitor PAE da disciplina de Processos Evolutivos duas vezes ao longo da minha pós-graduação. Durante o pós-doutorado na USP, ofereci uma disciplina de pós-graduação com a Dra. <NAME> no Programa de Pós-Graduação em Biologia Comparada da FFCLRP-USP, em Ribeirão Preto, na qual apresentamos uma introdução à modularidade e teoria evolutiva e ligamos esses formalismos com suas consequências práticas. A disciplina conta com aulas teóricas e práticas e já foi oferecida duas vezes, em 2017 e 2019. Também estive envolvido, junto com vários pós-doutorandos de todos os departamentos do IB-USP, numa disciplina prática de escrita científica. Apesar de ser uma das atividades mais frequentes e importantes da carreira científica, temos muito pouco treino objetivo de escrita durante a pós-graduação. Isso é uma pena, já que a escrita é a principal ferramenta de disseminação do conhecimento produzido em nossos laboratórios. Percebendo isso, dediquei um tempo considerável de estudo a aprimorar minha escrita em inglês, focando na escrita de artigos e projetos. Nossa disciplina apresentou aos alunos maneiras de pensar a escrita científica e ofereceu métodos para que eles pudessem elaborar textos claros e cativantes. Já no meu Pós-doutorado na Universidade de Princeton, participei como monitor de uma disciplina de Genética Humana, Bioinformática, e Biologia Evolutiva, ministrada pelos professores <NAME>, <NAME> e <NAME>; e de uma disciplina de Epidemiologia, ministrada pelo Dr. <NAME>, para a qual minha experiência no Observatório Covid-19 BR foi fundamental. No último ano, fui também responsável por desenvolver e ministrar uma disciplina de Computação para Biologia, que apresentava aos alunos de graduação de diversos departamentos os principais conceitos de programação e análise de dados em R e Python, com um foco na pesquisa em ecologia e genômica. Com base nessas experiências didáticas, entendo que um bom curso de graduação ou de pós-graduação deveria oferecer as ferramentas para que os alunos possam se tornar capazes de idealizar, analisar e interpretar seus dados e experimentos de forma independente. Para isso, é fundamental oferecer tanto disciplinas instrumentais quanto teóricas. Nesse contexto, apresento algumas propostas de contribuições que poderia fornecer ao departamento, buscando proporcionar aos alunos da UFSCAR a melhor formação possível, voltada para o pensamento crítico, independência e rigor científico. == Disciplinas de graduação existentes Das disciplinas de graduação atualmente oferecidas pelo Departamento de Genética e Evolução, posso atual naquelas que envolvem ensino de evolução, como Evolução: o fato evolutivo, Evolução: O Processo Evolutivo. Poderia também colaborar com as disciplinas relacionadas a genética, como Princípios da Genética, Genética Molecular, e também poderia colaborar com as disciplinas quantitativas, como Biologia Quantitativa e eventualmente até com a disciplina de Cálculo para Biocientistas, procurando tornar estes cursos ainda mais interessantes e afinados com os interesses de biólogos em formação. == Propostas de disciplinas de graduação e pós-graduação Com o avanço das tecnologias de sequenciamento de DNA e RNA, e de outras técnicas de alta precisão, a quantidade de dados genômicos e de fenótipos moleculares disponíveis cresceu exponencialmente. Este acúmulo de informações, embora seja um marco importante, trouxe uma complexidade sem precedentes na análise e compreensão dos dados. A única forma de lidar com essa complexidade é uma abordagem integrativa, que combine teoria, experimentos e análises computacionais. A genética quantitativa evolutiva é uma ferramenta poderosa para entender e esmiuçar a arquitetura genética de fenótipos complexos. === Teoria Evolutiva Como disciplina eletiva, eu poderia oferecer uma disciplina de Teoria Evolutiva, apresentando de forma mais profunda os fundamentos teóricos da biologia evolutiva, abordando não só as formulações tradicionais em termos de frequências alélicas de Fisher e Wright, mas também as formulações algébricas como o Teorema de Price ou a genética quantitativa multivariada e as aplicações destes formalismos, como melhoramento animal, mapeamento genético e estudos evolutivos em populações naturais. Numa versão avançada para a pós-graduação, uma disciplina de teoria evolutiva poderia abordar também seleção multinível, modelos de manutenção da variação genética, teoria de jogos, e eventualmente, para alunos com algum conhecimento de cálculo, até mesmo a formulação usando equações diferenciais parciais da evolução de frequências alélicas iniciada por Kimura. O objetivo desse disciplina seria introduzir os principais modelos da teoria evolutiva, e mostrar como esses modelos podem ser aplicados a problemas biológicos concretos. A disciplina poderia ser adaptada para alunos de graduação ou pós-graduação, com uma ênfase maior em aplicações práticas para os alunos de graduação e uma ênfase maior em formalismos teóricos para os alunos de pós-graduação. Esses disciplinas teriam componentes teóricos e práticos, com aulas expositivas e exercícios práticos em R. === Estatística na era da computação Outra contribuição que eu poderia oferecer na graduação ou na pós-graduação seria uma disciplina de análise de dados utilizando ferramentas computacionais modernas e modelos Bayesianos aplicadas a problemas biológicos. Na graduação, eu poderia oferecer uma discplina optativa de Introdução à Programação de Computadores para Biologia, apresentando as principais ferramentas para o processamento de dados biológicos; ou uma disciplina de modelagem estatística, trazendo minha experiencia de ensino em estatística aplicada a biologia. Na pós-graduação, essa disciplina poderia ser planejada em conjunto com uma disciplina de programação em R, fornecendo aos alunos de pós-graduação da UFSCAR um caminho completo para uma formação moderna e adaptável em métodos estatísticos que os capacita para realizarem suas pesquisas com maior autonomia. Uma vantagem de oferecer esse tipo de disciplina no Departamento de Genética e Evolução é poder enfatizar aplicações em genômica, como mapeamento genético, modelos evolutivos e demográficos, e métodos de análise de transcriptomas, que não figuram nos cursos da tradicionais. Esses métodos estatísticos computacionais e de bioinformática são cada vez mais relevantes na biologia, com a disseminação de dados genômicos de larga escala que exigem análises sofisticadas e específicas. O objetivo dessas disciplinas seria aumentar o leque de ferramentas disponíveis para os alunos, permitindo que eles possam realizar análises que sejam desenhadas especificamente para suas perguntas biológicas. #set par( leading: 0.65em, first-line-indent: 0em, justify: false ) #bibliography("memorial.bib", style: "apa", title: "Referências")
https://github.com/Shuenhoy/modern-zju-thesis
https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/examples/undergraduate-cs.typ
typst
MIT License
#import "../lib.typ": undergraduate-cs #import undergraduate-cs: * #let info = ( title: ("毕业论文/设计题目",), grade: "2014级", student-id: "学号", author: "姓名", department: "学院", major: "专业", supervisor: "指导教师", submit-date: "递交日期", ) #let doc = undergraduate-cs(info: info, twoside: true) #show: doc.style #doc.pages.cover #show: frontmatter #doc.pages.decl #let individual = doc.pages.individual #individual("致 谢")[] #individual("摘 要")[] #individual("Abstract")[] #doc.pages.outline #show: mainmatter #part[毕业论文] #include "common-body.typ" #bibliography("ref.bib", style: "gb-7714-2015-numeric") #individual("参考文献", outlined: true)[ #part-bib ] #individual("附录", outlined: true)[ #appendix[ === 一个附录 <app1> @app1 === 另一个附录 ] ] #individual("作者简历", outlined: true)[ *基本信息:* - 姓名: - 性别: - 民族: - 出生年月: - 籍贯: *教育经历:* - 2199.09 - 2203.06:浙江大学攻读学士学位 ] #(doc.pages.task)()[任务] #(doc.pages.eval)(scores: (8, 15, 5, 60))[评价] #part[开题报告] #doc.pages.proposal-cover #(doc.pages.proposal-task)[ 内容 ] #counter(page).update(0) = 文献综述 @zjugradthesisrules == 参考文献 #part-bib = 开题报告 == 参考文献 #part-bib = 外文翻译 = 外文原文 #(doc.pages.proposal-eval)(scores-supervisor: (8, 15, 5))[评价]
https://github.com/artomweb/Quick-Sip-Typst-Template
https://raw.githubusercontent.com/artomweb/Quick-Sip-Typst-Template/master/lib.typ
typst
MIT License
#let page-number() = ( context { counter(page).display() } ) #let section( title, fill-clr: rgb("FFFFFF"), body, ) = ( context { if (title != none and title != "") { counter("step").update(0) let box-height = measure( align( center, stack( // Line behind the box move( line(length: 100%, stroke: 2pt)), // The box with text box(width: 67mm, stroke: 2pt, outset: 4pt, fill: fill-clr)[ #v(0.8mm) #set text(size: 10pt) #box(width: 60mm)[ #align(center)[#upper(strong(title))] ] #v(0.8mm) ] ), )).height align( center, stack( // Line behind the box move(dy: box-height/2, line(length: 100%, stroke: 2pt)), // The box with text box(width: 67mm, stroke: 2pt, outset: 4pt, fill: fill-clr)[ #v(0.8mm) #set text(size: 10pt) #box(width: 60mm)[ #align(center)[#upper(strong(title)) #label("section")] ] #v(0.8mm) ], v(1.3mm) ), ) body align(center)[ #box( width: 20%, height: 2.2mm, stack( dir: ltr, ..for i in range(4) { ( square(size: 2.2mm, fill: black), h(1.85mm), ) }, ), ) ] linebreak() } } ) #let step(a, b) = ( context { v(1pt) counter("step").step() // Update the step counter set text(size: 9.8pt) // Get the current step number let step-num = counter("step").get() text[#str(step-num.at(0) + 1) #label("step" + str(step-num.at(0) + 1))] h(10pt) if (a != none and a != "" and (b == none or b == "")) { a } else if (a != none and a != "" and b != none and b != "") { a " " box(width: 1fr, repeat[.]) " " b } linebreak() } ) #let condition(fill-bg: rgb("EAEAEAFF"), body) = ( context { if (body.has("children")) { let condition-width = measure(text(size: 7pt)[ Condition: ]).width box(width: 100%, inset: (y: 3pt, x: 3pt), outset: (y: 4pt), fill: fill-bg)[ #box( grid( columns: 2, align: horizon, column-gutter: 6pt, row-gutter: 5pt, text(size: 7pt)[Condition:], text(size: 9.6pt)[One or more of these occur:], // Add an empty space in the first column to shift #body [ ], move(dx: 5pt, text(size: 9.6pt)[ #grid(columns: 2, align: horizon, row-gutter: 5pt, column-gutter: 2pt, ..for c in body.children{ if (c != [ ] and c != (:)) { (circle(radius: 1.178mm / 2, fill: black), c.at("body")) } } ) ]) ), ) ] } else { box(width: 100%, inset: (y: 3pt, x: 3pt), outset: (y: 4pt), fill: fill-bg)[ #box( grid( columns: 2, align: horizon, column-gutter: 6pt, row-gutter: 5pt, text(size: 7pt)[Condition:], text(size: 9.6pt)[#body], ), ) ] } } ) #let objective(fill-bg: rgb("EAEAEAFF"), body) = ( context { box(width: 100%, inset: (y: 3pt, x: 3pt), outset: (y: 4pt), fill: fill-bg)[ // #v(5pt) #box( grid( columns: 2, align: horizon, column-gutter: 6pt, text(size: 7pt)[Objective:], text(size: 9.6pt)[#body], ), ) ] } ) #let note(fill-bg: rgb("edf7f7ff"), body) = ( context { box(width: 100%, outset: (y: 4pt), inset: (x: 4pt), fill: fill-bg)[ #box( grid( columns: 2, align: top, column-gutter: 6pt, text(size: 9pt, weight: "bold")[Note:], text(size: 10pt)[#body], ), ) ] } ) #let caution(fill-bg: rgb("edf7f7ff"), body) = ( context { stack( spacing: 4pt, line(length: 100%, stroke: 2pt + rgb("d98d00ff")), grid( columns: 2, column-gutter: 6pt, text(weight: "bold", size: 9.8pt)[Caution!], text(weight: "bold", size: 9.8pt)[#body], ), line(length: 100%, stroke: 2pt + rgb("d98d00ff")), ) } ) #let bullet(phrase) = ( context { phrase linebreak() } ) #let chooseOne(fill-bg: rgb("edf7f7ff"), body) = ( context { counter("step").step() counter("localOption").update(0) let step-num = counter("step").get() text[#str(step-num.at(0) + 1) #label("step" + str(step-num.at(0) + 1))] h(10pt) text()[Choose one:] linebreak() body } ) #let option(body) = ( context { counter("globalOption").step() counter("localOption").step() let globalOption = counter("globalOption").get().at(0) move( dx: 16pt, grid( columns: 2, column-gutter: 3pt, rotate(45deg)[#box(width: 2.2mm, height: 2.2mm, fill: black) #label(("option" + str(globalOption + 1)))], body, ), ) // text[#("option" + str(globalOption + 1)) ] context { let localOption = counter("localOption").get().at(0) let globalOption = counter("globalOption").get().at(0) // text[#globalOption #localOption] if (localOption > 1) { let pos = locate(label("option" + str(globalOption - 1))).position() let currPos = locate(label("option" + str(globalOption))).position() if (currPos.page == pos.page) { // text[#pos.y #currPos.y] // linebreak() // text["Previous Option Page: " #pos.page] // text["Current Option Page: " #currPos.page] place(top, line(start: (pos.x - 25.5pt, pos.y - 20pt), end: (currPos.x - 25.5pt, currPos.y - 20pt))) } } } } ) #let detail(body) = ( context { body } ) #let optionStep(a, b) = ( context { if (a != none and a != "" and (b == none or b == "")) { // Check if only 'a' is present move( dx: 16pt, box( width: 100% - 16pt, text(a), ), ) } else if (a != none and a != "" and b != none and b != "") { // Check if both 'a' and 'b' are present move( dx: 16pt, box( width: 100% - 16pt, grid( columns: 3, a, repeat[.], align(right)[#b], ), ), ) } } ) #let tab(body) = { move( dx: 17pt, box( width: 100% - 16pt, body, ), ) } #let endNow() = { align(center)[ #box( width: 20%, height: 2.2mm, stack( dir: ltr, ..for i in range(4) { ( square(size: 2.2mm, fill: black), h(1.85mm), ) }, ), ) ] } #let goToStep(step) = ( context { move( dx: 18pt, grid( columns: 3, align: horizon, column-gutter: 3pt, path( fill: black, // Color of the first triangle closed: true, // Close the triangle (0pt, 0pt), // Bottom-left corner (5pt, 2.83pt), // Rightmost point (0pt, 5pt) // Top-left corner ), path( fill: black, // Color of the first triangle closed: true, // Close the triangle (0pt, 0pt), // Bottom-left corner (5pt, 2.83pt), // Rightmost point (0pt, 5pt) // Top-left corner ), link(label("step" + step))[#text(weight: "bold")[Go to step #step]], ), ) } ) #let waitHere() = { repeat[#stack(dir: ltr, rect(width: 2mm, height: 1mm, fill: black), h(2mm))] } #let subStep(a, b) = { v(1pt) set text(size: 9.8pt) move( dx: 25pt, dy: -2pt, box( width: 100% - 25pt, if (a != none and a != "" and (b == none or b == "")) { a } else if (a != none and a != "" and b != none and b != "") { a " " box(width: 1fr, repeat[.]) " " b }, ), ) } #let index() = { locate(loc => { let elems = query(<section>) if elems.len() == 0 { return } align(center, text(weight: "bold")[INDEX]) for body in elems { text([#link(body.location(), body.child.body) ]) box(width: 1fr, repeat[.]) text[#body.location().page()] linebreak() } pagebreak() }) } #let QRH(title: none, body) = { set page( width: 105mm, height: 177mm, margin: (bottom: 12mm, top: 8mm, x: 9mm), footer: [ #line(start: (0pt, -6pt), length: 100%) #place( left, dy: -2pt, text(size: 6pt, fill: rgb("000000"))[ #datetime.today().display() ], ) #place( center, dy: -2pt, text(size: 6pt, fill: rgb("000000"))[ #page-number() ], ) #place( right, dy: -2pt, text(size: 6pt, fill: rgb("000000"))[ #title ], ) ], ) set text(font: "<NAME>", size: 9.6pt) body }
https://github.com/rikhuijzer/phd-thesis
https://raw.githubusercontent.com/rikhuijzer/phd-thesis/main/chapters/3.typ
typst
The Unlicense
#import "../style.typ": citefig #import "../functions.typ": chapter, textcite, parencite, note #chapter( [SIRUS.jl: Interpretable Machine Learning via Rule Extraction], label: [ <NAME>., <NAME>., <NAME>, <NAME>. (2023). SIRUS.jl: Interpretable Machine Learning via Rule Extraction. _Journal of Open Source Software_, 8(90), 5786, #link("https://doi.org/10.21105/joss.05786") ], abstract: [ SIRUS.jl#footnote[Source code available at #link("https://github.com/rikhuijzer/SIRUS.jl").] is an implementation of the original Stable and Interpretable RUle Sets (SIRUS) algorithm in the Julia programming language @bezanson2017julia. The SIRUS algorithm is a fully interpretable version of random forests, that is, it reduces thousands of trees in the forest to a much lower number of interpretable rules (e.g., 10 or 20). With our Julia implementation, we aimed to reproduce the original C++ and R implementation in a high-level language to verify the algorithm as well as making the code easier to read. We show that the model performs well on classification tasks while retaining interpretability and stability. Furthermore, we made the code available under the permissive MIT license. In turn, this allows others to research the algorithm further or easily port it to production systems. ] ) == Statement of need Many of the modern day machine learning models are noninterpretable models, also known as _black box_ models. Well-known examples of noninterpretable models are random forests @breiman2001random and neural networks. Such models are available in the Julia programming language via, for example, LightGBM.jl @ke2017lightgbm, Flux.jl @innes2018flux, and BetaML.jl @lobianco2021betaml. Although these models can obtain high predictive performance and are commonly used, they can be problematic in high stakes domains where model decisions have real-world impact on individuals, such as suggesting treatments or selecting personnel. The reason is that noninterpretable models may lead to unsafe, unfair, or unreliable predictions @doshi2017towards @barredo2020explainable. Furthermore, interpretable models may allow researchers to learn more from the model, which in turn may allow researchers to make better model decisions and achieve a higher predictive performance. However, the set of interpretable models is often limited to ordinary and generalized regression models, decision trees, RuleFit, naive Bayes classification, and k-nearest neighbors @molnar2022interpretable. For these models, however, predictive performance can be poor for certain tasks. Linear models, for instance, may perform poorly when features are correlated and can be sensitive to the choice of hyperparameters. For decision trees, predictive performance is poor compared to random forests @james2013introduction. RuleFit is not available in Julia and is _unstable_ @benard2021sirus, meaning sensitive to small changes in data. Naive Bayes, available in Julia as NaiveBayes.jl#footnote[Source code available at #link("https://github.com/dfdx/NaiveBayes.jl.")], is often overlooked and can be a suitable solution, but only if the features are independent @ashari2013performance. Researchers have attempted to make the random forest models more interpretable. Model interpretation techniques, such as SHAP @lundberg2017unified or Shapley, available via Shapley.jl#footnote[Source code available at #link("https://gitlab.com/ExpandingMan/Shapley.jl.")], have been used to visualize the fitted model. However, the disadvantage of these techniques are that they convert the complex model to a simplified representation. This causes the simplified representation to be different from the complex model and may therefore hide biases and issues related to safety and reliability @barredo2020explainable. The SIRUS algorithm solves this by simplifying the complex model and by then using the simplified model for predictions. This ensures that the same model is used for interpretation and prediction. However, the original SIRUS algorithm was implemented in about 10k lines of C++ and 2k lines of R code#footnote[Source code available at #link("https://gitlab.com/drti/sirus").] which makes it hard to inspect and extend due to the combination of two languages. Our implementation is written in about 2k lines of pure Julia code. This allows researchers to more easily verify the algorithm and investigate further improvements. Furthermore, the original algorithm was covered by the GPL-3 copyleft license meaning that copies are required to be made freely available. A more permissive license makes it easier to port the code to other languages or production systems. == Interpretability <interpretability> To show that the algorithm is fully interpretable, we fit an example on the Haberman's Survival Dataset @haberman1999survival. The dataset contains survival data on patients who had undergone surgery for breast cancer and contains three features, namely the number of axillary _nodes_ that were detected, the _age_ of the patient at the time of the operation, and the patient's _year_ of operation. For this example, we have set the hyperparameters for the maximum number of rules to 8 since this is a reasonable trade-off between predictive performance and interpretability. Generally, a higher maximum number of rules will yield a higher predictive performance. We have also set the maximum depth hyperparameter to 2. This hyperparameter means that the random forests inside the algorithm are not allowed to have a depth higher than 2. In turn, this means that rules contain at most 2 clauses (`if A & B`). When the maximum depth is set to 1, then the rules contain at most 1 clause (`if A`). Most rule-based models, including SIRUS, are restricted to depth of 1 or 2 @benard2021sirus. The output for the fitted model looks as follows (see @code-example for the code): ``` StableRules model with 8 rules: if X[i, :nodes] < 7.0 then 0.238 else 0.046 + if X[i, :nodes] < 2.0 then 0.183 else 0.055 + if X[i, :age] ≥ 62.0 & X[i, :year] < 1959.0 then 0.0 else 0.001 + if X[i, :year] < 1959.0 & X[i, :nodes] ≥ 2.0 then 0.0 else 0.006 + if X[i, :nodes] ≥ 7.0 & X[i, :age] ≥ 62.0 then 0.0 else 0.008 + if X[i, :year] < 1959.0 & X[i, :nodes] ≥ 7.0 then 0.0 else 0.003 + if X[i, :year] ≥ 1966.0 & X[i, :age] < 42.0 then 0.0 else 0.008 + if X[i, :nodes] ≥ 7.0 & X[i, :age] ≥ 42.0 then 0.014 else 0.045 and 2 classes: [0, 1]. ``` This shows that the model contains 8 rules where the first rule, for example, can be interpreted as: \ _If the number of detected axillary nodes is lower than 7, then take 0.238, otherwise take 0.046._ This calculation is done for all 8 rules and the score is summed to get a prediction. In essence, the first rule says that if there are less than 8 axillary nodes detected, then the patient is more likely to survive (`class == 1`). Put differently, the model states that if there are many axillary nodes detected, then it is, unfortunately, less likely that the patient will survive. This model is fully interpretable because the model contains a few dozen rules which can all be interpreted in isolation and together. == Stability Another problem that the SIRUS algorithm addresses is that of model stability. A stable model is defined as a model which leads to similar conclusions for small changes to data @yu2020veridical. Unstable models can be difficult to apply in practice as they might require processes to constantly change. This also makes such models appear less trustworthy. Put differently, an unstable model by definition leads to different conclusions for small changes to the data and, hence, small changes to the data could cause a sudden drop in predictive performance. One model which suffers from a low stability is a decision tree, available via DecisionTree.jl @sadeghi2022decisiontree, because it will first create the root node of the tree, so a small change in the data can cause the root, and therefore the rest, of the tree to be completely different @molnar2022interpretable. Similarly, linear models can be highly sensitive to correlated data and, in the case of regularized linear models, the choice of hyperparameters. The aforementioned RuleFit algorithm also suffers from stability issues due to the unstable combination of tree fitting and rule extraction @benard2021sirus. The SIRUS algorithm solves this problem by stabilizing the trees inside the forest, and the original authors have proven the correctness of this stabilization mathematically @benard2021sirus. In the rest of this paper, we will compare the predictive performance of SIRUS.jl to the performance of decision trees @sadeghi2022decisiontree, linear models, XGBoost @chen2016xgboost, and the original (C++/R) SIRUS implementation @benard2021sirus. The interpretability and stability are summarized in Table #citefig(<interpretability-stability>). #figure( table( columns: (auto, auto, auto, auto, auto), align: (left, center, center, center, center), table.hline(start: 0), table.header( [], [*Decision Tree*], [*Linear Model*], [*XGBoost*], [*SIRUS*], ), table.hline(start: 0), [*Interpretability*], [High], [High], [Medium], [High], [*Stability*], [Low], [Medium], [High], [High], table.hline(start: 0), ), caption: "Summary of interpretability and stability for various models" ) <interpretability-stability> == Predictive Performance The SIRUS model is based on random forests and therefore well suited for settings where the number of variables is comparatively large to the number of datapoints @biau2016random. To make the random forests interpretable, the large number of trees are converted to a small number of rules. The conversion works by converting each tree to a set of rules and then pruning the rules by removing simple duplicates and linearly dependent duplicates, see the SIRUS.jl documentation or the original paper @benard2021interpretable for details. In practice, this trade-off between between model complexity and interpretability comes at a small performance cost. To show the performance, we compared SIRUS to a decision tree, linear model, XGBoost, and the original (C++/R) SIRUS algorithm; similar to Table #citefig(<interpretability-stability>). We have used Julia version 1.9.3 with SIRUS version 1.3.3 (at commit `5c87eda`), 10-fold cross-validation, and we will present variability as 1.96 $*$ standard error for all evaluations with respectively the following datasets, outcome variable type, and measures: Haberman's Survival Dataset @haberman1999survival binary classification dataset with AUC, Titanic @eaton1995titanic binary classification dataset with Area Under the Curve (AUC), Breast Cancer Wisconsin @wolberg1995breast binary classification dataset with AUC, Pima Indians Diabetes @smith1988using binary classification dataset with AUC, Iris @fisher1936use multiclass classification dataset with accuracy, and Boston Housing @harrison1978hedonic regression dataset with $"R"^2$; see Table #citefig(<perf>). For full details, see `test/mlj.jl`#footnote[#link("https://github.com/rikhuijzer/SIRUS.jl/blob/5c87eda4d0c50e0b78d12d6bd2c4387f5a83f518/test/mlj.jl")]. The performance scores were taken from the SIRUS.jl test job that ran following commit `5c873da` using GitHub Actions. The result for the Iris dataset for the original SIRUS algorithm is missing because the original algorithm has not implemented multiclass classification. #figure( { set text(size: 7.5pt) let param(txt) = text(txt, size: 6pt, weight: "bold") table( columns: (auto, auto, auto, auto, auto, auto, auto), align: (left, center, center, center, center, center, center), table.hline(start: 0), table.header( [*Dataset*], [*Decision*], [*Linear*], [*XGBoost*], [*XGBoost*], [*Original*], [*SIRUS.jl*], [], [*Tree*], [*Model*], [], [], [*SIRUS*], [], [], [], [], param([max depth: $infinity$]), param([max depth: 2]), param([max depth: 2]), param([max depth: 2]), [], [], [], [], [], param([max rules: 10]), param([max rules: 10]), ), table.hline(start: 0), [Haberman], [$0.54 plus.minus 0.06$], [$0.69 plus.minus 0.06$], [$0.65 plus.minus 0.04$], [$0.63 plus.minus 0.04$], [$0.66 plus.minus 0.05$], [$0.67 plus.minus 0.06$], [Titanic], [$0.76 plus.minus 0.05$], [$0.84 plus.minus 0.02$], [$0.86 plus.minus 0.03$], [$0.87 plus.minus 0.03$], [$0.81 plus.minus 0.02$], [$0.83 plus.minus 0.02$], [Cancer], [$0.92 plus.minus 0.03$], [$0.98 plus.minus 0.01$], [$0.99 plus.minus 0.00$], [$0.99 plus.minus 0.00$], [$0.96 plus.minus 0.02$], [$0.98 plus.minus 0.01$], [Diabetes], [$0.67 plus.minus 0.05$], [$0.70 plus.minus 0.06$], [$0.80 plus.minus 0.04$], [$0.82 plus.minus 0.03$], [$0.80 plus.minus 0.02$], [$0.75 plus.minus 0.05$], [Iris], [$0.95 plus.minus 0.03$], [$0.97 plus.minus 0.03$], [$0.94 plus.minus 0.04$], [$0.93 plus.minus 0.04$], [], [$0.77 plus.minus 0.08$], [Boston], [$0.74 plus.minus 0.11$], [$0.70 plus.minus 0.05$], [$0.87 plus.minus 0.05$], [$0.86 plus.minus 0.05$], [$0.63 plus.minus 0.07$], [$0.61 plus.minus 0.09$], table.hline(start: 0), ) }, caption: "Predictive performance estimates" ) <perf> At the time of writing, SIRUS's predictive performance is comparable to the linear model and XGBoost on the binary classification datasets, that is, Haberman, Titanic, Breast Cancer, and Diabetes. The best performance occurs at the Diabetes dataset where both XGBoost and the SIRUS models outperform the linear model. The reason for this could be that negative effects are often nonlinear for fragile systems @taleb2020statistical. For example, it could be that an increase in oral glucose tolerance increases the chance of diabetes exponentially. In such cases, the hard cutoff points chosen by tree-based models, such as XGBoost and SIRUS, may fit the data better. For the multiclass Iris classification and the Boston Housing regression datasets, the performance was worse than the other non-SIRUS models. It could be that this is caused by a bug in the implementation or because this is a fundamental issue in the algorithm. Further work is needed to find the root cause or workarounds for these low scores. One possible solution would be to add SymbolicRegression.jl @cranmer2023interpretable as a secondary back end for regression tasks. Similar to SIRUS.jl, SymbolicRegression.jl can fit expressions of a pre-defined form to data albeit with more free parameters, which might fit better but also might cause overfitting, depending on the data. This achieves performance that is similar to XGBoost @hanson2023discourse. In conclusion, interpretability and stability are often required in high-stakes decision making contexts such as personnel or treatment selection. In such contexts and when the task is classification, SIRUS.jl obtains a reasonable predictive performance, while retaining model stability and interpretability. == Code Example <code-example> The model can be used via the Machine Learning Julia (MLJ) @blaom2020mlj interface. The following code, for example, was used to obtain the fitted model for the Haberman example at the start of this paper, and is also available in the SIRUS.jl docs#footnote[#link("https://sirus.jl.huijzer.xyz/dev/basic-example/").]. #let julia_code(str) = { let str = str.trim(regex("\n| ")) [ #block( raw(str, lang: "julia"), breakable: false ) ] } We first load the dependencies: #julia_code(" using CategoricalArrays: categorical using CSV: CSV using DataDeps: DataDeps, DataDep, @datadep_str using DataFrames using MLJ using StableRNGs: StableRNG using SIRUS: StableRulesClassifier ") And specify the Haberman dataset via DataDeps.jl, which allows data verification via the checksum and enables caching: <br> #julia_code(" function register_haberman() name = \"Haberman\" message = \"Haberman's Survival Data Set\" remote_path = \"https://github.com/rikhuijzer/haberman-survival-dataset/ releases/download/v1.0.0/haberman.csv\" checksum = \"a7e9aeb249e11ac17c2b8ea4fdafd5c9392219d27cb819ffaeb8a869eb727a0f\" DataDeps.register(DataDep(name, message, remote_path, checksum)) end ") Next, we load the data into a `DataFrame`: <br> #julia_code(" function load_haberman()::DataFrame register_haberman() path = joinpath(datadep\"Haberman\", \"haberman.csv\") df = CSV.read(path, DataFrame) df[!, :survival] = categorical(df.survival) return df end ") We split the data into features (`X`) and outcomes (`y`): #julia_code(" data = load_haberman() X = select(data, Not(:survival)) y = data.survival ") We define the model that we want to use with some reasonable hyperparameters for this small dataset: #julia_code(" model = StableRulesClassifier(; rng=StableRNG(1), q=4, max_depth=2, max_rules=8) ") Finally, we fit the model to the data via MLJ and show the fitted model: #julia_code(" mach = let mach = machine(model, X, y) MLJ.fit!(mach) end mach.fitresult ") Resulting in the fitresult that was presented in @interpretability.
https://github.com/jassielof/typst-templates
https://raw.githubusercontent.com/jassielof/typst-templates/main/upsa-bo/estudio-de-factibilidad/template/capítulos/2.marco teórico.typ
typst
MIT License
= Marco Teórico == Definición y Selección de la Metodología == Marco Conceptual == Marco Referencial == Marco Legal
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/02-concepts/dimension/vertical-advance.typ
typst
Other
#import "/lib/draw.typ": * #import "/lib/glossary.typ": tr #import "/template/lang.typ": mongolian #let start = (0, 0) #let end = (500, 540) #let example = rotate(90deg, mongolian[ᠪᠰ‍]) #let graph = with-unit((ux, uy) => { // mesh(start, end, (100, 100), stroke: 1 * ux + gray) rect( (20, 500), end: (390, 285), stroke: 2 * ux + theme.main, ) rect( (20, 285), end: (390, 100), stroke: 2 * ux + theme.main, ) segment( (215, 530), (215, 35) ) txt(tr[baseline], (215, 10), anchor: "cb", size: 20 * ux) arrow( (410, 495), (410, 285), stroke: 2 * ux + theme.main, head-scale: 3, ) arrow-head((410, 500), 6, theta: 90deg) txt(block(width: 1em)[#par(leading: 0.25em)[#tr[vertical advance]]], (425, 400), anchor: "lc") txt(example, (195, 430), anchor: "ct", size: 360 * ux) }) #canvas(end, start: start, width: 50%, graph)
https://github.com/drupol/master-thesis
https://raw.githubusercontent.com/drupol/master-thesis/main/resources/typst/inputs-and-outputs-part1.typ
typst
Other
#import "../../src/thesis/imports/preamble.typ": * #set align(center + horizon) #set text(font: "<NAME>") #grid( columns: (1fr, 1fr, 1fr, 1fr, 1fr), rows: (40pt, 25pt), image("../../resources/images/inputs-cube.svg"), xarrow(sym: sym.arrow.r, width: 50pt, ""), image("../../resources/images/computation-cogs.svg"), xarrow(sym: sym.arrow.r, width: 50pt, ""), image("../../resources/images/inputs-icon.svg"), "Inputs", "", "Computation", "", "Outputs", )
https://github.com/augustebaum/tenrose
https://raw.githubusercontent.com/augustebaum/tenrose/main/README.md
markdown
MIT License
# tenrose A simple Penrose binding for Typst using the WebAssembly plugin system. This is heavily inspired by the equivalent for graphviz, `diagraph`. ## Usage ### Basic usage This plugin is quite simple to use, you just need to import it: TODO ```typ #import "@preview/diagraph:0.2.2": * ``` You can render a Graphviz Dot string to a SVG image using the `render` function: ```typ #render("digraph { a -> b }") ``` Alternatively, you can use `raw-render` to pass a `raw` instead of a string: ````typ #raw-render( ```dot digraph { a -> b } ``` ) ```` You can see an example of this in [`examples/`](https://github.com/Robotechnic/diagraph/tree/main/examples). For more information about the Graphviz Dot language, you can check the [official documentation](https://graphviz.org/documentation/). ### Arguments `render` and `raw-render` accept multiple arguments that help you customize your graphs. - `engine` (`str`) is the name of the engine to generate the graph with. Available engines are circo, dot, fdp, neato, nop, nop1, nop2, osage, patchwork, sfdp, and twopi. Defaults to `"dot"`. - `width` and `height` (`length` or `auto`) are the dimensions of the image to display. If set to `auto` (the default), will be the dimensions of the generated SVG. If a `length`, cannot be expressed in `em`. - `clip` (`bool`) determines whether to hide parts of the graph that extend beyond its frame. Defaults to `true`. - `background` (`none` or `color` or `gradient`) describes how to fill the background. If set to `none` (the default), the background will be transparent. - `labels` (`dict`) is a list of labels to use to override the defaults labels. This is discussed in depth in the next section. Defaults to `(:)`. ### Labels By default, all node labels are rendered by Typst. If a node has no explicitly set label (using the `[label="..."]` syntax), its name is used as its label, and interpreted as math if possible. This means a node named `n_0` will render as 𝑛<sub>0</sub>. If you want a node label to contain a more complex mathematical equation, or more complex markup, you can use the `labels` argument: pass a dictionary that maps node names to Typst `content`. Each node with a name within the dictionary will have its label overridden by the corresponding content. ````typ #raw-render( ``` digraph { rankdir=LR node[shape=circle] Hmm -> a_0 Hmm -> big a_0 -> "a'" -> big [style="dashed"] big -> sum } ```, labels: (: big: [_some_#text(2em)[ big ]*text*], sum: $ sum_(i=0)^n 1/i $, ), ) ```` See [`examples/`](https://github.com/Robotechnic/diagraph/tree/main/examples) for the rendered graph. ## Build This project was built with emscripten `3.1.46`. Apart from that, you just need to run `make wasm` to build the wasm file. All libraries are downloaded and built automatically to get the right version that works. There are also some other make commands: - `make link`: Link the project to the typst plugin folder - `make clean`: Clean the build folder and the link - `make clean-link`: Only clean the link - `make compile_database`: Generate the compile_commands.json file - `make module`: It copy the files needed to run the plugin in a folder called `graphviz` in the current directory - `make wasi-stub`: Build the wasi stub executable, it require a rust toolchain properly configured ### Wasi stub Somme functions need to be stubbed to work with the webassembly plugin system. The `wasi-stub` executable is a spetial one fitting the needs of the typst plugin system. You can find the source code [here](https://github.com/astrale-sharp/wasm-minimal-protocol/tree/master). It is important to use this one as the default subbed functions are not the same and the makefile is suited for this one. ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details ## Changelog ### 0.2.2 - Fix an alignment issue - Added a better mathematic formula recognition for node labels ### 0.2.1 - Added support for relative lenghts in the `width` and `height` arguments - Fix various bugs ### 0.2.0 - Node labels are now handled by Typst ### 0.1.2 - Graphs are now scaled to make the graph text size match the document text size ### 0.1.1 - Remove the `raw-render-rule` show rule because it doesn't allow use of custom font and the `render` / `raw-render` functions are more flexible - Add the `background` parameter to the `render` and `raw-render` typst functions and default it to `transparent` instead of `white` - Add center attribute to draw graph in the center of the svg in the `render` c function ### 0.1.0 Initial working version
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/CHANGELOG/CHANGELOG-0.4.md
markdown
Apache License 2.0
# v0.4.1 ## Changelog since v0.4.1 **Full Changelog**: https://github.com/Myriad-Dreamin/typst.ts/compare/v0.4.0...v0.4.1 ### Security Notes No new security note. ### Bug fix - compiler: compile race condition in browser in https://github.com/Myriad-Dreamin/typst.ts/pull/393 - pkg::core: add a missing await in https://github.com/Myriad-Dreamin/typst.ts/pull/394 ### Changes - cli: improve TYPST_FONT_PATHS (typst#2746) in https://github.com/Myriad-Dreamin/typst.ts/pull/432 - compiler: use fontdb to load system fonts in https://github.com/Myriad-Dreamin/typst.ts/pull/403 - compiler: compile with env on stack in https://github.com/Myriad-Dreamin/typst.ts/pull/409 - compiler: replace diag features by CompileReporter in https://github.com/Myriad-Dreamin/typst.ts/pull/413 ### External Feature - build: build: upgrade to typst v0.10.0 in https://github.com/Myriad-Dreamin/typst.ts/pull/432 - pkg::parser: init in https://github.com/Myriad-Dreamin/typst.ts/pull/401 - pkg::core: expose render canvas api in https://github.com/Myriad-Dreamin/typst.ts/pull/404 and https://github.com/Myriad-Dreamin/typst.ts/pull/405 - cli: manual generation in https://github.com/Myriad-Dreamin/typst.ts/pull/408 - cli: export pdf with timestamp in https://github.com/Myriad-Dreamin/typst.ts/pull/423 - compiler: add query, getSemanticTokens api in https://github.com/Myriad-Dreamin/typst.ts/pull/398 - compiler: add offset encoding option for getSemanticTokens in https://github.com/Myriad-Dreamin/typst.ts/pull/400 - compiler: compile with env on stack in https://github.com/Myriad-Dreamin/typst.ts/pull/409 - compiler: post process handler for dyn layout in https://github.com/Myriad-Dreamin/typst.ts/pull/428 - exporter::text: add text exporter in https://github.com/Myriad-Dreamin/typst.ts/pull/422 - exporter::svg: layout and shape text in browser in https://github.com/Myriad-Dreamin/typst.ts/pull/416 and https://github.com/Myriad-Dreamin/typst.ts/pull/420 - exporter::svg: basic left-to-right text flow detection in https://github.com/Myriad-Dreamin/typst.ts/pull/421 - exporter::svg: pull better location handler from preview in https://github.com/Myriad-Dreamin/typst.ts/pull/419 - exporter::svg: update location handler for semantic labels in https://github.com/Myriad-Dreamin/typst.ts/pull/426 ### Internal Feature - proj: add cetz-editor in https://github.com/Myriad-Dreamin/typst.ts/pull/395 - proj: init highlighter in https://github.com/Myriad-Dreamin/typst.ts/pull/402 - core: add DynGenericExporter and DynPolymorphicExporter in https://github.com/Myriad-Dreamin/typst.ts/pull/411 - core: implement ligature handling in https://github.com/Myriad-Dreamin/typst.ts/pull/414 - core: add `PageMetadata::Custom` in https://github.com/Myriad-Dreamin/typst.ts/pull/425 - core: add getCustomV1 api in https://github.com/Myriad-Dreamin/typst.ts/pull/427 - compiler: export destination path to module in https://github.com/Myriad-Dreamin/typst.ts/pull/430 - compiler: add intern support in https://github.com/Myriad-Dreamin/typst.ts/pull/429 # v0.4.0 This is a major upgrade of typst.ts, so we decide to increment the minor version number. The most important change is that we have stabilized the API for TypstRenderer. We have also added guidance to typst.ts in https://github.com/Myriad-Dreamin/typst.ts/pull/391. One of the best features since v0.4.0 is that we provide a more user-friendly way to start exploring typst.ts, the all-in-one library apis: ``` <script type="module" src="/@myriaddreamin/typst.ts/dist/esm/contrib/all-in-one.bundle.js"></script> <script> document.ready(() => { const svg = await $typst.svg({ mainContent: 'Hello, typst!' }); }); </script> ``` See [All-in-one Library sample](https://github.com/Myriad-Dreamin/typst.ts/blob/main/packages/typst.ts/examples/all-in-one.html) for sample that previewing document in less than 200 LoCs and a single HTML. We have reworked vector format (IR) in https://github.com/Myriad-Dreamin/typst.ts/pull/317, https://github.com/Myriad-Dreamin/typst.ts/pull/324, and https://github.com/Myriad-Dreamin/typst.ts/pull/342. As a result, there are several notable changes: - Removed legacy artifact exporting in https://github.com/Myriad-Dreamin/typst.ts/pull/319. You can no longer get JSON output from typst.ts. Instead, use `typst.ts query` or `typst-ts-cli query` (v0.4.0+, https://github.com/Myriad-Dreamin/typst.ts/pull/286). - Refactored Renderer API in https://github.com/Myriad-Dreamin/typst.ts/pull/336 and https://github.com/Myriad-Dreamin/typst.ts/pull/338. Existing APIs still work but will be removed in v0.5.0. - Reworked canvas renderer with vector IR in https://github.com/Myriad-Dreamin/typst.ts/pull/318 and https://github.com/Myriad-Dreamin/typst.ts/pull/325. The new canvas renderer no longer needs to preload fonts (https://github.com/Myriad-Dreamin/typst.ts/pull/330). ## Changelog since v0.4.0 ## What's Changed **Full Changelog**: https://github.com/Myriad-Dreamin/typst.ts/compare/v0.3.1...v0.4.0 ### Security Notes No new security note. ### Bug fix - exporter::svg: missing quote in stroke dasharray by @Enter-tainer in https://github.com/Myriad-Dreamin/typst.ts/pull/332 - core: correctly align image items in https://github.com/Myriad-Dreamin/typst.ts/pull/282 - See [typst-preview: Failed to preview with figures on arm64 device](https://github.com/Enter-tainer/typst-preview/issues/77) - core: stable sort link items when lowering in https://github.com/Myriad-Dreamin/typst.ts/pull/306 - pkg::renderer: use approx float cmp by @seven-mile in https://github.com/Myriad-Dreamin/typst.ts/pull/297 - cli: calculate abspath before linking package in https://github.com/Myriad-Dreamin/typst.ts/pull/296 - compiler: formalize font search order in https://github.com/Myriad-Dreamin/typst.ts/pull/293 - compiler: reparse prefix editing in https://github.com/Myriad-Dreamin/typst.ts/pull/316 --- Since v0.4.0-rc3 - core: gc order in https://github.com/Myriad-Dreamin/typst.ts/pull/352 - core: hold span to/from u64 safety for users in https://github.com/Myriad-Dreamin/typst.ts/pull/361 - core: error is not send in https://github.com/Myriad-Dreamin/typst.ts/commit/05060cfe5a3bf9f0ba7404f069320cfcb3bb2aaa - compiler: eagle check syntax of the main file in https://github.com/Myriad-Dreamin/typst.ts/pull/374 - compiler: vfs panic when file not found by @Enter-tainer in https://github.com/Myriad-Dreamin/typst.ts/pull/380 - exporter::svg: broken clip on adjacent paths in https://github.com/Myriad-Dreamin/typst.ts/pull/386 - exporter::svg: partially disable incr rendering in https://github.com/Myriad-Dreamin/typst.ts/pull/387Dreamin/typst.ts/commit/ad69d915d14f587d8e9a40300bc85f6dac4364a1 - pkg::compiler: set default dummy access model in https://github.com/Myriad-Dreamin/typst.ts/pull/364 ### Changes - build: setup typescript monorepo with turbo in https://github.com/Myriad-Dreamin/typst.ts/pull/312 - You don't have to face the error-prone `yarn link` anymore. - core: remove legacy artifact exporting in https://github.com/Myriad-Dreamin/typst.ts/pull/319 - compiler: remove deprecated resolve_with in https://github.com/Myriad-Dreamin/typst.ts/pull/328 - pkg::core: refactor render api in https://github.com/Myriad-Dreamin/typst.ts/pull/336 and https://github.com/Myriad-Dreamin/typst.ts/pull/338 --- Since v0.4.0-rc3 - CSS change since typst v0.9.0 in https://github.com/Myriad-Dreamin/typst.ts/pull/384 Reference change: https://github.com/Myriad-Dreamin/typst.ts/commit/c9f185a6e16a901ae253bed2aef3c9ab1f49fd83#diff-8913391598d5e624d7d91114b7d3deb33a841833b79d7f6045258a5144abccfbL33-R36 ```css - .outline_glyph path { + .outline_glyph path, path.outline_glyph { fill: var(--glyph_fill); } - .outline_glyph path { + .outline_glyph path, path.outline_glyph { transition: 0.2s fill; } ``` ### External Feature - typst: sync to 0.8.0 in https://github.com/Myriad-Dreamin/typst.ts/pull/xxx - pkg::core: adapt and export render session - pkg::react: expose setWasmModuleInitOptions in https://github.com/Myriad-Dreamin/typst.ts/pull/311 - pkg::compiler: allow set dummy access model - cli: add query command in https://github.com/Myriad-Dreamin/typst.ts/pull/286 - cli: add interactive query command by Me and @seven-mile in https://github.com/Myriad-Dreamin/typst.ts/pull/289 - cli: specify fonts via an environment variable `TYPST_FONT_PATHS` in https://github.com/Myriad-Dreamin/typst.ts/pull/305 - compiler: add `set_{layout_widths,extension,target}` in https://github.com/Myriad-Dreamin/typst.ts/pull/299, https://github.com/Myriad-Dreamin/typst.ts/pull/304, and in https://github.com/Myriad-Dreamin/typst.ts/pull/308 - compiler: embed emoji fonts for browser compiler, which will increase much bundle size - docs: init typst.ts documentation in https://github.com/Myriad-Dreamin/typst.ts/pull/340 --- Since v0.4.0-rc3 - more convenient way to integrate projects in https://github.com/Myriad-Dreamin/typst.ts/pull/388 - exporter::svg: embed transparent html elements in https://github.com/Myriad-Dreamin/typst.ts/pull/379 - pkg::core: all-in-one library support in https://github.com/Myriad-Dreamin/typst.ts/commit/17d86f8a9325c62eddf59d5b52a117f1da2d3167 - pkg::core: let typst.ts work with node.js (nodenext) in https://github.com/Myriad-Dreamin/typst.ts/pull/366 - pkg::core: add option of assetUrlPrefix in https://github.com/Myriad- - pkg::compiler: load font asset from remote in https://github.com/Myriad-Dreamin/typst.ts/pull/368 - pkg::compiler: export to pdf api in https://github.com/Myriad-Dreamin/typst.ts/pull/372 - pkg::compiler: fetch package support in https://github.com/Myriad-Dreamin/typst.ts/pull/373 - compiler: new font distribute strategy in https://github.com/Myriad-Dreamin/typst.ts/pull/362 You can install `typst-ts-cli` by cargo since this PR: ``` cargo install --locked --git https://github.com/Myriad-Dreamin/typst.ts typst-ts-cli ``` - compiler: add actor for watch compiler in https://github.com/Myriad-Dreamin/typst.ts/pull/371 ### Internal Feature - core: rework vector format (IR) in https://github.com/Myriad-Dreamin/typst.ts/pull/317, https://github.com/Myriad-Dreamin/typst.ts/pull/324, and https://github.com/Myriad-Dreamin/typst.ts/pull/342 - compiler: pollyfill time support in browser - exporter::canvas: rework with vector ir in https://github.com/Myriad-Dreamin/typst.ts/pull/318 and https://github.com/Myriad-Dreamin/typst.ts/pull/325 - corpora: auto add std test cases in https://github.com/Myriad-Dreamin/typst.ts/pull/331 --- Since v0.4.0-rc3 - test: add incremental compilation fuzzer in https://github.com/Myriad-Dreamin/typst.ts/pull/370
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/modern-cv/0.2.0/README.md
markdown
Apache License 2.0
# Modern CV [![say thanks](https://img.shields.io/badge/Say%20Thanks-👍-1EAEDB.svg)](https://github.com/DeveloperPaul123/modern-cv/stargazers) [![Discord](https://img.shields.io/discord/652515194572111872?logo=Discord)](https://discord.gg/CX2ybByRnt) ![Release](https://img.shields.io/github/v/release/DeveloperPaul123/modern-cv) [![Build documentation](https://github.com/DeveloperPaul123/modern-cv/actions/workflows/build-documentation.yml/badge.svg)](https://github.com/DeveloperPaul123/modern-cv/actions/workflows/build-documentation.yml) A port of the [Awesome-CV](https://github.com/posquit0/Awesome-CV) Latex resume template in [typst](https://github.com/typst/typst). ## Requirements You will need the `Roboto` and `Source Sans Pro` fonts installed on your system or available somewhere. If you are using the `typst` web app, no further action is necessary. You can download them from the following links: - [Roboto](https://fonts.google.com/specimen/Roboto) - [Source Sans Pro](https://github.com/adobe-fonts/source-sans-pro) This template also uses FontAwesome icons via the [fontawesome](https://typst.app/universe/package/fontawesome) package. You will need to install the fontawesome fonts on your system or configure the `typst` web app to use them. You can download fontawesome [here](https://fontawesome.com/download). To use the fontawesome icons in the web app, add a `fonts` folder to your project and upload the `otf` files from the fontawesome download to this folder like so: ![alt text](assets/images/typst_web_editor.png) See `typst fonts --help` for more information on configuring fonts for `typst` that are not installed on your system. ### Usage Below is a basic example for a simple resume: ```typst #import "@preview/modern-cv:0.1.0": * #show: resume.with( author: ( firstname: "John", lastname: "Smith", email: "<EMAIL>", phone: "(+1) 111-111-1111", github: "DeveloperPaul123", linkedin: "Example", address: "111 Example St. Example City, EX 11111", positions: ( "Software Engineer", "Software Architect" ) ), date: datetime.today().display() ) = Education #resume-entry( title: "Example University", location: "B.S. in Computer Science", date: "August 2014 - May 2019", description: "Example" ) #resume-item[ - #lorem(20) - #lorem(15) - #lorem(25) ] ``` After saving to a `*.typ` file, compile your resume using the following command: ```bash typst compile resume.typ ``` For more information on how to use and compile `typst` files, see the [official documentation](https://typst.app/docs). Documentation for this template is published with each commit. See the attached PDF on each Github Action run [here](https://github.com/DeveloperPaul123/modern-cv/actions). ### Output Examples | Resumes | Cover letters | | --- | --- | | ![Resume](assets/images/resume.png) | ![Cover Letter](assets/images/coverletter.png) | | | ![Cover Letter 2](assets/images/coverletter2.png)|
https://github.com/jrihon/multi-bibs
https://raw.githubusercontent.com/jrihon/multi-bibs/main/chapters/02_chapter/introduction.typ
typst
MIT License
#import "../../lib/multi-bib.typ": * #import "bib_02_chapter.typ": biblio == Introduction #lorem(50). Afterwards the thing haasnoot1992conformation did cool thing, together with stuff #mcite(("Zgarbova2015dnaol15"), biblio).
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/perf-nest.typ
typst
Apache License 2.0
#let f(..arg) = arg #f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(1,2,3))))))))))))))))))))))
https://github.com/nathanielknight/tsot
https://raw.githubusercontent.com/nathanielknight/tsot/main/src/utils_phase.typ
typst
#let title(t) = { align( center, block( above: 0%, below: 8mm, text(font: "National Park", size: 8mm, weight: "bold")[#t] ) ) }
https://github.com/flaribbit/numbly
https://raw.githubusercontent.com/flaribbit/numbly/master/README.md
markdown
MIT License
# numbly A package that helps you to specify different numbering formats for different levels of headings. ## Usage example Suppose you want to specify the following numbering format for your document: - Appendix A. Guide - A.1. Installation - Step 1. Download - Step 2. Install - A.2. Usage You might use `if` to achieve this: ```typst #set heading(numbering: (..nums) => { nums = nums.pos() if nums.len() == 1 { return "Appendix " + numbering("A.", ..nums) } else if nums.len() == 2 { return numbering("A.1.", ..nums) } else { return "Step " + numbering("1.", nums.last()) } }) = Guide == Installation === Download === Install == Usage ``` But with `numbly`, you can do this more easily: ```typst #import "@preview/numbly:0.1.0": numbly #set heading(numbering: numbly( "Appendix {1:A}.", // use {level:format} to specify the format "{1:A}.{2}.", // if format is not specified, arabic numbers will be used "Step {3}.", // here, we only want the 3rd level )) ``` ## General explanation In general the function `numbly` takes an arbitrary number of string arguments. The first argument specifies the formating of the numbering of the first level headers, the second for the second level headers and so on. If one wants to access the number of the $n$th level header, one can use `{n:f}`, where `f` is a counting symbol, which states how the number is represented (e.g. `1` stands for arabic numbers, which is the default, `I` for roman numbers from capital letters and so on). A list of all possible counting symbols can be found in the typst documentation of numbering (https://typst.app/docs/reference/model/numbering/).
https://github.com/elteammate/typst-shell-escape
https://raw.githubusercontent.com/elteammate/typst-shell-escape/main/example-python.typ
typst
#import "shell-escape.typ": * #let python(code) = { if type(code) == "content" { code = code.text } code = code.replace("\\", "\\\\") code = code.replace("\"", "\\\"") exec-command("python -c \"" + code + "\"") } #python("print(\"Hello, world!\")") #python("print(2 + 2)") #let py(code) = python("print(" + code + ")").stdout #py("2 + 2 * 2 + 2 * 2") // If you uncomment the following line, you can enter a python expression // in the terminal where you run the filesystem thingy. // The compiler will wait, the filesystem should not. // #py("eval(input())")
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/布局/place/place.typ
typst
= place 将内容放置在绝对位置。 放置的内容不会影响其他内容的位置。Place 始终相对于其父容器,并且将位于容器中所有其他内容的前台。页面边距将得到尊重。 == 例 #image("屏幕截图 2024-04-16 164918.png")
https://github.com/pluttan/typst-bmstu
https://raw.githubusercontent.com/pluttan/typst-bmstu/main/bmstu/g7.32-2017/decoration.typ
typst
MIT License
#let гост732-2017(content) = { set page( footer: context [ #text(size: 14pt)[ #let (num,) = counter(page).get() #if (num != 1) { align(center)[#num] }] ], paper: "a4", margin: (left: 30mm, right: 15mm, top: 20mm, bottom: 20mm), ) set text(font: "Times New Roman", size: 14pt, lang: "ru") set heading(numbering: "1.1") set align(top) show heading.where(level:1): it => { pagebreak() set text(14pt, hyphenate: false) upper[#align(center)[#it]] par(text(size: 0.35em, h(0.0em))) } show heading.where(level:2): it => { set text(16pt, hyphenate: false) it par(text(size: 0.35em, h(0.0em))) } show heading.where(level:3): it => { set text(14pt, hyphenate: false) it par(text(size: 0.35em, h(0.0em))) } set par(justify: true, first-line-indent: 1.25cm) set list(indent: 1.25cm) show list: it => { it par(text(size: 0.35em, h(0.0em))) } set enum(indent: 1.25cm) show enum: it => { it par(text(size: 0.35em, h(0.0em))) } show raw: it => { box( fill: luma(240), inset: (x:6pt, y:0pt), outset: (y:3pt), radius: 4pt, align(left)[it] ) } content }
https://github.com/chen-qingyu/Typst-Code
https://raw.githubusercontent.com/chen-qingyu/Typst-Code/master/limit%202.typ
typst
#let LF = {v(3em); linebreak()} $ & lim_(x -> 0) ((a_1^x + a_2^x + a_3^x + dots.c + a_n^x) / n)^(1/x) LF =& lim_(x -> 0) e^((1/x ln (a_1^x + a_2^x + a_3^x + dots.c + a_n^x) / n)) LF =& lim_(x -> 0) e^((1/x ln (1 + (a_1^x + a_2^x + a_3^x + dots.c + a_n^x - n) / n))) LF =& lim_(x -> 0) e^((1/x ((a_1^x + a_2^x + a_3^x + dots.c + a_n^x - n) / n))) LF =& lim_(x -> 0) e^(((a_1^x + a_2^x + a_3^x + dots.c + a_n^x - n) / (n x))) LF =& lim_(x -> 0) e^(((a_1^x ln a_1 + a_2^x ln a_2 + a_3^x ln a_3 + dots.c + a_n^x ln a_n)/ n)) LF =& e^(((ln a_1 + ln a_2 + ln a_3 + dots.c + ln a_n)/ n)) LF =& e^((1/n ln (a_1 a_2 a_3 dots.c a_n))) LF =& (a_1 a_2 a_3 dots.c a_n)^(1/n) LF $
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/lib/palette.typ
typst
Apache License 2.0
#let base-style = (stroke: (paint: black), fill: none) /// Create a new palette based on a base style /// /// #example(``` /// let p = cetz.palette.new(colors: (red, blue, green)) /// for i in range(0, p("len")) { /// set-style(..p(i)) /// circle((0,0), radius: .5) /// set-origin((1.1,0)) /// } /// ```) /// /// The functions returned by this function have the following named arguments: /// #show-parameter-block("fill", ("bool"), default: true, [ /// If true, the returned fill color is one of the colors /// from the `colors` list, otherwise the base styles fill is used. /// ]) /// #show-parameter-block("stroke", ("bool"), default: false, [ /// If true, the returned stroke color is one of the colors /// from the `colors` list, otherwise the base styles stroke color is used. /// ]) /// /// You can use a palette for stroking via: `red.with(stroke: true)`. /// /// - base (style): Style dictionary to use as base style for the styles generated /// per color /// - colors (none, array): List of colors the returned palette should return styles with /// - dash (none, array): List of stroke dash patterns the returned palette should return styles with /// /// -> function Palette function of the form `index => style` that returns a style for an integer index #let new(base: base-style, colors: (), dash: ()) = { if not "stroke" in base { base.stroke = (paint: black, thickness: 1pt, dash: "solid") } if not "fill" in base { base.fill = none } let color-n = colors.len() let pattern-n = dash.len() return (index, fill: true, stroke: false) => { if index == "len" { return calc.max(color-n, pattern-n, 1) } let style = base if pattern-n > 0 { style.stroke.dash = dash.at(calc.rem(index, pattern-n)) } if color-n > 0 { if stroke { style.stroke.paint = colors.at(calc.rem(index, color-n)) } if fill { style.fill = colors.at(calc.rem(index, color-n)) } } return style } } // Predefined color themes #let tango-colors = ( "edd400", "f57900", "c17d11", "73d216", "3465a4", "75507b", "cc0000", "d3d7cf", "555753").map(rgb) #let tango-light-colors = ( "fce94f", "fcaf3e", "e9b96e", "8ae234", "729fcf", "ad7fa8", "ef2929", "eeeeec", "888a85").map(rgb) #let tango-dark-colors = ( "c4a000", "ce5c00", "8f5902", "4e9a06", "204a87", "5c3566", "a40000", "babdb6", "2e3436").map(rgb) #let rainbow-colors = ( "#9400D4", "#4B0082", "#0000FF", "#00FF00", "#FFFF00", "#FF7F00", "#FF0000").map(rgb) #let red-colors = ( "#FFCCCC", "#FF9999", "#FF6666", "#FF3333", "#CC0000").map(rgb) #let orange-colors = ( "#FFE5CC", "#FFCC99", "#FFB266", "#FF9933", "#FF8000").map(rgb) #let light-green-colors = ( "#E5FFCC", "#CCFF99", "#B2FF66", "#99FF33", "#72E300", "#66CC00", "#55A800", "#478F00", "#3A7300", "#326300").map(rgb) #let dark-green-colors = ( "#80E874", "#5DD45D", "#3CC23C", "#009900", "#006E00").map(rgb) #let turquoise-colors = ( "#C0FFD3", "#99FFCC", "#66FFB2", "#33FF99", "#4BD691").map(rgb) #let cyan-colors = ( "#CCFFFF", "#99FFFF", "#66FFFF", "#00F3F3", "#00DADA").map(rgb) #let blue-colors = ( "#BABAFF", "#9999FF", "#6666FF", "#3333FF", "#0000CC").map(rgb) #let indigo-colors = ( "#BABAFF", "#9999FF", "#6666FF", "#3333FF", "#0000CC").map(rgb) #let purple-colors = ( "#E0C2FF", "#CC99FF", "#B266FF", "#9933FF", "#7F00FF").map(rgb) #let magenta-colors = ( "#FFD4FF", "#FF99FF", "#FF66FF", "#F331F3", "#DA00DA").map(rgb) #let pink-colors = ( "#FFCCE5", "#FF99CC", "#FF66B2", "#FF3399", "#F20C7F", "#DB006B", "#C30061", "#99004C", "#800040", "#660033").map(rgb) // Predefined palettes #let gray = new(colors: range(90, 40, step: -12).map(v => luma(v * 1%))) #let red = new(colors: red-colors) #let orange = new(colors: orange-colors) #let light-green = new(colors: light-green-colors) #let dark-green = new(colors: dark-green-colors) #let turquoise = new(colors: turquoise-colors) #let cyan = new(colors: cyan-colors) #let blue = new(colors: blue-colors) #let indigo = new(colors: indigo-colors) #let purple = new(colors: purple-colors) #let magenta = new(colors: magenta-colors) #let pink = new(colors: pink-colors) #let rainbow = new(colors: rainbow-colors) #let tango = new(colors: tango-colors) #let tango-light = new(colors: tango-light-colors) #let tango-dark = new(colors: tango-dark-colors)
https://github.com/jomaway/typst-gentle-clues
https://raw.githubusercontent.com/jomaway/typst-gentle-clues/main/gc-overview.typ
typst
MIT License
#import "lib/predefined.typ": * #import "lib/clues.typ": clue #set page(paper: "a5", flipped: true, margin: 1cm) #let predefined-clues = ( idea[`#idea[]`], abstract[`#abstract[]`], question[`#question[]`], info[`#info[]`], example[`#example[]`], experiment[`#experiment[]`], task[`#task[]`], error[`#error[]`], warning[`#warning[]`], success[`#success[]`], tip[`#tip[]`], conclusion[`#conclusion[]`], memo[`#memo[]`], quotation[`#quotation[]`], goal[`#goal[]`], notify[`#notify[]`], code[`#code[]`], danger[`#danger[]`] ) #let clue-grid = grid( columns: 4, gutter: 12pt, ..predefined-clues ) #clue(title:"Gentle Clues - Overview", header-color: gradient.linear(..color.map.crest), body-color: color.white)[ #clue-grid ]