repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/b647c0-lug_101_ch7/main.typ
typst
#import "@preview/polylux:0.3.1": * #import "@preview/diagraph:0.2.1": * #set page(paper: "presentation-16-9") #set text( font: ("linux libertine", "Source Han Serif SC", "Source Han Serif"), size: 25pt, ) #show heading: it => text(fill: rgb("11999e"), it) #show raw.where(block: true): it => { box( fill: blue.lighten(95%), inset: (x: 10pt, y: 2pt), outset: (x: 0pt, y: 8pt), radius: 2pt, )[ #set text(size: 15pt) #it ] } #polylux-slide[ #align(horizon + center)[ = Linux 101 Chapter 7\ Linux 上的编程 \ <NAME> 2024.05.14 ] // Talking points: // 自我介绍 ] #polylux-slide[ == Contents - Programming with C/C++ - GCC - GNU Make - CMake - Programming with Python - Python 3 - `pip` - `venv` // - Jupyter Notebook // Talking points: // 今天主要介绍的内容是在 Linux 上的编程, 我们会从 C/C++ 和 Python 两个方面来讲. // 在讲述过程中, 我预期大家已经了解语言本身的基础, (比如已经在 IDE 中写过代码, 了解基本的语法). // 但是没有经验也不要紧, 我们今天不会使用很复杂的特性, 会从最基础的开始. // 更重要的是相关工具的讲解. ] #polylux-slide[ #align(horizon + center)[ == Pt. 1\ Programming with C/C++ ] ] #polylux-slide[ == Programming with C/C++ 我们从一个简单的 `main.c` 开始: ```c #include <stdio.h> int main() { printf("Hello, World!\n"); return 0; } ``` 在 Linux 上, 可以很方便的通过 `gcc` 编译: ```bash gcc -o main main.c && ./main ``` 如果编译成功不会输出任何内容, 这是 Unix 哲学的一部分. // Talking points: // 现场 demo: // cat main.c // gcc main.c -o main // ./main ] #polylux-slide[ == GCC - GNU 1.0 时其实是 `GNU C Compiler`, 后来扩展到了 C++, Fortran, Objective-C 等. 现在的 GCC 是 *GNU Compiler Collection*. - 在 GCC 12.2 中, 包含了 C: `gcc` , C++:`g++` , Objective-C , Fortan: `gfortan` 等前端; 指令集的支持包含 x86, x86-64, ARM, MIPS 等. - GCC 是大部分 Linux 发行版的标准编译器, 也是很多嵌入式系统的首选. // Talking points: // 现场 demo: // GCC 安装, 两个发行版 (Ubuntu, Arch) 的安装方式: // Ubuntu: // sudo apt install gcc // 但是更推荐安装 build-essential // Arch: // sudo pacman -S gcc // 但是更推荐安装 base-devel ] #polylux-slide[ == 多文件: 编译、链接 我们继续上一个 demo, 把 `print()` 函数拆出来: #show: it => columns(2, it) ```c // print.c #include <stdio.h> void print() { printf("Hello, World!\n"); } ``` ```c // print.h #ifndef PRINT_H #define PRINT_H void print(); #endif // PRINT_H ``` ```c // main.c #include "print.h" int main() { print(); return 0; } ``` ] #polylux-slide[ == 多文件: 编译、链接 手动操作需要我们手动将每个文件编译成目标文件, 然后链接: ```bash gcc -c print.c -o print.o gcc -c main.c -o main.o gcc print.o main.o -o main && ./main ``` `gcc -c` 会编译出 #text(weight: "bold")[O]bject file (对象文件) 是一类二进制产物, 不能直接运行的原因在于其中外部引用的符号没有解析. 如果只有这两个文件, 上述编译过程也可以简化为: ``` gcc print.c main.c -o main ``` ] #polylux-slide[ == Behind the Scene #raw-render(```dot digraph { rankdir=LR; node [shape=rect]; c; i; s; o; r; c -> i [label="gcc -E"]; i -> s [label="gcc -S"]; s -> o [label="gcc -c"]; o -> r [label="gcc"]; } ```) - `gcc -E`: 预处理 ( _Pre-process_ ) `cpp`: 展开宏, 处理 `#include` 等 $=>$ `*.i`. - `gcc -S`: 编译 ( _Complication_ ) `cc1`, 生成汇编代码 $=>$ `*.s`. - `gcc -c`: 汇编 ( _Assembly_ ) `as`, 生成目标文件 $=>$`*.o`. - `gcc`: 链接 ( _Linking_ ) `ld`, 生成可执行文件. ] #polylux-slide[ == 大型项目怎么办? 上面讲述的是一个简单的多文件项目, 但是在实际项目中: - 文件数量更多, 以 Linux kernel 为例, 有 8 万多个文件. ```console $ find . -type f | wc -l 84374 ``` - 依赖关系复杂, 有些文件需要先编译, 有些文件需要先链接. - 外部库的链接, 比如 `libm`, `libpthread` 等. - 增量编译, 只编译修改过的文件. ] #polylux-slide[ == GNU Make - `make` 是一个自动化编译工具, 用于管理多文件项目的编译过程 - `Makefile` 由一系列规则组成, 每个规则包含了目标, 依赖和命令. - 一个简单的 `Makefile`: ```make main.o: main.c print.h print.o: print.c print.h main: main.o print.o ``` 接着只需要执行 ```bash make main ``` ] #polylux-slide[ == GNU Make #set text(size: 20pt) 我们来解释下上面的 `Makefile`: ```make main.o: main.c print.h ``` 指定了一个规则, `main.o` 是目标, `main.c print.h` 是依赖. 因为文件中没有声明 `main.c` 为目标, 则对应的文件成为依赖. 事实上, `make` 会自动推导出命令, 也就是: ```bash gcc -c main.c -o main.o ``` 也可以手动在 `Makefile` 中指定: ```make main.o: main.c print.h gcc -c main.c -o main.o # 使用 Tab 缩进而不是空格 ``` // Talking points: // 通常情况下, 我们不需要手动指定命令, make 会自动推导. // Makefile 的亮点在于引入了 「文件之间的依赖关系」,通过文件更新时间来判断是否需要重新编译. // 这也可以解决编译、链接顺序的问题. ] #polylux-slide[ == CMake // - `CMake` 是一个跨平台的构建工具, 用于管理多文件项目的编译过程. - `CMakeLists.txt` 由一系列命令组成, 每个命令包含了目标, 依赖和命令. - 一个简单的 `CMakeLists.txt`: ```cmake cmake_minimum_required(VERSION 3.20) project(main) add_executable(main main.c print.c) ``` 接着只需要执行 ```bash mkdir build && cd build cmake .. make ``` // Talking points: // CMake 的介绍超过本课程的范围. 它被创建出来是解决 Makefile 难以编写和维护的问题. // 但是在现如今, CMake 也缺少一些现代功能, 例如包管理等. // vcpkg, conan 等工具可以用来解决这个问题. // 另外值得一题的是, CMake 是跨平台的工具, 在 Linux 平台上, 下一步是生成 Makefile, 然后调用 make. // 但是在 Windows 平台上, 会生成 Visual Studio 的项目文件, 然后调用 MSBuild (msvc). // 在 Linux 上也可以选择其他编译工具, 比如 Ninja. // Ninja 是跟 Makefile 类似的构建工具, 但是更快, 更简洁. ] #polylux-slide[ #align(horizon)[ == Rust? 作为一个现代的编译语言, Rust 在语言层面解决了很多 C/C++ 的问题的同时, 自带的工具链也非常强大. 作为课程的延伸, 请可以尝试使用 Rust 来编写项目, 了解一下 Rust 的工具链. ] ] #polylux-slide[ #align(horizon + center)[ == Pt. 2\ Programming with Python ] ] #polylux-slide[ == Programming with Python 在 Linux 上开发 Python 会比 Windows 上方便的多. 从安装的角度, 只需要从软件仓库中安装即可: ```bash sudo apt install python3 python3-pip python3 -V pip3 -V # Run: python3 main.py ``` #strike[在 Windows 上你甚至还要解决应用商店版本的 Python 污染 PATH 的问题]. // Talking points: // Python REPL // python main.py // Windows 上麻烦事, winget search python // Windows 上安装方法, winget install Python.Python3.7 (?) ] #polylux-slide[ == Interpreted Lang / 解释型语言 与编译型语言不同, 解释型语言并不是在编译期生成可执行文件, 而是在运行时解释执行. 诸如 Python, Java 等语言会首先将代码转成 Bytecode, 接着在虚拟机上执行. 得益于这些特性, 跨平台、动态类型等特性也就成为了可能. 到 2024 年, 几乎所有发行版都会预装 Python. ] #polylux-slide[ == Python 2? 与很多人猜测的不同, Python 其实并不是一门很新的语言. 从 Python 2 到 Python 3, 这几乎完全是一门新语言, 最典型的就是 print 函数的变化. ```python print "Hello, World!" ``` ```python print("Hello, World!") ``` 这样的转变使得迁移异常麻烦, 因此很多发行版(例如 Ubuntu), 出于历史原因, 仍然会预装 Python 2, 并且 `python` 默认指向 Python 2. 如果可能的话, 在脚本/命令中显式指定 `python3` 可能是一个好习惯. ] #polylux-slide[ == Which Python? 在 2023 年末, Python 3.7 已经 EOL (end of life). Python 并没有 LTS 的概念, 每个发行版都会以相同的周期维护、更新. #rect(inset: 0.5em)[ *在 2024 年 5 月, 我们推荐 Python 3.11.* (或者发行版自带的版本) ] 从 Python 2 $=>$ Python3 迁移的巨大代价让社区认识到了向后兼容的重要性, Python 3.x 几乎不会 break 之前的代码; 新版本的 Python 一般会带来新的语言特性, 诸如 typing 等. ] #polylux-slide[ == pip / 拿来主义 Python (相比之下) 完善的包管理、社区是 Python 成为热门语言的原因之一. 大部分时候不需要纠结「怎么使用第三方库的问题」,只需要简单的从 `PyPI` 安装即可. ```bash pip install numpy ``` #set text(size: 20pt) 因为网络问题, 也许需要加上 `-i` 参数指定源: ```bash pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple ``` ] #polylux-slide[ == pip / 拿来主义 完善的第三方库带来的收益是巨大的, 通常情况下这意味着你可以更轻松的用 Python 来解决问题. #set text(size: 15pt) #strike[某打卡脚本]: ```python import requests import json import time import datetime import pytz import re import sys import argparse from bs4 import BeautifulSoup ``` ] #polylux-slide[ == pip / 拿来主义 #set text(size: 20pt) 这也意味着需要一个更方便的办法来安装这些库, 通常的包装方法是 `requirements.txt`: ```txt requests==2.26.0 numpy==1.21.2 matplotlib==3.4.3 ``` 其他人安装的时候只需要执行: ```bash pip install -r requirements.txt ``` #rect(inset: 0.5em)[ 固定版本号通常是一个好习惯. 如果你的程度两年后没更新, 但是库更新了, 这时如果不指定版本号, 可能会导致代码无法运行. ] ] #polylux-slide[ == Virtualenv #set text(size: 20pt) 上面提到, 通常我们需要指定第三方库的版本, 有时候这些库的版本可能会冲突. `pip` 不允许同时安装一个包的不同版本, 如果全局安装有冲突, 需要手动解决. 一个解决方案是使用 `virtualenv`: ```bash python3 -m venv venv source venv/bin/activate pip install -r requirements.txt ``` // Talking: `venv` 一般默认随 Python 一起安装, 也可以通过 `sudo apt install python3-venv` 安装. 执行上述操作后的结果是: 在当前目录下生成了一个 `venv` 目录, 里面包含了一个独立的 Python 环境. 所有的 `pip` 包都会安装在这个环境下, 与全局环境隔离. 进入环境后, `python` 和 `pip` 都会指向这个环境下的版本; 可以通过 `deactivate` 退出环境. ] #polylux-slide[ #align(horizon)[ == Node.js? Node.js 的包管理器 npm 也是一个很好的包管理工具, 与 Python 的 pip 类似. 作为课程的延伸, 请可以尝试使用 Node.js 来编写项目, 了解一下 Node.js 的工具链, 注意 `package.json` 的使用. ] ] #polylux-slide[ #align(horizon + center)[ = Thanks. ] ]
https://github.com/mitinarseny/invoice
https://raw.githubusercontent.com/mitinarseny/invoice/main/src/invoice.typ
typst
#import "./header.typ": header #import "./parties.typ": parties #import "./items.typ": items as make_items #import "./payment.typ": payment as make_payment #import "./signature.typ": signature as make_signature #let invoice( id: none, issue_date: none, due_date: none, contractor: none, billed_to: none, service: none, additional_items: none, payment: none, signature: none, ) = { grid( columns: (1fr), rows: (1fr, 5fr, 5fr, 1.5fr, 1fr), gutter: 1fr, header(id, issue_date, due_date), parties(contractor, billed_to), make_items(service, ..additional_items), make_payment(payment), make_signature( signature.date, signature.at("location", default: none), signature.at("name", default: contractor.name), signature.at("sign", default: none), ), ) }
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/zalmy/Z102.typ
typst
Dobroreč, duša moja, Pánovi \* a celé moje vnútro jeho menu svätému. Dobroreč, duša moja, Pánovi \* a nezabúdaj na jeho dobrodenia. Veď on ti odpúšťa všetky neprávosti, \* on lieči všetky tvoje neduhy; on vykupuje tvoj život zo záhuby, \* on ťa venčí milosrdenstvom a milosťou; on naplňuje dobrodeniami tvoje roky, \* preto sa ti mladosť obnovuje ako orlovi. Pán koná spravodlivo \* a prisudzuje právo všetkým utláčaným. Mojžišovi zjavil svoje cesty \* a synom Izraela svoje skutky. Milostivý a milosrdný je Pán, \* zhovievavý a dobrotivý nesmierne. Nevyčíta nám ustavične naše chyby \* ani sa nehnevá naveky. Nezaobchodí s nami podľa našich hriechov \* ani nám neodpláca podľa našich neprávostí. Lebo ako vysoko je nebo od zeme, \* také veľké je jeho zľutovanie voči tým, čo sa ho boja. Ako je vzdialený východ od západu, \* tak vzďaľuje od nás našu neprávosť. Ako sa otec zmilúva nad deťmi, \* tak sa Pán zmilúva nad tými, čo sa ho boja. Veď on dobre vie, z čoho sme stvorení; \* pamätá, že sme iba prach. Ako tráva sú dni človeka, \* odkvitá sťa poľný kvet. Ledva ho vietor oveje, už ho niet, \* nezostane po ňom ani stopa. No milosrdenstvo Pánovo je od večnosti až na večnosť \* voči tým, čo sa ho boja, a jeho spravodlivosť chráni ich detné deti, \* tie, čo zachovávajú jeho zmluvu, čo pamätajú na jeho prikázania a plnia ich. Pán si pripravil trón v nebesiach; \* kraľuje a panuje nad všetkými. Dobrorečte Pánovi, všetci jeho anjeli, \* udatní hrdinovia, čo počúvate jeho slová a plníte jeho príkazy. Dobrorečte Pánovi, všetky jeho zástupy, \* jeho služobníci, čo jeho vôľu plníte. Dobrorečte Pánovi, všetky jeho diela, všade, kde on panuje. \* Dobroreč, duša moja, Pánovi. Všade, kde on panuje. \* Dobroreč, duša moja, Pánovi.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-fill-stroke_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test stroke folding. #let sq(..args) = box(square(size: 10pt, ..args)) #set square(stroke: none) #sq() #set square(stroke: auto) #sq() #sq(fill: teal) #sq(stroke: 2pt) #sq(stroke: blue) #sq(fill: teal, stroke: blue) #sq(fill: teal, stroke: 2pt + blue)
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/lib.typ
typst
#import "@preview/codly:1.0.0": * #import "@preview/gentle-clues:0.9.0": * #import "@preview/cuti:0.2.1": show-cn-fakebold #import "@preview/showybox:2.0.1": showybox #import "@preview/cetz:0.2.2" #import "@preview/mitex:0.2.4":* #import "@preview/lovelace:0.3.0": * #import "@preview/finite:0.3.2":automaton #import "@preview/commute:0.2.0":* #let ( BLUE, GREEN, YELLOW, RED, )=( rgb("#4285f4"), rgb("#34a853"), rgb("#fbbc05"), rgb("#ea4335"), ) #let BlueText(_text)={ set text(fill: BLUE) [#_text] } #let GreenText(_text)={ set text(fill: GREEN) [#_text] } #let YellowText(_text)={ set text(fill: YELLOW) [#_text] } #let RedText(_text)={ set text(fill: RED) [#_text] } #import "@preview/suiji:0.3.0": * #let Colorful(_text)={ let colors = ( rgb("#4285F4"), rgb("#34A853"), rgb("#FBBC05"), rgb("#EA4335"), ) let i=7; let rng = gen-rng(_text.text.len() * i); let index_pre = integers(rng, low: 0, high: 4, size: none, endpoint: false).at(1); for c in _text.text{ let rng = gen-rng(i - 1); let index_cur = integers(rng, low: 0, high: 4, size: none, endpoint: false).at(1); let cnt=100; while index_cur == index_pre and cnt>0{ let rng = gen-rng(cnt + i); index_cur = integers(rng, low: 0, high: 4, size: none, endpoint: false).at(1); cnt -= 1; } let color = colors.at(index_cur); set text(fill: color) [#c] index_pre = index_cur; i += 2; } } // #let Link(_link)=box(link(_link,image("assets/link.svg")), height: 1em) #let Title( title:[], reflink:"", level:1, )={ let pic = ( "", "assets/easy.svg", "assets/medium.svg", "assets/hard.svg", ) box( image(pic.at(level), height: 1em), ) [#title] box( link(reflink,image("assets/link.svg", height: 1em)) ) } #let note( difficuty:[], title:[标题], description:[描述], examples:(), tips:[提示], solutions:(), code:[代码], gain:none, )={ block({ question( title:title, )[#description] let i=1; for _example in examples { example( title:"示例" + str(i), )[#_example] i+=1; } tip( title:[提示], )[#tips] let j=1; // pagebreak() for solution in solutions { idea( title:"方法" + str(j)+": "+solution.name, )[#solution.text #solution.code ] j+=1; } if(gain != none){ conclusion( title:[笔记], )[#gain] } }) } #let xquotation(first:[],second:[])=if first != [ ]{ quotation( title:[书内链接], )[ #columns(2)[ #set par(justify: true) #first #colbreak() #second ] ] } yes! it works! #let llltable(titles:[],columns:1,caption:[],align:left,kind:"table",supplement:[表],..items)={ let items=items.pos()//在函数定义中,..bodies 表示接收任意数量的参数,这些参数被收集到一个特殊的 参数对象(arguments object) 中.bodies.pos() 方法从参数对象中提取所有的 位置参数,并返回一个 序列(sequence),即一个有序的参数列表。 figure( kind:kind, supplement:supplement, caption: caption, table( stroke: none, columns: columns, align: align, table.hline(), // table.header( // for title in titles { // strong(title) // } // ), titles, table.hline(), ..items, table.hline(), ), ) } #let algo(caption:[],content:[])={ figure( kind: "algorithm", caption: caption, supplement: [算法], content ) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/accelerated-jacow/0.1.0/README.md
markdown
Apache License 2.0
# Accelerated JACoW template for typst Paper template for conference proceedings in accelerator physics. Based on the JACoW guide for preparation of papers available at https://jacow.org/. ## Usage **Web app:** In the [typst web app](https://typst.app) select "start from template" and search for the accelerated-jacow template. **CLI:** Run these commands inside your terminal: ```sh typst init @preview/accelerated-jacow cd accelerated-jacow typst watch paper.typ ``` ![Thumbnail](thumbnail.webp) ## Licence Files inside the template folder are licensed under MIT-0. You can use them without restrictions. The citation style (CSL) file is based on the IEEE style and licensed under the [CC BY SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) compatible [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html) license. All other files are licensed under [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html).
https://github.com/19pdh/suplement-sprawnosci
https://raw.githubusercontent.com/19pdh/suplement-sprawnosci/master/sprawnosci.typ
typst
#import "style.typ": tagi, lay = ORGANIZACJA ZBIÓREK #tagi("#awangarda #zastępowy #wódz #co_dziś_robimy") Gdybym mógł wybierać miejsce, które chciałbym zajmować w ruchu, to chciałbym być zastępowym. #align(right)[gen. <NAME>-Powell] #v(0.5em) #text(weight: "bold")[ Sprawności z tego drzewka przyznawane są w ramach kursu zastępowych naszego hufca. Każdy może zawsze i wszędzie zdobywać tą sprawność, ale przyznawana ona jest tylko raz w roku, na apelu kończącym kurs zastępowych. ] #v(1cm) #grid( columns: 2, gutter: 1cm, image("krazki/awangarda1.png", width: 3.5cm), [ == Awangarda I ● Zdobył 3 sprawności \*\*/\*\*\* z kategorii Obozownictwo i przyroda. ● Potrafi rozpisać cykl 4 zbiórek, którego efektem jest zdobycie umiejętności na wybraną sprawność. ● Potrafi zaplanować i przeprowadzić grę na nauczenie i sprawdzenie wybranej umiejętności. ], image("krazki/awangarda2.png", width: 3.5cm), [ == Awangarda II (komenda kursu) ● Potrafi zaplanować cykl zbiórka ZZ + zbiórka drużyny sprawdzająca umiejętności zastępów z wybranej techniki i umożliwi zdobywanie sprawności na wszystkich poziomach (\*, \*\*, \*\*\*) ● Potrafi przygotować i przeprowadzić grę, która wyłoni naj-lepszy zastęp w wybranej technice ● Potrafi ocenić zbiórkę pod względem skuteczności i <NAME> oraz dać pomysł na ulepszenie planu. Np.: Zakradnij się na zbiórkę zastępu jednego z kursantów i zanotuj co harcerze robili na zbiórce. Potem przekaż uwagi zastępowemu. ], image("krazki/awangarda3.svg", width: 3.5cm), [ == Awangarda III (komendant kursu) ● Potrafi zorganizować kurs zastępowych. ] )
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap4/chap4.typ
typst
Other
== Scientific notation and metric prefixes #include "1_scientific_notation.typ" #include "2_arithmetic_with_scientific_notation.typ" #include "3_metric_notation.typ" #include "4_metric_prefix_conversions.typ" #include "5_hand_calculator_use.typ" #include "6_scientific_notation_in_spice.typ"
https://github.com/jedinym/sqc-text
https://raw.githubusercontent.com/jedinym/sqc-text/main/main.typ
typst
#import "@preview/unify:0.5.0": num, unit #import "@preview/big-todo:0.2.0": * #import "@preview/codly:0.2.1": * #set page(margin: 1.75in) #set par(leading: 0.55em, justify: true) #set text(font: "New Computer Modern") #show raw: set text(font: "Noto Sans Mono") #show heading: set block(above: 1.4em, below: 1em, ) #set heading(numbering: "1.1") #show figure: set block(breakable: true) #show: codly-init.with() #let icon(codepoint) = { box( height: 0.8em, baseline: 0.05em, image(codepoint) ) h(0.1em) } #codly( languages: ( python: (name: "Python", icon: icon("img/brand-python.svg"), color: rgb("#3380ff")) ), enable-numbers: true, ) #show "SQC": emph #show "SQCLib": emph #show "Kubernetes": emph #show "RabbitMQ": emph #show "MinIO": emph #show "MetaCentrum": emph #align(center)[ #text(size: 15pt)[ Masaryk University #linebreak() Faculty of Informatics #linebreak() // color logo #image("img/fi-mu-logo-color.png", width: 40%) #linebreak() #linebreak() #linebreak() *Bachelor's Thesis* #linebreak() #text(size: 17pt, font: "Noto Sans", hyphenate: false)[ #set par(justify: false) *Replication of PDB validation server functionality in the _MetaCentrum_ environment* ] #linebreak() <NAME> Spring 2024 ] ] #pagebreak() #heading(numbering: none, outlined: false)[ Declaration ] Hereby, I declare that this thesis is my original authorial work, which I have worked out on my own. All sources, references, and literature used or excerpted during the elaboration of this work are properly cited and listed in complete reference to the due source. During the preparation of this thesis, I used the following AI tools: - Grammarly for checking grammar, - ChatGPT to improve my writing style. I declare that I used these tools in accordance with the principles of academic integrity. I checked the content and take full responsibility for it. #align(right)[ <NAME> ] #align(bottom)[ *Advisor:* Mgr. <NAME>, Ph.D. ] #pagebreak() #align(bottom)[ #heading(numbering: none, outlined: false)[ Acknowledgements ] I would like to thank my advisor, Vladimír for his huge support and time investment. I also thank my dearest friends for showing me what's possible. Lastly, I must thank my family for making sure I don't starve. Computational resources were provided by the e-INFRA CZ project (ID:90254), supported by the Ministry of Education, Youth and Sports of the Czech Republic. ] #pagebreak() #heading(numbering: none, outlined: false)[ Abstract ] Assessing the quality of biomacromolecular structural models (models of proteins, nucleic acids, and polysaccharides) acquired using experimental methods is a vital step in making inferences in structural biology. That is also why the validation of structures is an obligatory step in the Protein Data Bank's (PDB) deposition process. To allow structural biologists to refine their structures, the PDB provides a standalone validation service. However, the throughput of this service is too low for research projects that need to validate millions of structures. In this thesis, we implement Structure Quality Control (SQC), a scalable, containerized, and easily deployable service, that incorporates community-made validation tools. The implemented tool allows for easy-to-use structure validations via both a Python and a shell API. Deployed in the MetaCentrum virtual organization, the service is now ready for use in research. // Kontrola kvality biomakromolekulárnych štruktúr (modely bielkovín, nukleových kyselín a polysacharidov) získaných použitím experimentálnych metód je dôležitým krokom pri vyvodzovaní záverov v štrukturálnej biológii. Je to tiež jedným z dôvodov prečo validácia štruktúr je nutnou súčasťou depozičného procesu _Protein Data Bank_ (PDB). PDB poskytuje aj validačnú službu, ktorá je využívaná na iteratívnu kontrolu štruktúr. Priepustnosť tejto služby je však príliš nízka na využitie v niektorých projektoch. V tejto práci implementujeme _Structure Quality Control_ (SQC), škáľovateľnú, kontajnerizovanú a jednoducho nasaditeľnú službu, ktorá používa validačné nástroje vyvinuté komunitou štrukturálnych biológov. Implementovaný nástroj sprístupňuje validácie štruktúr pomocou Python rozhrania alebo rozhrania systémovej príkazovej riadky. Finálne riešenie je nasadené pomocou virtuálnej organizácie MetaCentrum a je pripravené na použitie vo výskume. #align(bottom)[ #heading(numbering: none, outlined: false)[ Keywords ] Protein Data Bank, PDB, biomacromolecules, MolProbity, proteins, nucleic acids, _Kubernetes_, bioinformatics, validation, _MetaCentrum_ ] #pagebreak() #outline(indent: auto) #pagebreak() #set page(numbering: "1") #counter(page).update(1) #heading(numbering: none)[ Introduction ] Understanding the structure of biomacromolecules is fundamental to structural biology research. The data acquired using experimental methods are used to assemble structures, i.e., computer models of large biomolecules. These models are crucial in understanding the molecular basis of biological processes, leading to advances in drug discovery or disease treatment. Because of the experimental nature of the methods used, these structural models can contain a wide range of errors. Therefore, validating biomacromolecular structural data is a critical step in ensuring their accuracy and reliability in biological research. This reality is reflected by the fact that every structure deposited into the _Protein Data Bank_ (the single global archive of three-dimensional structural models @pdb) is validated using community-developed tools @pdb-validation[p. 1917]. Based on the results of these tools, the validation pipeline generates a report @pdb-validation that can be used by structure authors for further refining of the coordinate models, as well as by users when searching for the best structure possible for their research. However, the throughput of the validation pipeline provided by the _Protein Data Bank_ is too low for use in some research projects (e.g., iterative validation of continuously optimized structures or batch validation of up to hundreds of millions of simpler structures predicted using neural networks @alphafoldDB). As a solution, a new service will be implemented that incorporates the tools used by the Protein Data Bank validation pipeline. Additionally, the service will include a queueing system, enabling batch validations of large numbers of structures. The service will utilize the computing resources of the _MetaCentrum_ virtual organization. #pagebreak() = Biomacromolecules The IUPAC #footnote[International Union of Pure and Applied Chemistry] defines a biopolymer or a biomacromolecule as a macromolecule #footnote[Large molecules consisting of many repeating subunits (monomers).] produced by living organisms @iupac-glossary. These include proteins, nucleic acids, and polysaccharides @iupac-glossary. In this section, we briefly introduce these three basic biomacromolecules. == Proteins Proteins are chains of amino acids with a molecular mass of around 10,000 or more @iupac-glossary-95[p. 1361]. They comprise one or more chains of amino acids #footnote[There are over 500 different amino acids, but only 22 are incorporated into proteins @amino-acids.] linked by peptide bonds $dash.en$ covalent bonds from the carbonyl carbon of one amino acid to the nitrogen atom of another with loss of water @iupac-glossary-95[p. 1356]. An example of such a reaction can be seen in @figure-peptide-bond. #figure( image("img/AminoacidCondensation.svg"), caption: "The dehydration condensation of two amino acids to form a peptide bond (in red). Sourced from Wikimedia Commons." ) <figure-peptide-bond> Proteins perform a vast array of functions in organisms: catalyzing reactions, providing structure to cells, replicating DNA, transporting molecules, and more @mol-cell-bio[p. 59]. The sequence of amino acids determines the protein's three-dimensional structure, which then dictates its function @mol-cell-bio[p. 60]. == Nucleic acids Nucleic acids are polymers comprised of monomers (subunits) known as nucleotides @mol-cell-bio[p. 40]. They are categorized into two classes: deoxyribonucleic acid (DNA) and ribonucleic acid (RNA) @mol-cell-bio[p. 102]. All nucleotides have a common structure: a phosphate group linked to a pentose, #footnote[A five-carbon sugar.] which in turn is linked to a _base_. The common bases include _adenine_, _guanine_, and _cytosine_. _Thymine_ is exclusively found in DNA, while _uracil_ is exclusive to RNA molecules. The pentose is deoxyribose in DNA and ribose in RNA. #figure( image("img/DAMP_chemical_structure.svg", width: 80%), caption: "Deoxyadenosine monophosphate, a nucleotide present in DNA. The phosphate group (blue) is linked to deoxyribose (black), which is in turn linked to an adenine base (red). Original image sourced from Wikimedia Commons and edited.", ) DNA molecules contain the information that dictates the sequences and, consequently, the structures of all proteins within a cell @mol-cell-bio[p. 101]. During protein synthesis, DNA is transcribed into ribonucleic acid (RNA), which is then translated into a protein @mol-cell-bio[p. 101]. == Polysacharides Monosaccharides, or simple sugars, are the monomer units of polysaccharides @iupac-glossary-95[p. 1360]. Polysaccharides are formed by linking monosaccharides together through glycosidic linkages. Some serve a storage function in a cell, preserving sugars for later use (e.g., starch in plants, glycogen in animals). Others function as building material for structures of cells @biology[p. 71]. #pagebreak() = Macromolecular structural data Macromolecules can be represented in computers in one, two or three dimensions @chemo-informatics. In this section, we first introduce these representations, and then take a closer look at the three-dimensional representations as they are the most relevant to this thesis. == One-dimensional structure The simplest way of representing a molecule is by indicating the total number of atoms present (using a molecular formula). To illustrate, the molecular formula of _glucose_ is written as $C_6 H_12 O_6$, that is, six carbon atoms, twelve hydrogen atoms, and six oxygen atoms. However, this representation lacks information about the relative positions of atoms and bonds, making it unable to differentiate molecules with identical total atom counts. For instance, molecules such as _fructose_ and _galactose_ share the same formula as _glucose_ despite having different structures. Therefore, the one-dimensional representation has limited usage for polymers containing thousands of atoms. == Two-dimensional structure A common way to represent structures in a two-dimensional manner is to use a _molecular graph_ @chemo-informatics[p. 2]. A graph is a pair $G = (V, E)$, where $V$ is a set of _vertices_, and $E$ is a set of pairs $E = {(v_1, v_2) | v_1,v_2 in V}$, elements called _edges_. Using a graph, it is possible to capture the topology of a molecule. In a molecular graph, vertices represent atoms, and edges represent bonds between them @chemo-informatics[p.2]. Both vertices and edges can hold additional information, such as bond orders for edges or atomic numbers for vertices @chemo-informatics[p.2]. These molecular graphs can be encoded using various formats @chemical-formats, with _line notation_ one of the simpler methods. A line notation represents a structure as a linear string of characters, making them relatively simple to read and understand. One commonly used notation is SMILES #footnote[Simplified Molecular Input Line Entry Specification] @smiles. Specifically, the OpenSMILES standard is widely adopted and open-source @open-smiles. SMILES enables the representation of molecular graphs using ASCII strings with only a few rules. It works by doing a depth-first traversal of the graph and printing appropriate symbols for vertices (atoms) and edges (bonds). Initially, the graph is edited to remove hydrogen atoms and break cycles to create a spanning tree (i.e. a subgraph that is a tree #footnote[A graph in which any two vertices are connected by exactly one edge.] and contains all the original vertices) @smiles-algorithm. @smiles-table illustrates a few examples of the SMILES format. #figure( table( columns: (auto, auto, auto), align: center + horizon, table.header([*Molecule*], [*Chemical formula*], [*SMILES string*]), "Methane", $C H_4$, raw("C"), "Dinitrogen", $N≡N$, raw("N#N"), "Adenine", image("img/Adenine.svg", width: 60pt), raw("Nc1c2ncNc2ncn1"), "Glucose", image("img/Beta-D-Glucose.svg", width: 100pt), raw("OC[C@@H](O1)[C@@H](O)[C@H](O)[C@@H](O)[C@H](O)1"), "Nicotine", image("img/nicotine.svg", width: 60pt), raw("CN1CCC[C@H]1c2cccnc2"), ), caption: "Examples of SMILES representations of chemical molecules." ) <smiles-table> == Three-dimensional structure Three-dimensional structures are represented in computer-readable form (and human-readable to some extent) using a chemical file format. These exist in the form of text files, which describe the locations of atoms in three-dimensional space. Metadata about the represented structure may also be included. In this section, the two formats relevant to this thesis are introduced. === PDB format The Protein Data Bank format is the original format used by the Protein Data Bank. It was originally developed in 1976 as a simple human-readable format @pdb-history. Each line of the file contains a _record_ - information about some aspect of the structure. The records can contain metadata (e.g., `AUTHOR`, `HEADER` or `TITLE`) or data about the molecule's chemical structure (e.g. `SEQRES` or `ATOM`). Additionally, the `REMARK` record type has been used to extend the format to support new details about the experimental methods used to obtain the macromolecular data @pdb-format-guides. Unfortunately, the lines of the file are fixed-width as the format is based on the original 80-column punched card @pdb-history. Because of this, limitations exist on the stored structure: - Maximum $num("100000")$ atoms in structure - Maximum $num("10000")$ residues in one chain - Maximum $num("62")$ chains in structure One way to address these limitations is by dividing the structure into multiple files. However, doing so may complicate tasks such as visualization or certain structure validations. As a result, this makes the format less suitable for handling very large structures. Some attempts have been made to improve these limitations over the years (e.g., the hybrid-36 counting system for atom and residue numbers @hybrid-36), but none of them have been particularly prevalent, as it would be difficult to adapt existing tools. The PDB format has been deprecated by the _Protein Data Bank_ in favor of the PDBx/mmCIF format in 2014 @pdb-formats. However, the PDB still offers structures in the PDB format; these are only best-effort conversions of the PDBx/mmCIF format. === PDBx/mmCIF Format The PDBx/mmCIF format was developed to address the limitations inherent in the legacy PDB format @mmcif[p. 571]. With ever-increasing sizes of structures, it became clear that change was needed @mmcif-ecosystem[p. 3]. The format is based on the Crystallographic Information Framework (CIF), which was adopted by the International Union of Crystallography (IUCr) in 1990. CIF operates under the idea that all values within an ASCII text file are assigned dictionary labels (keys). This concept was enabled using a Dictionary Definition Language (DDL), which is a versatile language allowing for the description of dictionary data structures, controlled vocabularies, boundary conditions, and relationships between values @mmcif-ecosystem[p. 2]. Later, in 1997, the mmCIF dictionary was approved by the international Committee for the Maintenance of the CIF Standard (COMCIFS) @mmcif-approval. It featured expanded data types, which included support for protein and nucleic acid polymer types, polymer chains, ligands, binding sites, macromolecular assemblies, amino acid and nucleotide residues, atomic coordinates, and experimental data @mmcif-ecosystem[p. 3]. While mmCIF already supported most of the structural and crystallographic concepts present in the PDB format, additional key categories prefixed with `pdbx_` were introduced to the dictionary, and some existing categories have been extended. This expansion aimed to guarantee complete compatibility and semantic equivalence with the PDB format @crystallographic-data[p. 195]. In 2014, the PDBx/mmCIF format became the primary format of the PDB @mmcif-ecosystem[p. 3]. #pagebreak() = Tools and methods In this section, we introduce the tools employed in the implementation. First, we discuss the _Protein Data Bank_ and its validation pipeline. Next, we examine MolProbity, a validation tool used in the implementation. Finally, we explore the components of the new system. == Protein Data Bank <section-pdb> The Protein Data Bank (PDB) is the single global archive of three-dimensional macromolecular structures. Established in 1971, its purpose is to serve as a central repository for macromolecular data, ensuring their accessibility to all @pdb-history. Since 2003, it is managed by the wwPDB consortium @wwpdb, consisting of: - Research Collaboratory for Structural Bioinformatics (RCSB) @pdb[p. D520] - Macromolecular Structure Database (MSD) at the European Bioinformatics Institute (EBI) @pdb[p. D520] - Protein Data Bank Japan (PDBj) at the Institute for Protein Research in Osaka University @pdb[p. D520] - Electron Microscopy Data Bank (EMDB) @emdb Currently (May 2024), it stores over two hundred and nineteen thousand structures @pdb-entry-stats. Eighty-four percent of this data was obtained using X-ray crystallography, nine percent using electron microscopy, and around six percent by nuclear magnetic resonance @pdb-stats-summary. As the number of large and complex structures in the PDB continued to grow, the existing deposition and validation infrastructure proved inadequate. That is why the wwPDB initiated the development of OneDep, a novel system designed for deposition, biocuration, and validation @onedep[p. 536]. During deposition, the deposited structure is validated using community-made tools in OneDep's _validation pipeline_ @onedep[p. 539]. Additionally, a standalone server #footnote[https://validate.wwpdb.org] is accessible to depositors, providing them with a platform for refining the structure. === OneDep validation pipeline To implement the relevant validation tools, the wwPDB convened so-called Validation Task Forces (VTFs) for each experimental method, which compiled recommendations for the validation pipeline @pdb-validation[p. 1917]. Based on these recommendations, the pipeline was integrated with the OneDep system @pdb-validation[p. 1917]. The VTFs recommended that deposited structures undergo validation against criteria falling into three categories. The first category encompasses criteria for validating the resulting atomic model, i.e., is only the three-dimensional computer representation. The second category involves analysis of the supplied experimental data. Lastly, the third category examines the fit between the supplied experimental data and the atomic model @pdb-validation[p. 1917]. The outcome of the validation pipeline is a validation report, which incorporates the parsed outputs of the validation tools employed on the structure. This report is presented in both a human-readable PDF format and a machine-readable XML format, complemented by an XSD schema #footnote[https://www.wwpdb.org/validation/schema/] @pdb-validation[p. 1917]. The pipeline is composed of component software tools that validate certain aspects of the supplied data @pdb-validation[p. 1922]. Some of these tools are publicly available, but access to some was only provided to the wwPDB. One of the publicly available tools that was used in the implementation of this thesis is MolProbity @molprobity, which we will explore further in @section-molprobity. There are three ways to access the validation pipeline: via an anonymous web user interface, as part of the deposition and biocuration process, and through a web API @pdb-validation[p. 1921]. The web API is most convenient for validating large numbers of structures, as it can be fully automated. It offers both a CLI #footnote[Command Line Interface] application and a small Python library. == MolProbity <section-molprobity> MolProbity is the single validation tool used in this thesis. It provides evaluation of atomic model quality for biomacromolecules @molprobity[p. 12]. The current maintainers are the Richardson Laboratory of Duke University. Its source code can be found in their GitHub repository #footnote[https://github.com/rlabduke/MolProbity]. The repository also contains a short guide on how to install MolProbity, however, the guide and installation scripts are rather outdated and require some refactoring for use on a modern system. MolProbity was chosen because, unlike other tools in the PDB validation pipeline, it is freely available and provides multiple validations in a single package. The main focus of the validations is the geometry of the structure. Validations such as too-close contacts, bond lenghts and angles and torsion angles. The software package contains a web interface for simple use but also a command line interface for bulk validations, which is more useful for automated use. // === Validations // In this section, we briefly introduce the various validations that MolProbity // performs on atomic models. // // ==== All-atom contact analysis <section-clashes> // This validation option checks for overlaps of van der Waals surfaces of // nonbonded atoms. Overlaps over $0.4 angstrom$ #footnote[$1 angstrom = 0.1 // unit("nano meter")$] are reported as _clashes_ @molprobity[p. 14]. // // ==== Covalent-geometry analyses // MolProbity additionally assesses outliers in bond lengths #footnote[The // average distance between nuclei of two bonded atoms.] and bond angles // #footnote[The geometric angle between two adjacent bonds.] of backbones // #footnote[The main chain of the polymer.] @molprobity[p. 15]. // // Based on ideal parameters derived ahead of time @molprobity[p. 15] // @struct-quality-data @backbone-conformation, the instances where the bond // lengths or bond angles deviate from the ideal value by at least four standard // deviations are identified and listed as bond length and angle outliers, // respectively @molprobity[p. 15]. // // ==== Ramachandran and rotamer analyses // #todo[Not really understanding these right now.] === Interface Multiple command-line programs can be used to run _MolProbity's_ validation suite on structures. They can be found in the `/cmdline` directory in the source tree. The two programs used in the implementation of this thesis are _residue-analysis_ and _clashscore_. Firstly, _residue-analysis_ runs all available validations and outputs outliers in each residue in the CSV #footnote[Comma Separated Values] format. Secondly, the _clashscore_ program checks for too-close contacts and outputs detected clashes in a one-clash-per-line format. == _Kubernetes_ Kubernetes is an open-source platform designed to automate the deployment, scaling, and operation of containerized applications. It organizes these applications into clusters, which are sets of nodes (machines) that run containerized applications. A Kubernetes cluster typically includes a control plane, which manages the overall state and lifecycle of the applications, and worker nodes, which run the containers. Central to Kubernetes is its API, which serves as the primary interface for interaction with the cluster. Users and automated systems communicate with the API to deploy, manage, and monitor applications. The API accepts requests in a declarative manner, meaning users specify the desired state of the system, and Kubernetes takes the necessary actions to achieve and maintain that state. Kubernetes objects are persistent entities within the system that represent the state and configuration of various cluster components. Key objects for this thesis include: + *Pods*: The smallest deployable unit that can be created, managed, and run. It encapsulates one or more containers that share the same network namespace and storage. Pods are designed to host a single instance of a running process in a cluster, making them the basic building blocks of a Kubernetes application. + *Replicas*: Refer to multiple instances of a Pod running concurrently to ensure high availability and reliability. Kubernetes uses ReplicaSet objects, often defined within Deployments, to manage the desired number of replicas. This ensures that the specified number of pod replicas are always running, allowing for automatic scaling, self-healing, and load balancing across the cluster. + *Deployments*: Manage the deployment and scaling of application replicas. They ensure that the desired number of pod replicas are running and can update pods in a controlled manner. + *Persistent Volume Claims (PVCs)*: Abstract the storage resources that a pod can use. A PVC requests storage resources from the cluster, which are then provisioned by Persistent Volumes (PVs). + *Ingresses*: Manage external access to the services in a cluster, typically HTTP. An Ingress controller watches the Ingress resources and manages the routing of external traffic to the appropriate services. + *Services*: Define a logical set of pods and a policy by which to access them. Services enable communication within the cluster and provide stable IP addresses and DNS names for pods, meaning pods can communicate easily. + *Secrets*: Store sensitive information such as passwords, tokens, and keys. Secrets allow sensitive data to be used in pods without exposing it directly in pod specifications. These objects are defined in YAML #footnote[YAML Ain't Markup Language] or JSON #footnote[JavaScript Object Notation] format and submitted to the Kubernetes API, which manages their lifecycle. == Ansible _Ansible_ is an open-source automation tool widely used for IT orchestration, configuration management, and application deployment @ansible. It operates through playbooks, which are scripts written in the YAML format that define a series of tasks to be executed on managed nodes. Each task specifies an action, such as installing software or configuring network settings, and is applied to hosts listed in an inventory. Inventories categorize hosts into groups, allowing for targeted management and execution of tasks across different subsets of infrastructure. A fundamental aspect of _Ansible_ is its focus on idempotency. This ensures that tasks, when executed, bring the system to a desired state without causing additional changes if the system is already in that state. This property is crucial for maintaining consistency and preventing unintended side effects during repeated executions. _Ansible_ also supports the integration of custom modules to extend its capabilities. These custom modules allow for the automation of specialized tasks. In this thesis, we utilize the `kubernetes.core.k8s` module #footnote[https://docs.ansible.com/ansible/latest/collections/kubernetes/core/k8s_module.html], for deployment automation. == _MetaCentrum_ The MetaCentrum virtual organization provides computing resources to all students and employees of academic institutions in the Czech Republic @metacentrum. Membership is free, with the requirement that members acknowledge MetaCentrum in their publications. It offers many different platforms for computation across the Czech Republic, but crucially for this thesis, it also offers a Kubernetes cluster @metacentrum-k8s via a _Rancher_ #footnote[https://www.rancher.com/] instance. == _RabbitMQ_ <section-rabbitmq> RabbitMQ is a messaging and streaming broker that supports several standard messaging protocols @rabbitmq. It is used as a mediator between producers and consumers of messages. Publishers (producers) publish a message to an exchange. The message is then routed to a queue. If the queue has any active consumers, the message is delivered to them. If no consumers are active, the message is cached on disk and delivered at the next opportunity. == _MinIO_ Object Store <section-minio> // TODO: Why MinIO and not a traditional database? // To store atomic structures and validation reports, a storage solution is required. MinIO is an object store inspired by and compatible with Amazon's S3 service #footnote[https://aws.amazon.com/s3/] @minio. MinIO is simple to deploy, as it's intended for use in the cloud, including using Kubernetes. MinIO offers high-performance storage of data by storing them as objects in _buckets_. A bucket is simply a container for objects, where each object has a key that uniquely identifies it in a _bucket_. Each object can also contain additional text metadata. Access to MinIO is mediated via an HTTP API designed initially for Amazon's S3 service. However, MinIO also offers software development kits (SDKs) for multiple programming languages, including Python. Another part of the MinIO deployment is the managment server $dash.en$ a web application used for configuration and management. Crucially, for this thesis, MinIO can monitor events associated with a _bucket_ and publish notifications via multiple protocols #footnote[https://min.io/docs/minio/kubernetes/upstream/administration/monitoring.html]. One of the supported protocols is _AMQP 0-9-1_, which is the protocol used by RabbitMQ. A few examples of such events are: - `s3:ObjectCreated:Put` which occurs when a new object is added to a bucket. - `s3:ObjectRemoved:Delete` which occurs when an object is deleted from a bucket. - `s3:ObjectCreated:CompleteMultipartUpload` which occurs when an object larger than 5MiB is added to a bucket. // == Miscellaneous // In this section, we introduce the tools and libraries that are not the core of // the solution. // #pagebreak() = Implementation The result of this thesis is a validation service called _Structure Quality Control_ (SQC) alongside a corresponding Python library, SQCLib. The source code is available in the _sb-ncbr_ (Structural bioinformatics research group at National Centre for Biomolecular Research) organization on GitHub for both SQC #footnote[https://github.com/sb-ncbr/sqc] and SQCLib #footnote[https://github.com/sb-ncbr/sqclib]. This section begins with an introduction to _SQC's_ high-level architecture and design decisions, followed by a closer examination of the implementation. == Requirements In this section, we outline the functional and non-functional requirements of the SQC system. === Functional requirements + The service must support running validations on atomic models. + The service must support both the legacy PDB and PDBx/mmCIF formats as inputs. + The service must provide a machine-readable output containing results of validations. + The service must provide a schema for the output. + The service must support many concurrent validations using a queueing system. + The service must be easily deployable to the MetaCentrum Kubernetes cluster. + The service must be easily scalable to accommodate higher loads. + The service must provide a web-accessible API. + The service must provide a Python library for accessing the API. === Non-functional requirements + The service must be implemented using the Python programming language. + The service must be containerized using Docker. + The service must be deployed to the MetaCentrum Kubernetes cluster. + The service must use Ansible to automate deployment to the MetaCentrum cluster. == Architecture Since supporting many concurrent validations is crucial, we needed to devise a solution that could handle them effectively. To guarantee that even during high load, the system can accept new validation requests, we use a Producer Consumer system design pattern. === Producer Consumer pattern In the Producer Consumer system design pattern, producers generate data or events and put them in a shared queue. Consumers then retrieve the data or events from the queue and process them (@figure-producer-consumer). The main benefit of using the pattern is the decoupling of producers and consumers. While a consumer is occupied processing prior data or events, producers can continue adding more data to the queue. This additional data awaits consumption and processing once at least one consumer completes all its tasks. Adding data to the queue is faster than processing, ensuring producers encounter no delays due to consumers. During periods of increased load, when the queue accumulates more data and consumers are slow in processing it; new consumers accessing the shared queue can be created. #figure( caption: "Diagram of the Producer Consumer pattern. Producers produce new data in parallel and consumers consume and process data in parallel.", image("img/producer_consumer.svg"), ) <figure-producer-consumer> === Producer Consumer pattern in SQC To implement the Producer Consumer pattern in SQC, we utilize RabbitMQ (@section-rabbitmq) and MinIO (@section-minio). When a user submits a validation request through SQCLib (refer to @section-sqclib), the library code creates a new object in a MinIO bucket. This object contains the atomic model along with associated metadata. The library subsequently returns the ID of the pending request to the user. The user uses this ID to invoke another SQCLib function, which awaits the completion of the request. Upon the creation of the object, MinIO publishes a bucket notification event to the `requests` exchange in RabbitMQ. This notification contains the identifier of the new request. The SQC server listens to the `requests` exchange. Upon receiving a notification from MinIO, it downloads the associated atomic model of the request to temporary storage and runs validations on it. Once the atomic model is validated, SQC uploads the results to another MinIO bucket. When the result is submitted, the library returns the results of the validation to the user. In our scenario, users submitting validation requests act as producers, _RabbitMQ's_ exchange acts as a shared queue, and the SQC server acts as a consumer. During periods of high load, additional instances of the SQC server can be created, accessing the same shared queue. This approach boosts the system's throughput. A sequence diagram showing a user's interaction with the system when validating a single structure can be seen in @figure-sequence. #figure( caption: "UML Sequence Diagram of an SQC validation request.", image("img/sequence.png"), ) <figure-sequence> == Validation service In this section, we introduce the validation service and its key components. First, we discuss the service's source code. Next, we examine containerization. Then, we explore how the MolProbity suite is utilized. Finally, we inspect the service's output format. === Source code overview In this section, we explore _SQC's_ source code repository and provide an overview of its elements. The `ansible/` directory contains _Ansible_ playbooks and inventories, used to deploy SQC to MetaCentrum. @section-automation goes further into the deployment setup. The `compose.yaml` file contains the configuration file for _Docker Compose_ #footnote[https://docs.docker.com/compose/]. Using it, developers can start a local instance of SQC for simpler development and testing. _Docker Compose_ starts the RabbitMQ, MinIO, and SQC containers, and exposes the default MinIO port `9000`. The local instance can then be accessed for testing using the SQCLib library. The `Dockerfile` contains instructions for _Docker_ to build _SQC's_ image. See more in @section-containerization. The `pyproject.toml` contains definitions pertaining to the SQC Python project. It defines the required Python version to run the project and the project's production and development dependencies. To manage dependencies, we utilize _PDM_ #footnote[https://pdm-project.org/en/latest/], a modern python dependency manager. _PDM_ simplifies various development tasks, including dependency resolution and updates, virtual environment support, and management of user scripts. The `pdm.lock` file is created by _PDM_ and contains exact versions of packages required to run SQC. The advantage of using a lockfile is that during the Docker image-building process, dependencies are not resolved again, but extracted from the lockfile, which guarantees the reproducibility of all builds. The `sqc/` directory contains the source code of the SQC validation service. === Containerization <section-containerization> With each validation tool potentially having its own dependencies, a key challenge in implementing the validation service is ensuring its simple setup. We chose to simplify the setup by employing containerization, specifically Docker. Containerizing the validation service offers additional advantages, including straightforward deployment, isolation from the host system, and consistent results, as all the dependencies of the tools (both software dependencies and reference data) can be controlled. The _Dockerfile_ utilizes a multi-stage build. The first stage installs the necessary packages, fetches _MolProbity's_ reference data and source code from GitHub and builds _MolProbity's_ binaries. In the second stage, SQC's dependencies are installed. This method was selected to reduce the Docker image's build time. Building MolProbity can be time-consuming, taking up to an hour on a recent laptop. Docker can cache unchanged parts of the image between builds, improving build times. Since _MolProbity's_ results are dependent on reference data, the repositories containing it were forked into the _sb-ncbr_ organization on GitHub. These are then cloned during the image build. == Authentication In order to restrict access to the service, we utilize MinIO's built-in authentication mechanism. To access resources in a MinIO bucket, the user must provide an access key and a secret key. These two values are generated by the administrator using the MinIO management service and then provided to a new user. === Running validations The core of the validation service is utilizing the MolProbity suite to validate atomic models and parsing its outputs into a validation report. The SQC server listens for messages in the `requests` exchange in RabbitMQ. When a request arrives, the respective atomic model is fetched from MinIO and stored in the `/tmp` directory. Since MolProbity exclusively supports validating models stored in the legacy PDB format, it's necessary to initially convert the PDBx/mmCIF atomic models to this legacy format. This is done using the _Gemmi_ #footnote[https://gemmi.readthedocs.io/en/latest/] library for structural biology. _Gemmi_ has multiple features useful in macromolecular biology but supports format conversions using the `gemmi convert` subprogram. After the structure is fetched from MinIO, _Gemmi_ converts it to the legacy format. Another constraint of MolProbity is that it can only operate on PDB files containing only a single model. It is possible for PDB files to contain an ensemble of models, something that is typical for structures determined by nuclear magnetic resonance. We utilize the _BioPython_ #footnote[https://biopython.org/] library to split the original PDB file into multiple single-model files. Once the files are prepared, MolProbity's programs are executed on each one. The results of the validations are then returned on a per-model basis. After the input files are preprocessed, _MolProbity's_ _residue-analysis_ program is executed with the path to the structure as the first argument. The process is started and managed using the built-in _subprocess_ library. The output of the process is captured and then parsed using the _csv_ built-in library into the format of the validation report. The second program to be executed is _clashscore_. The output of _clashscore_ is not in the CSV format and therefore requires quite intricate parsing. The output is parsed into the validation report as well. Before converting the validation report to JSON and sending it to MinIO, we add the versions of the reference data used for validation of the model. These versions are represented as URLs of the git repositories and commit hashes of the latest commits. === Validation reports We decided to use the JSON format for the validation reports, as it's a simple human-readable format that is often used in the industry. To ensure that the reports are convenient to use, we utilize _JSON Schema_ #footnote[https://json-schema.org/], a vocabulary used to annotate JSON documents. By providing a _JSON Schema_, we allow users to easily parse the validation reports. To facilitate the generation of _JSON Schema_, we use the _Pydantic_ #footnote[https://docs.pydantic.dev/latest/] Python library. _Pydantic_ is primarily used for validation of external data, but can also be used to emit _JSON Schema_. With _Pydantic_ a _model_ of the output is created as a Python object. From this model, it is possible to generate a _JSON Schema_. Once populated with results from MolProbity, the model is converted into JSON and returned to the user in that format. This approach offers the advantage that as the model expands in the future, the schema is automatically adjusted accordingly. @figure-pydantic shows an example Python object with its associated _JSON Schema_. #show figure: set block(breakable: true) #figure( grid( rows: 2, gutter: 2em, ```python import pydantic class SubObject(pydantic.BaseModel): integer: int opt_string: str | None class ExampleObject(pydantic.BaseModel): fields: list[str] sub: SubObject ```, ```JSON { "$defs": { "SubObject": { "properties": { "integer": { "title": "Integer", "type": "integer" }, "opt_string": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "title": "Opt String" } }, "required": [ "integer", "opt_string" ], "title": "SubObject", "type": "object" } }, "properties": { "fields": { "items": { "type": "string" }, "title": "Fields", "type": "array" }, "sub": { "$ref": "#/$defs/SubObject" } }, "required": [ "fields", "sub" ], "title": "ExampleObject", "type": "object" } ```, ), caption: figure.caption(position: bottom)[An example of a small Pydantic model and its generated JSON Schema. The schema describes the types of every field of the model.] ) <figure-pydantic> #show figure: set block(breakable: false) == Validation client library <section-sqclib> In order to send a validation request to the SQC server, it is necessary to use the SQCLib Python package. This package includes a library API for use in Python code and a small command-line application for uploading structures from the system shell. The library is easily installable and distributed as a Python package. The implementation wraps the Python API provided by MinIO #footnote[https://min.io/docs/minio/linux/developers/python/API.html], while providing a few additional validations. === Python API The main part of the library consists of a simple Python API. Users utilize the `SQCClient` object to interact with SQC instances. To create the object, users must pass their credentials to the client, which will then use them to communicate with SQC. Optionally, the users can specify a different URL of the SQC server, which can be useful when running SQC locally or having a separately deployed instance. The client offers the following methods: + The `submit(path)` method submits a structure to an SQC instance and returns an ID of the pending request. The structure is specified via a filesystem path. This method can be useful when validating a lot of structures, as they can be all uploaded first and all awaited later. + The `get_result(request_id, timeout_s)` method is used in combination with the `submit(path)` method. It takes an ID of a pending request as an argument and blocks until the SQC server returns a validation report. + The `validate(path, timeout_s)` is a combination of the `submit` and `get_result` methods. It submits a request to the SQC server and blocks until a report is returned. This method offers the simplest API and is useful when validating a single structure. An example script utilizing the Python API can be seen in @figure-sqclib-python. #figure( ```python from os import environ from sqclib import SQCClient client = SQCClient( access_key=environ.get("SQC_ACCESS_KEY"), secret_key=environ.get("SQC_SECRET_KEY"), ) requests = [] for path in ["183d.pdb", "2pde.mmcif"]: request_id = client.submit(path) requests.append((path, request_id)) reports = [] for path, request_id in requests: report = client.get_result(request_id) reports.append((path, report)) ```, caption: "An example Python script showing SQCLib usage. Once the client is initialized, two structures are submitted to the SQC instance and their reports awaited." ) <figure-sqclib-python> === Shell API The library also contains the program `sqc` that can be used to submit structures for validation directly from the system shell. To use SQC, the `SQC_ACCESS_KEY` and `SQC_SECRET_KEY` environment variables must be set with before-provided credentials. @figure-sqclib-shell shows how to upload a structure to the main instance of SQC in the _bash_ shell. #figure( ```sh export SQC_ACCESS_KEY=access export SQC_SECRET_KEY=secret sqc structure.pdb sqc structure.mmcif ```, caption: "An example of submitting a structure for validation using the sqc program. Credentials must be provided by the SQC administrators." ) <figure-sqclib-shell> By default, the `sqc` program submits validations to the public SQC instance. To use a locally running instance of SQC, it is possible to use the `--url` and `--insecure` parameters. @figure-sqclib-local shows how to utilize these parameters. #figure( ```sh # "minioadmin" is the default key of the local instance export SQC_ACCESS_KEY=minioadmin export SQC_SECRET_KEY=minioadmin # following two calls are equivalent sqc --insecure --url localhost:9000 structure.mmcif sqc -k -u localhost:9000 structure.mmcif ```, caption: "An example of submitting a structure for validation to a local instance of SQC. The local instance uses default \"minioadmin\" credentials." ) <figure-sqclib-local> === Documentation Since the SQCLib library is the sole entry point to the SQC system, thorough documentation is essential. To generate documentation from the code, we use _Sphinx_, a documentation generator designed for Python that supports various output formats #footnote[https://www.sphinx-doc.org/en/master/]. To automatically generate documentation from Python docstrings, we use the _autodoc_ extension to _Sphinx_. _Autodoc_ parses Google-style docstrings #footnote[https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings] and generates a reference for a Python module. Furthermore, it is important that the documentation is easily accessible. For this end, we use _GitHub Pages_ #footnote[https://pages.github.com/], a system that allows free hosting of websites directly from a GitHub repository. To automate the process, we utilize _GitHub Actions_ #footnote[https://github.com/features/actions], a CI/CD solution from GitHub, that allows automation to run on GitHub repository events. When a new commit is added to the `main` branch in the SQCLib GitHub repository, the documentation is built and uploaded to _GitHub Pages_. This process guarantees that the accessible documentation is always up to date. The documentation is then available in the `sb-ncbr` subdomain of the github.io domain #footnote[https://sb-ncbr.github.io/sqclib/]. #pagebreak() = Deployment To deploy the main instance of SQC, we chose the Rancher Kubernetes distribution provided by MetaCentrum #footnote[https://rancher.cloud.e-infra.cz]. Since we had already decided to utilize containerization and needed simple scaling, Kubernetes was the obvious choice. In this section we first explore the array of objects used to deploy SQC to Kubernetes, and then we describe how the process of deployment is automated using _Ansible_. == _Kubernetes_ project setup To deploy SQC to a Kubernetes project, we take advantage of various Kubernetes objects. The credentials for the MinIO administrator account and RabbitMQ user are stored using a Secret. These secrets are then copied to an environment variable when creating respective Deployments. The MinIO object store requires storage for objects, so we create a Persistent Volume Claim (PVC) that is later mounted into a MinIO Deployment. This guarantees that the data stored by MinIO are persistent even across Pod restarts. Similarly, RabbitMQ requires some storage for buffering of messages in queues. Again, we create a PVC and later mount it into the RabbitMQ Deployment. To deploy MinIO, RabbitMQ, and SQC, we create three Deployments. The SQC Deployment is unique in the fact that the number replicas in the ReplicaSet is configurable. By specifying a higher number of replicas, the throughput of the service will be increased. Exposing MinIO, RabbitMQ, and SQC is achieved by utilizing a Kubernetes Service. Each of the three Deployments is exposed by a Service, allowing Pods to communicate over the network. Lastly, we create two Ingresses, exposing the main MinIO port and the MinIO management port. We utilize special annotations provided by MetaCentrum #footnote[https://docs.cerit.io/docs/kubectl-expose.html], which create a subdomain under the `dyn.cloud.e-infra.cz` domain and automatically enable TLS to use HTTPS. == Automation <section-automation> To automate the deployment of SQC, we use two _Ansible_ playbooks: `deploy-sqc.yaml`, which creates all Kubernetes objects required for a minimal setup of SQC and `teardown-sqc.yaml`, which deletes all objects pertaining to SQC. Both playbooks utilize an _Ansible_ vault, which contains secrets needed to deploy SQC, like the token to _MetaCentrum's_ Kubernetes API. When running the playbooks, a vault password is entered, which then decrypts the vault and makes the secrets available to _Ansible_ as inventory variables. The inventory only contains one host: `metacentrum`, because it is the only deployment target at the moment. However, new deployment targets can be easily added in the future. Another Kubernetes cluster can be added with minimal effort. The inventory for the host `metacentrum`, contains some important values for the deployment: + `k8s_sqc_namespace` specifies the Kubernetes project that SQC will be deployed to. + `k8s_sqc_replicas` specifies the base number of replicas of SQC pods. + `k8s_sqc_image` specifies the repository, name and tag of the SQC Docker image. + `k8s_sqc_request_cpu` and `k8s_sqc_request_mem` specify the requested memory for the SQC container. When deploying a new version of SQC, it is necessary to rebuild the image and push it to a docker repository, so Kubernetes can then pull it during the deployment. One important aspect of the deployment is fitting SQC's replicas, CPU and memory requests to the Kubernetes project quota. The default project quota in the MetaCentrum cluster is 20 CPUs request, 32 CPUs limit, 40GB memory requests, and 64GB memory limits. Adjusting the requested CPUs, memory, and the number of replicas is important to get the highest performance. If validating many small structures, it is faster to have more replicas with fewer requested CPUs. When validating larger structures, it might be more beneficial to have fewer replicas with more requested CPU and memory. @figure-resources shows the default configuration of resources. #[ #set par(justify: false) #figure( table( columns: (auto, auto, auto, auto, auto), align: center + horizon, table.header([*Deployment*], [*Replicas*], [*CPU Requests*], [*Memory Requests*], [*Memory Limits*]), "SQC", "20", "0.9", [$1.5$ GiB], [$3$ GiB], "RabbitMQ", "1", "1", [$512$ MiB], [$512$ MiB], "MinIO", "1", "1", [$512$ MiB], [$512$ MiB], ), caption: "Default resource requests and limits of the SQC Deployments." ) <figure-resources> ] #pagebreak() = Evaluation In this section, we address two aspects of the newly implemented solution. First, we examine SQC's scaling performance, and second, we review the validation results. == Scaling To test SQC's scaling capabilities, we validated thirty structures with an increasing number of replicas. We chose thirty structures because it is the highest number of replicas that can be provisioned in the Kubernetes project while fitting into quota memory limits. @figure-scaling shows that with the increasing number of replicas, the time spent on multiple structure validations drops rapidly. Scaling replicas further is possible; the limiting factor is the resource quota in the Kubernetes cluster. #figure( image("img/replica-perf.png"), caption: "Time spent on validating 30 183d structures (PDB id 183d) plotted against the number of SQC validation service replicas." ) <figure-scaling> == Validation results Certain validations performed by MolProbity (namely bond lengths, bond angles, and torsion angles) are heavily influenced by reference data. Unfortunately, the datasets used by PDB are not publicly available. After an email inquiry, PDB referred us to the MolProbity paper from 2017 @molprobity-more-data. According to this paper, MolProbity in the PDB pipeline should be using the data provided by the Richardson Laboratory at Duke University. However, even after using their datasets from GitHub, some validations produced slightly different results. Without access to the specific files used by PDB, it is difficult to determine the cause of these discrepancies. #pagebreak() = Conclusion In this thesis, we aimed to reimplement parts of the PDB validation pipeline to improve the throughput of structure validation and allow local deployment. We developed a solution that can be simply accessed using a Python library or a commandline program. According to performed tests, the implementation scales well with increasing computational resources. Additionally, the service defines an output schema, facilitating its use. The implementation leverages Kubernetes for deployment and scaling, and Ansible for deployment automation. Other cloud-native technologies were also used in the implementation, such as RabbitMQ and the MinIO object store. The final solution is ready for upcoming projects in the Structural bioinformatics research group at the National Centre for Biomolecular Research such as validations of hundreds of millions of predicted structures from _AlphaFoldDB_ @alphafoldDB or fast iterative validations during the process of structure optimization by means of computational chemistry. == Future plans Even though the implemented solution offers practical validation of structures, there are several ares that could be improved in the future. Notably, the service only utilizes one validation tool. Adding more validation tools has the potential to make the tool the one-stop shop for high throughput validations, even though they would have to be implemented from scratch, as they are not available. Additionally, allowing users to specify versions of reference data to use would significantly enhance the replicability of validations. #pagebreak() #bibliography("bibliography.yaml", style: "ieee") #pagebreak() = Appendix The attached zip file contains the source code of _SQC_ and _SQCLib_ in two directories. Please refer to the `README.md` files in both directories for instructions on running and using the SQC validation service.
https://github.com/Fr4nk1inCs/typreset
https://raw.githubusercontent.com/Fr4nk1inCs/typreset/master/src/styles/homework.typ
typst
MIT License
#import "./basic.typ": base-style #import "../utils/title.typ": make-title #import "../utils/header.typ": make-header #let i18n-hw-lit = ( "en": " Homework", "zh-cn": "作业", ) #let style( course: "Course Name", number: 0, names: "<NAME>", ids: "Student ID", lang: "en", hw-literal: none, body, ) = { let names = if type(names) == str { (names,) } else { names } let ids = if type(ids) == str { (ids,) } else { ids } assert( names.len() == ids.len(), message: "Number of names and IDs do not match", ) let hw-literal = if hw-literal == none { i18n-hw-lit.at(lang) } else { hw-literal } let title = course + hw-literal + " " + str(number) show: base-style.with(lang: lang) set document(title: title, author: names) // header let header = if names.len() == 1 { grid( columns: (auto, 1fr), align(left, title), align(right, names.at(0) + " " + ids.at(0)), ) } else { text(title) } set page( header-ascent: 14pt, header: make-header(header), ) // title make-title( title: title, other: grid( align: center + bottom, columns: 2, column-gutter: 1em, row-gutter: 0.4em, ..names.zip(ids).flatten() ), ) body }
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/hide-meta.typ
typst
Apache License 2.0
// Test that metadata of hidden stuff stays available. --- #set cite(style: "chicago-notes") A pirate. @arrgh \ #set text(2pt) #hide[ A @arrgh pirate. #bibliography("/files/works.bib") ] --- #set text(8pt) #outline() #set text(2pt) #hide(block(grid( [= A], [= B], block(grid( [= C], [= D], )) )))
https://github.com/GartmannPit/Praxisprojekt-II
https://raw.githubusercontent.com/GartmannPit/Praxisprojekt-II/main/Praxisprojekt%20II/PVA-Templates-typst-pva-2.0/template/figuresList.typ
typst
#let createListofFigures() = { set heading(numbering: none) par[= Abbildungsverzeichnis] // change heading here for other languages outline(title: none, target: figure.where(kind: image)) }
https://github.com/felsenhower/kbs-typst
https://raw.githubusercontent.com/felsenhower/kbs-typst/master/examples/23.typ
typst
MIT License
#table( columns: 3, [Händler], [Produkt], [Preis], [Ohbi], [Fliesen], [17,95], [Porrsche], [Motoren], [270,15], [Farber], [Stifte], [2,99], )
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap2/5_resistors.typ
typst
Other
#import "../../core/core.typ" === Resistors Because the relationship between voltage, current, and resistance in any circuit is so regular, we can reliably control any variable in a circuit simply by controlling the other two. Perhaps the easiest variable in any circuit to control is its resistance. This can be done by changing the material, size, and shape of its conductive components (remember how the thin metal filament of a lamp created more electrical resistance than a thick wire?). Special components called _resistors_ are made for the express purpose of creating a precise quantity of resistance for insertion into a circuit. They are typically constructed of metal wire or carbon, and engineered to maintain a stable resistance value over a wide range of environmental conditions. Unlike lamps, they do not produce light, but they do produce heat as electric power is dissipated by them in a working circuit. Typically, though, the purpose of a resistor is not to produce usable heat, but simply to provide a precise quantity of electrical resistance. The most common schematic symbol for a resistor is a zig-zag line: #image("static/5-resistor-symbol.png") Resistor values in ohms are usually shown as an adjacent number, and if several resistors are present in a circuit, they will be labeled with a unique identifier number such as $R_1$, $R_2$, $R_3$, etc. As you can see, resistor symbols can be shown either horizontally or vertically: #image("static/5-resistor-example.png") Real resistors look nothing like the zig-zag symbol. Instead, they look like small tubes or cylinders with two wires protruding for connection to a circuit. Here is a sampling of different kinds and sizes of resistors: #image("static/5-resistor-example-2.jpg") In keeping more with their physical appearance, an alternative schematic symbol for a resistor looks like a small, rectangular box: #image("static/5-resistor-symbol-2.png") Resistors can also be shown to have varying rather than fixed resistances. This might be for the purpose of describing an actual physical device designed for the purpose of providing an adjustable resistance, or it could be to show some component that just happens to have an unstable resistance: #image("static/5-variable-resistor-symbol.png") In fact, any time you see a component symbol drawn with a diagonal arrow through it, that component has a variable rather than a fixed value. This symbol "modifier" (the diagonal arrow) is standard electronic symbol convention. Variable resistors must have some physical means of adjustment, either a rotating shaft or lever that can be moved to vary the amount of electrical resistance. Here is a photograph showing some devices called potentiometers, which can be used as variable resistors: #image("static/5-variable-resistor-example.jpg") Because resistors dissipate heat energy as the electric currents through them overcome the "friction" of their resistance, resistors are also rated in terms of how much heat energy they can dissipate without overheating and sustaining damage. Naturally, this power rating is specified in the physical unit of "watts." Most resistors found in small electronic devices such as portable radios are rated at 1/4 (0.25) watt or less. The power rating of any resistor is roughly proportional to its physical size. Note in the first resistor photograph how the power ratings relate with size: the bigger the resistor, the higher its power dissipation rating. Also note how resistances (in ohms) have nothing to do with size! Although it may seem pointless now to have a device doing nothing but resisting electric current, resistors are extremely useful devices in circuits. Because they are simple and so commonly used throughout the world of electricity and electronics, we'll spend a considerable amount of time analyzing circuits composed of nothing but resistors and batteries. For a practical illustration of resistors' usefulness, examine the photograph below. It is a picture of a printed circuit board, or PCB: an assembly made of sandwiched layers of insulating phenolic fiber-board and conductive copper strips, into which components may be inserted and secured by a low-temperature welding process called "soldering." The various components on this circuit board are identified by printed labels. Resistors are denoted by any label beginning with the letter "R". #image("static/5-pcb-example.jpg") This particular circuit board is a computer accessory called a "modem," which allows digital information transfer over telephone lines. There are at least a dozen resistors (all rated at 1/4 watt power dissipation) that can be seen on this modem's board. Every one of the black rectangles (called "integrated circuits" or "chips") contain their own array of resistors for their internal functions, as well. Another circuit board example shows resistors packaged in even smaller units, called "surface mount devices." This particular circuit board is the underside of a personal computer hard disk drive, and once again the resistors soldered onto it are designated with labels beginning with the letter "R": #image("static/5-hard-disk-example.jpg") There are over one hundred surface-mount resistors on this circuit board, and this count of course does not include the number of resistors internal to the black "chips." These two photographs should convince anyone that resistors -- devices that "merely" oppose the flow of electrons -- are very important components in the realm of electronics! In schematic diagrams, resistor symbols are sometimes used to illustrate any general type of device in a circuit doing something useful with electrical energy. Any non-specific electrical device is generally called a load, so if you see a schematic diagram showing a resistor symbol labeled "load," especially in a tutorial circuit diagram explaining some concept unrelated to the actual use of electrical power, that symbol may just be a kind of shorthand representation of something else more practical than a resistor. To summarize what we've learned in this lesson, let's analyze the following circuit, determining all that we can from the information given: #image("static/5-circuit.png") All we've been given here to start with is the battery voltage (10 volts) and the circuit current (2 amps). We don't know the resistor's resistance in ohms or the power dissipated by it in watts. Surveying our array of Ohm's Law equations, we find two equations that give us answers from known quantities of voltage and current: #align(center)[ $R = E / I$ and $P = I E$ ] Inserting the known quantities of voltage (E) and current (I) into these two equations, we can determine circuit resistance (R) and power dissipation (P): $ R = (10 V) / (2 A) = 5 Omega $ $ P = 2 A times 10 V = 20 W $ For the circuit conditions of 10 volts and 2 amps, the resistor's resistance must be 5 $Omega$. If we were designing a circuit to operate at these values, we would have to specify a resistor with a minimum power rating of 20 watts, or else it would overheat and fail. #core.review[ - Devices called resistors are built to provide precise amounts of resistance in electric circuits. Resistors are rated both in terms of their resistance (ohms) and their ability to dissipate heat energy (watts). - Resistor resistance ratings cannot be determined from the physical size of the resistor(s) in question, although approximate power ratings can. The larger the resistor is, the more power it can safely dissipate without suffering damage. - Any device that performs some useful task with electric power is generally known as a load. Sometimes resistor symbols are used in schematic diagrams to designate a non-specific load, rather than an actual resistor. ]
https://github.com/rijuyuezhu/temgen
https://raw.githubusercontent.com/rijuyuezhu/temgen/main/README.md
markdown
MIT License
<h1 align="center">temgen</h1> A simple template generator for creating latex/typst article/presentation templates. ## Usage ```bash temgen -h temgen -l temgen [-f] identity [output] ``` - `-h`: Show help message. - `-l`: List template directories, instead of generating a template. - `-f`: force overwrite of existing directory. `identity` is the identity of the template to generate. It is of the form `{a,p}{l,t}[:<name>]`. E.g. `al:template1`, `pt`. - `{a,p}` stands for article or presentation. - `{l,t}` stands for latex or typst. - `[:<name>]` is an optional name for the template. If it is not provided, interactive mode will be used to get the name. If it is provided, `temgen` uses a fuzzy search to find the template. `output` is the output directory for the template. If it is not provided, the current directory will be used. By default, `temgen` refuses to overwrite non-empty directories. Use `-f` to force overwrite. ## The template directory The searching of the template directory is done in the following order: - environment variable `TEMGEN_TEM_DIR`. - read from the configuration file `~/.config/temgen/temgen.conf`, the first valid line of which is the template directory. - `~/.local/share/temgen/template/`. - `/usr/share/temgen/template/`. And `temgen` stops at the first directory that exists. The template directory has the following subdirectories, served as the templates: ``` {art,pre}-{latex,typst}-name ``` E.g. `art-latex-template1`, `pre-typst-nju`. All files that does not match the above pattern will be ignored.
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/type_check/fn_named4.typ
typst
Apache License 2.0
#let dict = (x: 3) #let foo(c: dict.x) = c #let x = foo()
https://github.com/HiiGHoVuTi/requin
https://raw.githubusercontent.com/HiiGHoVuTi/requin/main/lang/pow_sqrt.typ
typst
#import "../lib.typ": * #show heading: heading_fct Soit $Sigma$ un alphabet possédant au moins 2 lettres. Pour $L$ un langage sur $Sigma$ et $k>1$ on pose $ L^((k)) = {w^k | w in L} "et" L^(1\/k) = {w | w^k in L} $ #question(1)[Calculer $L^(1\/2)$ pour $L$ reconnu par l'expression régulière $a b(Sigma Sigma)^*$] #question(2)[Pour $k,l>=1$, montrer que - $(L^((k)))^((l)) = L^((k l))$ - $(L^(1\/k))^(1\/l) = L^(1\/k l)$ - $(L^(1\/k))^((k)) subset.eq L$ ] #question(1)[Donner un langage rationnel $L$ tel que $forall k>=2, L^((k))$ n'est pas rationnel] //#correct([]) #correct([ 1. On a $L^(1\/2) = L$ 2. - $(L^((k)))^(l) = {w^l | w in L^k} = {w^l | exists u in L : w = u^k} = {u^(k l) | exists u in L : w = u} = L^((k l))$ - ]) #question(1)[ Montrer que pour $L$ reconnu par un automate $A=(Sigma, Q, q_i, delta, F)$, on a $ w in L^(1\/2) <=> exists q in Q, cases(delta (q_i,w) = q ,delta (q,w) in F) $ ] #question(2)[Montrer que si $L$ rationnel, alors $L^(1\/2)$ aussi.] #question(3)[Montrer que soit $k in NN$, si $L$ est rationnel, alors $L^(1\/k)$ aussi.] #question(1)[ Si $L$ est rationnel, est-ce forcément aussi le cas de $union.big_(k>=1) L^(1\/k)$ ?] #question(4)[ Donner un algorithme qui détermine si un langage rationnel $L$ respecte $L = (L^(1\/2))^((2))$] #question(4)[ Montrer que si $L$ est rationnel, alors $"Root"(L) = {w in Sigma^* : w^(|w|) in L}$ l'est aussi.] #correct([ Soit $cal(A) = (Q, Sigma, delta, q_0, F)$ l'automate reconnaissant $L$. On pose alors $Q' = Q^Q times [| 0; 2(|Q|!!)|]$. Pour chaque $alpha in Sigma$ on pose $f_alpha : Q --> Q$ "l'action" de $alpha$ sur $Q$, définie formellement par $f_alpha (q) = delta(q,alpha)$.\ Finalement, on définit $delta' : Q' times Sigma --> Q'$ par : $delta'((f,n),a) = (f_a compose f ,k)$ avec $k=n+1$ si $n<2|Q|!$ et $k=|Q|!$ sinon. On dit qu'un couple $(f,n) in Q'$ est final si $f^n (q_0) in F$. (lemme) On remarque que pour tout $f : Q --> Q$ on a $f^(|Q|!!) = f^(2|Q|!!)$, car par finitude de $Q^Q$ (tiroirs) il existe $i > j$ tel que $f^i = f^j$, et $i-j < |Q^Q|=|Q|!$ donc $i-j | |Q|!!$, donc $f^(|Q|!!) = f^((i-j)k) = f^(2(i-j)k) = f^(2Q!!)$ avec $k = |Q|!!\/(i-j)$ Soit $u$ un mot qui nous fait aller sur $(f,n)$ un état final. On a que $f^(|u|)(u)$ est l'état obtenu après lecture de $u^(|u|)$, car par la construction de $f$, on a $f(q) = q'$ ssi $q'$ est obtenue après lecture de $u$ depuis $q$. Or on a que $n = |u| - k|Q|!!$ donc par le lemme précédent, $f^(|u|) = f^n$, ce qui montrer que $u in "Root"(L)$ Soit $u in "Root"(L)$, alors si on ce situe en $(f,n)$ après lecture de $u$, on a par construction $f^(|u|)(u) in F$. Par le même argument que sur le point précédent, on a $f^n(u) = f^(|u|)(u) in F$, donc $u$ reconnu. ])
https://github.com/Treeniks/bachelor-thesis-isabelle-vscode
https://raw.githubusercontent.com/Treeniks/bachelor-thesis-isabelle-vscode/master/chapters/02-background.typ
typst
#import "/utils/todo.typ": TODO #import "/utils/isabelle.typ": * = Background #include "/chapters/02-background/isabelle.typ" #include "/chapters/02-background/lsp.typ"
https://github.com/OtaNix-ry/typst-packages
https://raw.githubusercontent.com/OtaNix-ry/typst-packages/main/examples/quick-start/example.typ
typst
MIT License
#import "@otanix/board-meeting:0.1.0": * #show: meeting.with( title: "OtaNix ry hallituksen kokous", subtitle: "Mallidokumentti" ) #opening( // start-time: "12.00", attendees: ("<NAME>", "<NAME>") )[] #lawfulness( board-members-present: 3 )[] #agenda( // accepted: true // format: false )[ + Aihe 1 ] = Aihe 1 #closing( // end-time: "12.30", )[]
https://github.com/dhilipsiva/resume
https://raw.githubusercontent.com/dhilipsiva/resume/main/README.md
markdown
MIT License
# resume My Resume. Built with Typst. ## Compile ``` typst compine resume.typ ```
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/英语/1.typ
typst
#set page(numbering: "— 1 —") = Former 意思:前者的,以前的 国际音标:/ˈfɔːrmər/ 词性:形容词 词源解说:该词源于中古英语的"formere",意为"以前的"。它由"fore"(前)和"mer"(更早的)两个词根组成。 词根:fore-,mer- 派生词:formation(形成),formal(正式的),formality(正式),formulate(阐述),formidable(可怕的) 常用短语: 1. former president(前总统) 2. former employee(前雇员) 3. in the former case(在前一种情况下) 4. former glory(昔日的辉煌) 5. former life(前世) 关联例句: 1. The former CEO of the company retired last year. (该公司的前首席执行官去年退休了。) 2. She used to be a teacher, but now she works as a writer. (她曾经是一名教师,但现在从事写作工作。) --- = perspective [pəˈspɛktɪv] 词性:名词 意思:观点,角度,透视法 词源解说:源自拉丁语“perspectivus”,意为“透视的”。 词根:spect(看) 派生词:perspectively(副词),perspectivism(哲学上的一种观点),perspectivist(持有透视主义的人) 常用短语: 1. in perspective:从更广阔的角度来看 2. gain perspective:获得更好的观点 3. shift perspective:改变观点 4. keep perspective:保持正确的观点 5. lose perspective:失去正确的观点 关联例句: 1. From a historical perspective, this event was a turning point in our country's development. 2. It's important to keep perspective and not get too caught up in the small details. = italic [ɪˈtælɪk] 词性:形容词 词源解说:italic一词源于意大利语的"italicus",意为"意大利的"。最初,这个词用来形容意大利的文字风格,后来扩展为指斜体字体。 词根:无 派生词:italicize (动词) 常用短语: 1. in italic:以斜体字形式 2. italic type:斜体字体 3. italic font:斜体字体 4. write in italics:用斜体字书写 5. italicize a word:将一个词变成斜体字 关联例句: 1. Please write your name in italic. 请用斜体字写下你的名字。 2. The title of the book is in italics. 这本书的标题是用斜体字书写的。 ```latex \begin{itemize} \item Fast \item Flexible \item Intuitive \end{itemize} ``` #rect(fill: aqua)[Get started here!]
https://github.com/swaits/typst-collection
https://raw.githubusercontent.com/swaits/typst-collection/main/glossy/0.1.0/lib.typ
typst
MIT License
#import "src/gloss.typ": init-glossary, glossary
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/patterns/weeks/week5.typ
typst
#import "../../utils.typ": * #subsection("Object Aspects") - task - behavior - identity - small state - value - behavior - state - entity - state - small behavior - identity - service - behavior #align( center, [#image("../../Screenshots/2023_10_20_07_40_21.png", width: 100%)], ) #section("Values in Programming") How are values represented in programming languages? - types - int - double - etc. - functions convert values - fn(i32) -> i32 - OO -> values represented by objects - must be converted since technically values can't have an "identity" #subsection("Why objects?") Classes allow you to specify what exactly your value type does. For example, if you want a temperature value with kelvin, then you need a specific range, by using classes, you can ensure that it will be within this range without needing to check inside functions that use this value. #align( center, [#image("../../Screenshots/2023_10_20_07_54_38.png", width: 80%)], ) #subsubsection("Issues with objects") When using objects, we introduce identity to values, this means whenever we want to compare the actual values, we need to make sure to dereference the identity -> \*ptr. Or if you are forced to use shit languages: "java".equals("shit") -> true ! #section("Patterns of Value") #subsection([Whole Value]) #set text(size: 14pt) Problem | When creating something like a date class, there is an issue with parameters, year, month and day are all integers, how can we enforce the correct usage at compile time? Use types for each parameter! - disallows inheritance to avoid slicing - wraps existing types - value receives meaning by providing a *dimension and range*\ Context |\ Participants : - #set text(size: 11pt) // images //typstfmt::off ```java // year public final class Year { public Year(int year) { value = year; } public int getValue() { return value; } private final int value; } // ... // usage public final class Date { public Date(Year year, Month month, Day day) { … } // ... } Date first = new Date(new Year(year), new Month(month), new Day(day)); ``` //typstfmt::on #columns(2, [ #text(green)[Benefits] - enforces value is withing range of meaning - usually done at compile time -> no runtime performance hit when used with real languages #colbreak() #text(red)[Liabilities] - change in meaning requires change in code -> less flexible ]) #subsection([Value Object]) #set text(size: 14pt) Problem | When creating an object, we only have an integer to compare the objects, this is not ideal, we usually would like to compare the actual contents, not the identity. How can we do this?\ Solution | We simply use hashing functions and compare the hash. - #set text(size: 11pt) //typstfmt::off ```java public final class Date implements Serializable { // ... private static final long serialVersionUID = -3248069808529497555L; // ... @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Date date = (Date) o; return year.equals(date.year) && month.equals(date.month) && day.equals(date.day); } @Override public int hashCode() { return Objects.hash(year, month, day); } } ``` //typstfmt::on #columns(2, [ #text(green)[Benefits] - allows you to compare values with identity and multiple values within #colbreak() #text(red)[Liabilities] - change in object requires redoing hash - hashing might not always be simple - hash collisions possible ]) #subsection([Copied Value and Cloning]) #set text(size: 14pt) Problem | How can we transform value objects from one to the other? \ Solution | \ - conversion methods - toOtherType method - Date.toInstant() - constructor #align(center, [#image("../../Screenshots/2023_10_20_08_13_23.png", width: 30%)]) - factory method - Date.from(Instant instant) -> same as conversion just static #subsection([Immutable Value]) #set text(size: 14pt) Problem | We require a value that is not subject to change and needs to be shared between threads -> immutable and implements Send/Sync\ Solution | jafuck: make class final, rust: just don't make it mut, lol, also impl Send/Sync, done #set text(size: 11pt) // images //typstfmt::off ```java public final class Date { private final Year year; private final Month month; private final Day day; public Date(Year year, Month month, Day day) { // range checks ... this.year = year; this.month = month; this.day = day; } // ... } ``` //typstfmt::on #subsection([Enumeration Values]) #set text(size: 14pt) Problem | Same as whole value but range should not change -> Enum\ Context | Every single language has this these days... #set text(size: 11pt) // images //typstfmt::off ```java public enum Month { JANUARY(1), // ... DECEMBER(12); private final int value; private Month(int value) { if (value < 1 || value > 12) { // avoid careless mistakes, check value range throw new IllegalArgumentException(); } this.value = value; } public int getValue() { return value; } } ``` //typstfmt::on #subsection([Copied Value and Cloning]) #set text(size: 14pt) Problem | Essentially call by value on value objects -> .clone()\ Context | Can be used for memory safety #set text(size: 11pt) #align(center, [#image("../../Screenshots/2023_10_20_08_23_01.png", width: 70%)]) #columns(2, [ #text(green)[Benefits] - memory safety - call-by-value #colbreak() #text(red)[Liabilities] - runtime overhead ]) #subsection([Copy Contructor]) #set text(size: 14pt) Problem | Copy all values from another object without copying the identity\ Solution | Loop through all attributes and copy them over\ #set text(size: 11pt) // images #align(center, [#image("../../Screenshots/2023_10_20_08_24_12.png", width: 70%)]) #subsection([Class Factory Method]) #set text(size: 14pt) Problem | How can we create objects without constructors (and adding caching to it)?\ Solution | Static Functions to create the object\ #set text(size: 11pt) // images #align(center, [#image("../../Screenshots/2023_10_20_08_25_58.png", width: 70%)]) Aka with these constructors we could check whether we already have this date within the cache and just return that if that is the case. #columns(2, [ #text(green)[Benefits] - more control over constructor #colbreak() #text(red)[Liabilities] - - ])
https://github.com/francorbacho/cv
https://raw.githubusercontent.com/francorbacho/cv/master/cv.typ
typst
#import "alt.typ": esei, pk, uvigomotorsport #import "secrets.typ": phone #let chiline() = {v(-3pt); line(length: 100%); v(-5pt)} // TODO: Add link to Webpage? #let banner = [#phone | #link("mailto:<EMAIL>") | #link("https://github.com/francorbacho")[github.com/francorbacho] | #link("https://linkedin.com/in/francorbacho")[linkedin/francorbacho] ] #let technologies = [Docker, Linux, Unix, Bash, C & C++, Python, Java, Kotlin, Git, GitHub, Computer Vision, Nvidia, Arduino, Rust, SQL, ROS2, HTML, CSS, JavaScript, WebAssembly]
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/001.%20prop62.html.typ
typst
#set page( paper: "a5", margin: (x: 1.8cm, y: 1.5cm), ) #set text( font: "Liberation Serif", size: 10pt, hyphenate: false ) #set par(justify: true) #v(10pt) = This Year We Can End the Death Penalty in California #v(10pt) _November 2016_ If you're a California voter, there is an important proposition on your ballot this year: Proposition 62, which bans the death penalty. When I was younger I used to think the debate about the death penalty was about when it's ok to take a human life. Is it ok to kill a killer? But that is not the issue here. The real world does not work like the version I was shown on TV growing up. The police often arrest the wrong person. Defendants' lawyers are often incompetent. And prosecutors are often motivated more by publicity than justice. In the real world, about 4% of people sentenced to death are innocent. So this is not about whether it's ok to kill killers. This is about whether it's ok to kill innocent people. A child could answer that one for you. This year, in California, you have a chance to end this, by voting yes on Proposition 62. But beware, because there is another proposition, Proposition 66, whose goal is to make it easier to execute people. So yes on 62, no on 66. It's time.
https://github.com/MooersLab/manuscriptInTypst
https://raw.githubusercontent.com/MooersLab/manuscriptInTypst/main/classic-first-submission-manuscript.typ
typst
MIT License
// Created 2024-09-29 Sun 23:01 // Intended Typst compiler #set page(width: 8.5in, height: 11in, margin: (x: 0.5in, y: 0.5in),) #set text(11pt) #set text(font: "Helvetica") #show figure: set par.line(numbering: none) #let running = [Classic Template #datetime.today().display()] #let title = [Classic Generic First Submission Journal Article in Typst] #align(center, text(17pt)[ #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() *#title* ]) // Set the title use for reuse in the running title and the main title page. #let firstauthor = [Graduate Student] #let secondauthor = [Senior Collaborator] #let thirdauthor = [Staff Scientist] #let seniorauthor = [Senior author] #let affil1 = [Department of Biochemistry and Physiology, University of Oklahoma Health Sciences Center, Oklahoma City, Oklahoma, United States 73104] #let affil2 = [Stephenson Cancer Center, University of Oklahoma Health Sciences Center, Oklahoma City, Oklahoma, United States 73104] #let affil3 = [Laboratory of Biomolecular Structure and Function, University of Oklahoma Health Sciences Center, Oklahoma City, Oklahoma, United States 73104] #set footnote(numbering: "*") #align(center, text(11pt)[ #linebreak() #linebreak() #linebreak() #firstauthor#super[1], #secondauthor#super[2], #thirdauthor#super[3], and #seniorauthor#super[1,2,3]#footnote[Corresponding author: blaine-mooers at ouhsc.edu, phone: 405-271-8300, FAX: 405-271-????] #linebreak() #linebreak() #linebreak() #super[1]#affil1 #linebreak() #linebreak() #super[2]#affil2 #linebreak() #linebreak() #super[3]#affil3 #linebreak() #linebreak() #datetime.today().display() ]) #pagebreak() #set page( header:[ Student, ..., and Mooers #h(1fr) #running], numbering: "1 / 1", number-align: right, ) // Requires typst version 0.12.0 for line numbering. #set par.line(numbering: "1") #set par(leading: 2em, justify: false) = Abstract Fill in after the results section is filled in. Fill in after the results section is filled in. Fill in after the results section is filled in. Fill in after the results section is filled in. Fill in after the results section is filled in. Fill in after the results section is filled in. Fill in after the results section is filled in. Fill in after the results section is filled in. Fill in after the results section is filled in. Fill in after the results section is filled in. Fill in after the results section is filled in. Fill in after the results section is filled in. *Keywords:* typesetting, typography, scientific writing, reproducible research, text editing, collaborative writing, version control #pagebreak() = Introduction Typst is a new markup language for writing various kinds of documents, such as PDF and HTML. It is meant to be a rethink of LaTeX, although the heavy influence of LaTeX in the typing of math equations suggests otherwise. It takes a computer programmer approach to typesetting by providing functions to act on some or all of the text. Many of these functions can be stored in an external template file that is imported into a given typst manuscript file so the clustter of these functions can remain out of sight to give the main typst document less cluttered appearance. The typst project is still in development and is not yet complete, but the project' repository on GitHub has attracted over 33,100 stars. The tinymist program supports live previews of the document in the web browser, so any editor can be used to edit typst documents while enjoying previews of the PDF. The typst project is complete enough to support the generation of the first-submission version of a manuscript as a PDF, although it may be years before publishers will accept typst source files. \ \ The biggest snag to getting going with typst for writing is the need for the bibliography to be in the typst native format (hayagriva) or in BibLaTeX. The JabRef program supports conversions of BibTeX entries to BibLaTeX. The second program is that there are breaking changes in the main program. Some packages are already broken because the maintainers lost interest. = Materials and methods == First set of methods == Second set of methods = Results I insert an overview of the results section here let the reader know what is comming. No one has ever complained about this paragraphy although most authors skip it. == Hot result number one Tables have to be wrapped in a figure function (see @progress) to add a caption. I put the label at the end of the caption. Tables are numbered separately from figures. You do not have to take any special measures. You may have to move the table to the back of the paper, depending on the author guidelines. #figure( table( columns: (auto, auto, auto), inset: 10pt, align: horizon, table.header( [*Milestone*], [*Traget date*], [*Achievement data*],), [milestone 1], [date], [date], [milestone 2], [date], [date], [milestone 3], [date], [date] ), caption: [Milestones and dates.] )<progress> == Hot result number two With regard to figures (see @words), typst does not handle PDF nor Tiff. You have to convert them to SVG or to one of the bitmap formats: PNG, GIF, or JPG. Note the absence of support of postscript or encapsulated postscript. Many journals accept these only these latter formats for the final submission. Be prepared to make your figures in multiple formats. #figure( image("words10.png", width: 80%), caption: [A curious figure.], )<words> == Hot result number three Equations can be numbered and shown in display mode (@ratio). The math equation fuction allows you to control the placement of the equation number. #set math.equation(numbering: "(1)") $ phi.alt = (1 + sqrt(5)) / 2 $ <ratio> Can we add a caption to the equation by wrapping it in a figure @bragg? Not really. It is called a figure when it is an equation. #figure( $ 2 upright(d) sin theta = upright(n) lambda $, caption: [Caption of the equation.], )<bragg> == Hot result number four == Hot result number five == Hot result number six = Discussion == Typst vs. LaTeX It is useful to compare and contrast typst with LaTeX because typst was developed as an alternative to LaTeX. Many of the claims of ease of use in favor of typst are over-stated. It is clearly more capable than Common Markdown, but it is far less capable than LaTeX. It might meet the demands of users unwilling, or not ready, to do the work of learning LaTeX who are dissatisfied with markdown. I learned a series of markup languages and experienced repeated disaapointments with their shortcomings: Then I gave in and learned LaTeX. \ \ The phrase ``tpyst makes LaTeX great again'' comes to mind: typst has inspired me to dig deeper into LaTeX. LaTeX users may want to learn typst to rekindle their love for LaTeX. Org-mode users may want to learn typst for similar reasons. \ \ == Acceptance by publishers Publishers should accept PDFs of first submission manuscirpts written in typst. Some skilled typst users have already prepared templates for several journals. One is available for MDPI journals. \ \ == Suitability for version control The practice is writing one sentence per line is consistent with version control. Typst accommodates this unorthodox approach to writing sentences. \ \ The wrapping of sentences into paragraphs in a source document is mark of insanity. You will have to unwrap your sentences to be able to shuffle them around during rewriting. I think that the wrapping of sentences into block paragraphs was driven by the need to save paper. It is not necessary in electronic formats. \ \ Some claim that the format of one sentence per line reduces comprehension. I doubt this is true: It more likely that reading comprehension is improved. \ \ == Support for collaborative editing The typst.app has promised to support collaborative writing in a fashion similar to Oveleaf. The developers even have an underleaf project based on typst. I have a latency issue with this app when my computer is running low on RAM. \ \ == Voice computing with typst You should be able to use speech-to-text via the Google plug-in Voice In. \ \ == Text editor support I prefer to work local in Emacs @Mooers2021Templates. I use the typst-ts-mode with treemacs. I am still working on the live preview in Emacs. \ \ = Acknowledgments We thank <NAME> for introducing us to typst. = Funding #set par(leading: 0.5em, justify: false) #bibliography("first-submission.bib", title: "Cited References", style: "cell") // Local Variables: // tp--master-file: "/Users/blaine/6112MooersLabGitHubLabRepos/manuscriptInTypst/first-submission-manuscirpt.typ" // End:
https://github.com/rabotaem-incorporated/algebra-conspect-1course
https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/02-complex-numbers/01-construction.typ
typst
Other
#import "../../utils/core.typ": * == Построение поля комплексных чисел #def[ $CC = RR times RR = \{(a, b) divides a, b in RR\}$ ] #def[ - Сложение на $CC$: $(a_1, b_1) + (a_2, b_2) = (a_1 + a_2, b_1 + b_2)$ - Умножение на $CC$: $(a_1, b_1) dot (a_2, b_2) = (a_1 a_2 - b_1 b_2, a_1 b_2 + a_2 b_1)$ ] #pr[ $(CC, +, dot)$ --- поле. ] #proof[ - Коммутативность сложения: #[ $ &(a, a') + (b, b') =\ &(a + b, a' + b') =\ &(b + a, b' + a') = &(b, b') + (a, a') $ ] - Ассоциативность сложения: #[ $ &((a, a') + (b, b')) + (c, c') =\ &(a + b + c, a' + b' + c') =\ &(a + (b + c), a' + (b' + c')) =\ &(a, a') + ((b, b') + (c, c')) $ ] - $(0, 0)$ --- нейтральный элемент сложения. - $(-a, -b)$ --- обратный элемент к $(a, b)$. - Коммутативность умножения: #[ $ &(a, a') dot (b, b') =\ &(a b - a' b', a b' + a' b) =\ &(b a - b' a', b a' + b' a) =\ &(b, b') dot (a, a') $ ] - Ассоциативность умножения: #[ $ &((a, a') dot (b, b')) dot (c, c') =\ &(a b - a' b', a b' + a' b) dot (c, c') =\ &(c (a b - a' b') - c' (a b' + a' b), c (a b' + a' b) + c' (a b - a' b')) =\ &(c a b - c a' b' - c' a b' - c' a' b, c a b' + c a' b + c' a b - c' a' b') =\ &(a b c - a' b' c - a b' c' - a' b c', a b c' + a b' c + a b c' - a' b' c') $ $ &(a, a') dot ((b, b') dot (c, c')) =\ &(a, a') dot (b c - b' c', b c' + b' c) =\ &(a (b c - b'c') - a' (b c' + b' c), a (b c' + b' c) + a' (b c - b' c')) =\ &(a b c - a' b' c - a b' c' - a' b c', a b c' + a b' c + a b c' - a' b' c') $ Как видно, выражения совпадают. ] - Дистрибутивность: #[ Проверим правую, левая проверяется аналогично: $ &((a, a') + (b, b')) dot (c, c') =\ &(a + b, a' + b') dot (c, c') =\ &((a c + b c) - (a' c' + b' c'), (a' c + b' c) + (a c' + b c')) =\ &(a c - a' c', a' c + a c') + (b c - b' c', b' c + b c') =\ &(a, a') dot (c, c') + (b, b') dot (c, c') $ ] - $(1, 0)$ --- нейтральный элемент умножения. - $(a, b) z_1 z_2 = (1, 0): space z_1 = (a, -b), space z_2 = (1)/(a^2 + b^2)$ ] #def[ $CC$ --- поле комплексных чисел. ] #def[ $c in CC$ --- комплексное число. ] #pr[ $RR' = \{(a, 0) divides a in RR\}$, тогда: $RR'$ замкнуто относительно сложения, вычитания, умножения, содержит единицу, то есть является подкольцом поля $CC ==> RR'$ --- само является кольцом относительно сложения, умножения, ограниченных на $RR'$. Тогда существует отображение $phi: space RR -> RR'$, где $a maps (a, 0)$, и $phi(a)$ --- изоморфизм колец, то есть $phi$ --- биекция и $display(cases( phi(a + b) = phi(a) + phi(b), phi(a b) = phi(a) phi(b) ))$. Отождествим $(a, 0)$ с вещественным числом $a$. ] Давайте наконец-то определим комплексное число. $(a, 0) dot (0, 1) = (0, a)$ $(a, b) = (a, 0) + (0, b) = (a, 0) + (b, 0) dot (0, 1) = a + b dot (0, 1) = a + b i$ #def[ $z = a + b i$ --- _комплексное число_. $a = \Re(z)$, $b = \Im(z)$ --- _действительная_ и _мнимая_ части комплексного числа $z$. В геометрическом виде это вектор $z = (a, b)$. ] #def[ Пусть $z = a + b i$ --- комплексное число, тогда $overline(z) = a - b i$ --- _сопряженное_ к $z$. ] *Отступление про отображения* #def[ $id_M: M -> M, space x maps x$ --- тождественное отображение на $M$. ] #def[ Пусть $alpha: M -> N, space beta: N -> P$ --- отображения Тогда $alpha compose beta: M -> P, space x maps alpha(beta(x))$ --- композиция отображений. ] #def[ Пусть $alpha: M -> N$ --- отображение Отображение $beta: N -> M$ --- обратное к $alpha$, если $beta compose alpha = id_M$. ] #pr[ У отображения $alpha: M -> N$ есть обратное отображение, если и только если $alpha$ --- биекция. ] #proof[ "$arrow.r.double$": Инъективность: $beta compose alpha = id_M, space alpha(x) = alpha(y) ==> beta(alpha(x)) = beta(alpha(y)) ==> x = y$ Сюръективность: $y in N, space y = alpha(beta(y)) in \Im(alpha)$ ($\Im$ это прообраз) "$arrow.l.double$": Пусть $alpha$ --- биекция, назовем $beta: N -> M$ --- обратным, если $forall y in N alpha^(-1)(y) = \{x\}, space x in M$ Положим $beta(y) = x, space alpha compose beta = id_N, space beta compose alpha = id_M$ ] *Продолжение* #def[ Автоморфизм --- изоморфизм на себя. ] #pr[ $sigma: CC -> CC, space z maps overline(z)$ --- автоморфизм. ] #proof[ $sigma$ --- биекция, т.к. $sigma compose sigma = id_(CC)$ $sigma(z_1 + z_2) = sigma(z_1) + sigma(z_2)$ --- очевидно $sigma(z_1 z_2) = sigma(z_1) sigma(z_2)$ $sigma(1) = 1$ --- очевидно $z_1 = a_1 + b_1i, space z_2 = a_2 + b_2i$ $sigma(z_1 z_2) = overline(a_1 a_2 - b_1 b_2 + i(a_1 b_2 + a_2 b_1)) = a_1 a_2 - b_1 b_2 + i(a_1 b_2 + a_2 b_1)$ $sigma(z_1) sigma(z_2) = overline((a_1 - i b_1) (a_2 - i b_2)) = a_1 a_2 - b_1 b_2 + i(a_1 b_2 + a_2 b_1)$ ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/055%20-%20Murders%20at%20Karlov%20Manor/003_Episode%203%3A%20Shadows%20of%20Regret.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 3: Shadows of Regret", set_name: "Murders at Karlov Manor", story_date: datetime(day: 09, month: 01, year: 2024), author: "<NAME>", doc ) The party was pretty much over after that. Etrata's removal from the grounds of Karlov Manor took no time at all in the grand scheme of things. Long enough for everyone to see what was happening; long enough for several members of the Selesnya Conclave to approach Teysa, nearly frantic with the need to make it clear that Etrata wasn't with them, they hadn't smuggled her into the party, this was not their doing, they had been betrayed as much as anyone else! Not, perhaps, as much as Zegana, who would never be betrayed by anyone ever again, but as much as Teysa, as much as the Agency, as much as anyone else who was innocent of all wrongdoing. Teysa's wards should have kept anyone from leaving: Karlov Manor wasn't the seat of Orzhov power, but it was the seat of #emph[her] power, and here, her word was absolute law. But when the Azorius mages who had grabbed Etrata marched her to the gate and pulled her out, nothing stopped them; no other members of House Dimir appeared to demand the release of one of their own. As during the run for the coatroom, Kaya would have sworn Teysa was nowhere nearby. The tap of the other woman's walking stick against the stones of the courtyard was the only warning she had that she was wrong, and if she hadn't been so attuned to the sound, she would have missed it under the rising hubbub of voices. #emph[Everyone] wanted to know what had happened. #emph[Everyone] wanted to know why a Dimir assassin had led Teysa's pet Planeswalker on a merry chase through what was supposed to be a celebration, dressed as a member of the Selesnya Conclave, no less! And into that ridiculous magic of Proft's! Only a few members of the Agency had seen it in action before, and while they were quietly smug about how elegantly he'd applied it to the task at hand, the remaining Azorius looked more annoyed than anything else. Kaya supposed that wasn't much of a surprise. Proft had been their asset before he chose to go off and ply his talents with the Agency, and if there was one thing she knew about the guilds, it was that they didn't like losing resources. Especially these days, with everyone running close to the bone as it was. Kaya resisted the urge to glance at Teysa as she stepped up on Kaya's right, leaning heavily on her stick. The evening had taken a lot out of her. "You let them leave," said Kaya. "Following our colleagues at the Agency into the investigative arts?" asked Teysa. "It seemed impolitic to imprison the members of another guild when they were apprehending a killer. They're my wards. I can open them for anyone I like. I would have opened them for you, if you'd tried to follow." "You can't hold me here without my consent." "No. I suppose I never could, could I? Out of all of us, you remain the one who can just … walk away, any time you want to." Teysa's expression sobered. Kaya managed not to flinch. Somehow, without coming anywhere close to mentioning them by name, Teysa had managed to invoke the shades of Jace and Vraska, the other two people who'd walked away from Ravnica. The two who hadn't come back. The two who never would. What was she doing? She didn't belong here anymore. She might have said as much, but Teysa looked directly at her, heartbreaking shadows in her eyes, and said, "I'm grateful that you stayed." "I said I would," said Kaya, looking away. "How is Vannifar?" "Shaken, but recovering," said Teysa. "She's moving past grief and into outrage. I wouldn't want to be the person who did this. They're likely to find the entire weight of the Simic crashing down upon them, and there's no one in a position to leaven Vannifar's wrath. She and Zegana fought over the future of the Simic Combine, but they were sisters, in their way. There were deep bonds of loyalty and affection there. Vannifar won't allow this to go unanswered." "No, I can't imagine that she would. What did you want to talk to me about before?" Teysa hesitated, glancing at the partygoers milling around them, even as they clumped back into groups and began drifting toward the exits. Some were heading for the manor, others for the gates, depending on whether they'd left anything inside, and Kaya found herself wondering, somewhat uselessly, what the Agency intended to do about the coats that had been left under Zegana's body. Proft, who had been standing nearby and observing this entire interaction with dismayingly keen eyes, apparently had the same thought. He straightened and hurried back toward the manor, leaving Teysa and Kaya alone in the thinning crowd. "The news will be everywhere by morning," said Teysa bitterly. "'Come celebrate what a great job the guilds did of protecting us all, by watching them fail to protect one of their own.'" "I'm sure people will understand that this wasn't your fault," said Kaya. Teysa shot her a sharp look. "You know better." She did. Still, she had hope. Hope that the wounds of war were healing; hope that the old wounds of Ravnica might be healing at the same time. Torn scar tissue could sometimes heal into something cleaner than the initial injury, if conditions were right. Maybe the conditions were right. "Before, on the balcony, there was something you wanted to say to me," said Kaya. "Or tell me. Can you tell me now?" Teysa sighed. "Stay long enough for the news to break, and to see that the ripples don't wash us all away, and I'll call for you," she said. "I do #emph[want] to tell you, it's just … this isn't the time." Kaya looked at her carefully. She seemed sincere. Teysa was a born politician, but even politicians can have their moments of vulnerability. "Three days," she said, finally. "Then, if you haven't called me, I come looking." "Deal," said Teysa. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Three days slipped steadily by. Kaya returned to her rented room, refusing Teysa's offer of a guest chamber at the manor, and Teysa, perhaps understanding that pressing the matter would be a good way to make Kaya leave the plane, hadn't pushed the issue. During the day, she wandered the streets, enjoying the familiar tastes of Ravnican street food and strong coffee laced with cream and lavender honey, and listened to the people who didn't know her well enough to bite their tongues. Rumors swirled in the streets, bitter, writhing things with teeth that snap and bite. There had been a theft at the Orzhov party, they said; some guild member had lost a precious heirloom and was going to be furious until it could be reclaimed. There had been a betrayal. An affair had been uncovered. All manner of crimes had apparently happened on the grounds of Karlov Manor, and because both the Agency and the Azorius had been present, both groups were being spoken of with uncommon disdain. #figure(image("003_Episode 3: Shadows of Regret/01.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Anyone known to have been in attendance moved at the center of a hurricane of flattery and sweet-tongued requests for more information. Most people, lacking true gossip to share, invented more and more outlandish stories, knowing that there was no one who could contradict them. Kaya listened to them all, frowned to herself, and said nothing. The less attention she attracted now, the better. Because they didn't just talk about the party, although that was the most recent glorious scandal, and somewhat less raw than the wounds of war. They talked about the Phyrexian invasion and how the Planeswalkers had failed them all. After spending years safe in the knowledge that the average person didn't know what a Planeswalker was and thus couldn't have opinions on them, Kaya was now faced with a reality where everyone knew, and almost everyone disapproved. It was uncomfortable enough that she was almost relieved when, on the morning of the third day, a messenger from the Agency came looking for her. She was positioned in a tiny coffee shop, listening to the morning news. The word "murder" was finally starting to circulate. That, combined with the unusual scarcity of Simic Combine members, was attracting attention, and pulling the gossips away from their ongoing discussion of the war. "Ma'am?" said the messenger, stopping a few feet away, virtually vibrating as he waited to be acknowledged. Kaya took one last, lingering sip of her coffee before turning to face him, blinking when she saw his face. "Agent … Kellan? Why did they send you?" "Were you expecting the Agency to send someone?" asked Kellan, blinking earnestly. "I thought they might, so I've been staying where I'd be easy to find," said Kaya. She rose, regretfully leaving her half-finished coffee behind. "I assume Detective Proft would like to speak with me about what happened?" She knew, all too well, how many ears would be perking up and turning in her direction, their owners attracted by mention of the Agency, hoping to catch some juicy scrap of information. "No, actually," said Kellan. "He isn't much on sharing his thoughts with other people when he doesn't have to. No, it's the chief who'd like to speak to you." Kaya caught herself before blurting out, "Ezrim?" Let the gossips wonder a little longer. Instead, she nodded and beckoned for Kellan to follow her out of the shop. Once they were on the street, and a little less obvious of a target for busybodies, she asked, "Why did you come yourself? They just honored you for your service; you should rank above playing message boy." "Oh," said Kellan. "I asked them to send me." "What? Why?" "I wanted to speak with you." Kaya blinked, not sure how she was supposed to respond to that. Kellan started walking toward the Agency headquarters, and she automatically followed, still trying to process her thoughts. "Why?" she asked, finally. "I've read your file. You're not from here." He waved a hand, indicating the city around them. "Ravnica, I mean. You came from someplace much farther away." "You're allowed to say 'Planeswalker,' you know. It's not a bad word," said Kaya. Kellan looked briefly abashed. "Sorry. Yes. You're a Planeswalker." "So is my father. I hoped you might … I wondered if you might know where he is." Kaya stopped walking. Kellan continued for several more steps before he noticed and turned to face her. "What?" he asked. "Your father is—who's your father?" #emph[Please don't let him say a name I know] , she added silently. #emph[Please, if there's any mercy left in the Blind Eternities, he won't name one of the dead.] "His name's Oko," he said. "He's one of the fae." A stranger, then. "Sorry. Don't know him." She could see the disappointment in his eyes even as the relief flowed through her. "You're the second Planeswalker I've talked to who's said that. I thought—well, the Agency has all sorts of information. I thought they might know something, if he's ever passed through here." "And no luck?" Kellan only shook his head. "The filing system is … complicated." "Just keep on looking, okay, kid? And if I ever run into him, I'll tell him you're trying to find him," said Kaya. Kellan gave her a fragile, sidelong smile. "Thank you," he said. "That would mean a lot." The floating, angular shape of the Agency headquarters loomed in front of them. Streams of water cascaded from the base, falling into channels that had been designed to catch them before they could flood the streets. Agency mounts stood at the ready, ferrying agents up and down. Kellan led Kaya through the queue, up to the door, and past the security check, escorting her down the hall to Ezrim's office before he said, "I'll see you when you're done with the boss," and left her alone. Kaya hesitated, looking at the closed door. Waiting wouldn't make this happen any faster, and so, gingerly, she raised her hand and knocked. "Enter," boomed Ezrim from inside. Kaya took a deep breath and stepped through the door, not bothering to open it first. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Ezrim's office had been designed with his ever-present companion in mind. In addition to a massive desk and several traditional chairs for visitors, the back third or so of the space had been turned into something close to a stable, with straw on the floor under a heap of pillows that formed a sort of lounging chair. Not that Ezrim was currently lounging; the great archon was sitting on the back of his steed, twisted to face the desk, sorting a pile of papers. Kaya realized with a small start that she didn't know whether Ravnican archons were a single conjoined being or a pair of individuals who simply chose to never be apart for any reason. She had never seen Ezrim dismounted nor any other archon of Ravnica knocked from their partners in combat. If they were one creature, this office was a symbol of practical necessity, not one of consideration. "You called for me, sir?" she asked, folding her hands behind her back and standing at attention. "I did," said Ezrim, before falling silent. Kaya recognized the ensuing silence as a prompt for her to say something, and so she stood a little straighter and said nothing at all. She was happy to come when called for, but that didn't mean she worked for Ezrim. She didn't technically owe him anything. If he wanted her to talk, he could ask her a question. After enough time had passed for the silence to become uncomfortable, Ezrim cleared his throat and said, "You're not a member of the Agency." "No, sir." "But you're a well-known problem-solver. The Orzhov have always spoken highly of your problem-solving abilities." Somehow, she doubted the "always" in that sentence. Kaya smiled thinly and said, "Thank you, sir." "Because of your position as a former guild leader, the guilds will view you as largely neutral in this situation. You had no known grudges against either the Simic Combine or House Dimir." "No, sir. I get on reasonably well with both guilds." "Teysa called us both to that party to try to lend us what legitimacy she had to offer. I, as head of the Agency, and you as a former guild master … and a Planeswalker. You're aware that your kind are not presently well regarded in Ravnica. I believe even Guildmaster Zarek has encountered issues of late." "I'm aware, sir," said Kaya. "I would like you to assume leadership of this investigation. You would have access to any resources you need, including my staff, and I believe you would need some sort of lever to remove Detective Proft from the case. He doesn't let go of a puzzle once his interest has been aroused. While the assassin Etrata has been detained, we still don't know who ordered the killing, or why, and she continues to insist that she has no memory of the deed." Kaya said nothing. For once, Ezrim didn't allow the pause to stretch out. "Your neutrality is assumed. Your involvement could only help to redeem public opinion of the Planeswalkers who couldn't save us when we needed them most." "No." "I'm sorry, what?" "No. It's a complete sentence, and you know what it means. No, I won't help you with this. I've done more than enough already. Thank you for your concern about my reputation." She turned on her heel and stalked out of the office, once more without opening the door. Ezrim didn't call her back. Kellan was gone, probably elsewhere in the building doing his actual job, but it felt like every other eye at the Agency was fixed on her as she lifted her chin and walked back down the hall to the door, leaving their silences and unwanted requests behind. The sooner she was out of Ravnica, the better. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The Agency had been established to investigate crimes without the bias of guild affiliation tainting their discoveries. Criminals, whether proven or strongly suspected, were remanded to Azorius custody to be held in appropriate conditions. As Proft stood waiting for the Azorius lawmage guarding the door to finish checking his papers and let him through, he couldn't help regretting the years he'd spent doing precisely the same thing. "Everything seems to be in order," said the lawmage finally. Three layers of security had looked over Proft's paperwork, none of them finding any issues. At least this one was too new to the guild to have overlapped his tenure. People who remembered him dressed in their own colors tended to be even more insufferable when confronted with what they saw as him begging them for access. "You can go in." The door unlocked at the lawmage's words, and Proft nodded, reclaiming his papers. "Excellent performance of duty," he said, trying to restrain his tone as he stepped into the final hall between him and his destination. Etrata's cell was the only one occupied in this block, leaving her entirely isolated, save for her guards, none of whom were likely to indulge her in conversation. She looked up at Proft's approach, abandoning what looked like the rapt contemplation of a spider that was making its way across the wall. "Consumed by fellow-feeling?" he asked. "We're nothing alike, the spider and I," she said. "It can leave whenever it desires. No one punishes it for following its nature. No one imprisons it. It does as it likes, and always shall." "Until someone smashes it flat." "I suppose. Come to gloat, have you? The victor reveling in his conquest?" "I want to," he admitted. "It has brought me pleasure in the past, the gloating. Gloating is the glass of bumbat the soul consumes when it succeeds. But this time … there are too many things I still can't explain. Too many little inconsistencies, too many unanswered questions. I know your reputation." Etrata stared at him, apparently bewildered by his sudden change of directions. "Many people do. Your point?" "My point would be, the people who know about you speak #emph[very] highly of your skills. You're supposedly one of the best that House Dimir has to offer, the cream of their crop, as it were. Please, for the sake of my unsettled thoughts, will you tell me why you chose to kill such a prominent target in such a public way? Not to mention the theatrics surrounding the body. You had plenty of time to commit the murder and make your escape, but you remained on the grounds even before the wards were raised to prevent your exit. That isn't the work of a professional. Why commit such a grievous crime in such a manner and not make your escape while you could?" #figure(image("003_Episode 3: Shadows of Regret/02.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Etrata looked at him, unblinking. "That's not what you really want to know, is it?" Her tone was mild; her words acid-tipped and unforgiving. "Ask the real question, #emph[Detective] ." Somehow, she turned his title into an insult. Proft was unfazed. "How were you able to trick the verity circles during your interview? If they've been defeated, the guilds need to know." "Aw, worried about losing one of your tools against the criminal underworld?" Etrata mimed wiping away a tear. "However would Ravnica survive without your little parlor tricks?" "Please." Etrata paused, briefly taken aback by the sincerity in his tone. He went on. "You've been caught. I'm not asking you to give away the secrets of your house; I'll have nothing to do with your trial or sentencing. But the city is already splintered enough. There's no trust lost between the individual guilds, or between the guilds and the citizens. We need to know that the verity circles—that #emph[something] in this city—can be trusted." Etrata looked away. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Kaya walked back to her rented room with her head down and her shoulders tight, hating the feeling of eyes on her skin, hating the feeling of isolation from a city that should have been hers, that had been hers for so long. Gods and monsters; she was ready to go. This place wasn't her home anymore. Maybe it had never been her home in the first place. A courier in Orzhov colors stood outside the rental house, young enough to have only the faintest blush of stubble painting his cheeks, glancing anxiously around as he waited. When he saw Kaya, he brightened and hurried toward her, quick and awkward, almost stumbling over his own feet. "Master Planeswalker," he said, once he was close enough to address her without shouting. Even as she inwardly winced at the address, Kaya supposed it made sense. She wasn't a guildmaster anymore, and the normal honorifics for a former Orzhov guild leader didn't apply to her, since she wasn't dead, either. Addressing her without respect could have been taken as a grave insult, and in the absence of any other role on Ravnica, he had defaulted to the one he knew. It was the safest choice. She didn't have to like it. "Yes?" she asked. "Guildmaster Karlov requests your presence at the manor." "Guess I'm just popular today." The courier blinked at her, clearly confused. "Pardon?" "Nothing. Never mind. Just let me get something from my room. Did she give you any additional messages for me?" "This," he said, producing a sealed note from inside his pocket and offering it to her with a small, satisfied nod. He had done his job, and as soon as she took the letter, he could go. Kaya took the note, not breaking the seal as she tucked it into her shirt. "Will you be escorting me?" "She said you would know the way." "She was right about that." Another method of avoiding insulting her. She was so tired of Ravnican manners. When she was done here, maybe she could go to Kaldheim for a while, where no one was worried about insulting anyone else, unless it was with a fist to the face. Or Innistrad. Far less etiquette and propriety involved. "Well, thank you for finding me so quickly." She produced a coin from her pocket and passed it to the courier, who surreptitiously checked the value before he made it disappear. "Thank you kindly," he said and emulated the coin as he vanished into a nearby alley. Kaya shook her head in reluctant fondness before making her way inside. She needed to change her shirt before she went to the manor. Manners again, but propriety must be observed. While in the privacy of her room, she broke the seal on Teysa's note and opened it. #emph[It's time for the discussion we couldn't have during the gala. I'm so sorry it's taken this long. It's not safe for me to write anything down. Please come at once. Come alone.] #emph[Thank you for staying. I know you did it for my sake, more than Ravnica's, and I appreciate it more than you can know.] #emph[Your friend, after everything,] #emph[Teysa] Teysa's signature was a nasty scrawl. Kaya frowned as she concealed the note beneath her pillow, quickly changed her clothes, and left. Time to head for the manor. Time to finish this. No one stopped her as she hurried through the streets to Karlov Manor, and she found the gates already unlocked for her, the wards having been adjusted to allow her passage. The walk up the driveway seemed like the most intolerable part of her journey, needlessly long, designed only to impress and intimidate. As if the manor weren't impressive enough entirely on its own merits. The topiary alone would send most thieves running, and the building seemed to loom, watching every step she took. Kaya continued onward into the house, which had been left unlocked for her arrival. She looked around, half expecting Teysa to be waiting for her, but saw no sign of the other woman, or of her staff. The manor was eerily quiet, with no one in attendance or rushing to announce her. Feeling a strange tightness in her stomach, Kaya started up the stairs. Teysa wouldn't want to have this meeting in one of the public areas of the house, or on the balcony; anything too important to be written down would be left for her private quarters, the rooms she reserved for herself alone. She had a parlor there, small and elegant, outfitted for meetings of precisely this type. Kaya knew her well enough to be certain she would find her there. The strange silence and stillness persisted as she made her way along the hall. Teysa must have sent the staff away before this meeting. Whatever she had to discuss, she wanted absolutely no risk that they'd be overheard. The door to Teysa's private parlor stood slightly ajar. Kaya moved toward it, hesitating for an instant when she caught the scent of blood in the air. That hesitation was more than balanced by the speed with which she threw herself at the door and into the room beyond, where she stopped, clapping a hand over her mouth to contain the scream she could feel building in her chest, and simply stared. Teysa was there, sprawled on the floor next to the desk where she received visitors. She had been waiting for Kaya: that much was clear. Her eyes were still open, staring blankly at the ceiling, and the shattered shaft of her walking stick protruded from her chest, slick with blood. More of that same blood stained her hands, where she had tried to pull the makeshift spear out before she bled to death. Teysa was gone. Knees threatening to buckle and drop her to the floor, Kaya staggered into the room, heading for the body of her friend. Death wasn't the end, not for the Orzhov, but Teysa, for all her entanglements with the dead, had always been one of the most vitally #emph[alive] people Kaya knew. And all that was over now. Another friend gone. Another body to bury. #figure(image("003_Episode 3: Shadows of Regret/03.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Something crunched under Kaya's foot, stopping her. She looked down. One of the elegant maiden statues Teysa kept on display in the parlor had been knocked over in whatever altercation happened here and lay in pieces. That felt like a desecration of Teysa's space to accompany the desecration of her body, and looking at it seemed easier than looking at her friend's body. Kaya knelt, beginning to collect the ceramic shards. A piece of paper was buried among the mess. Kaya frowned, setting what she'd gathered aside as she picked it up carefully then froze again, her chest tightening as the world narrowed to a single point. She could hear her heart hammering in her ears, the rushing of her blood like the sound of a distant sea, and if it hadn't been for Teysa's wards, she would have dropped straight through the floor, losing control of her phasing in the face of her panic. The writing was clearly Teysa's. Kaya knew the little smear at the bottom of each line. The script, however … The script was Phyrexian. Kaya breathed harder and harder, hand closing convulsively around the note and wrinkling it. She couldn't leave. Teysa was dead, Teysa might have been working with Phyrexia, and she couldn't leave. She had to go back to Ezrim. She had to tell him she was in this after all. She always had been. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "I didn't," said Etrata. Proft frowned. "But when you were questioned within the verity circle, you said you didn't kill her." "Because I didn't." Etrata tilted her head back until it hit the wall. "I snuck into the party because House Dimir needed #emph[someone] to be our eyes, and it seemed like an amusing evening. I had no targets. I had no assignments. I had a plate of those meat-filled pastries with the cheese on top. They were lovely." Proft made a frustrated sound. "Didn't you get to try them? I'm sorry." Etrata seemed to decide to stop toying with him then. She sighed and said, "If I killed her, I don't remember it. I didn't come there to kill anyone, and I don't assassinate for free." "You didn't …" Proft paused, mind whirling. Ravnican law was very clear: if mind control or magic had been used to force Etrata's actions, she was no more culpable than a knife. She might be the weapon, but she wasn't the killer. The case remained open. The puzzle remained unsolved. "Will you help me clear your name?" Etrata looked at him. "The guilds need their pound of flesh. There is no clearing my name." "Swear you'll help me," said Proft insistently. "You can't fix this." "I am Alquist Proft, and I will risk my name to clear yours. Now swear." Etrata blinked, then frowned. "As much as I can, you have my word." "Then come, we have work to do." He made a few simple motions, twisting his fingers through the air, and the lock on her cell sprang open with a click. "Pff. Only a quadroanarchic theory-lock? They're getting sloppy." He straightened his cufflinks. "You're a trained assassin. You can get out of here without being seen." Slowly, her frown became a smile. "And where am I going?" "My home," he said and gave her the address. "I'll see you there." Etrata nodded before stepping out of the cell and melting into the shadows. Proft turned to go, fixing a look of irritation on his face. "I was promised a prisoner," he said loudly, striding toward the door. "Not an empty cell." The chaos that followed would allow them both to make their exits.
https://github.com/Functional-Bus-Description-Language/Specification
https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/functionalities/return.typ
typst
== Return The return functionality is an inner functionality of the proc and stream functionalities. It represents data returned by a procedure or streamed by an upstream. The return functionality has following properties: *`width`*` integer (bus width) {definitive}` #pad(left: 1em)[ The width property defines the bit width of the return. ] The following example presents the definition of a procedure returning four element byte array, and a single bit flag indicating whether the data is valid. #block(breakable: false)[ #pad(left: 1em)[ ```fbd Read_Data proc data [4]return; width = 8 valid return; width = 1 ``` ] ]
https://github.com/janlauber/bachelor-thesis
https://raw.githubusercontent.com/janlauber/bachelor-thesis/main/chapters/methodology.typ
typst
Creative Commons Zero v1.0 Universal
= Methodology This section details how the One-Click Deployment system was developed, focusing on the research design, development approach, and the tools and technologies used. By adopting a structured and comprehensive methodology, we aimed to address the complex challenges of OSS deployment effectively. == Research Design To understand the OSS deployment landscape and evaluate our system's effectiveness, we used a combination of different research methods: - *Current Landscape Analysis*: We began by analyzing the current landscape of OSS deployment. This involved looking at existing tools, technologies, and methods used in the industry to identify common challenges and gaps. - *Case Studies*: We examined several OSS projects to understand their deployment processes. These case studies provided insights into the practical issues faced during deployment and the solutions adopted to overcome them. - *Prototype Evaluation*: A prototype of the One-Click Deployment system was created and tested by users. Feedback from these sessions was crucial in assessing the system's usability, effectiveness, and overall user satisfaction, guiding further development. == Development Approach The development of the One-Click Deployment system followed an iterative and agile methodology, which allowed us to be flexible and responsive to user feedback: - *Requirement Analysis*: Initial requirements were gathered based on our analysis of the current landscape and feedback from the case studies. These requirements helped shape the design and development of the system. - *Prototype Development*: We developed a minimum viable product (MVP) to showcase the core functionalities of the One-Click Deployment system. This MVP was essential for initial user testing and feedback. - *Iterative Development and Testing*: The system underwent multiple iterations of development and testing. After each iteration, user feedback was collected and used to refine features, improve usability, and add new functionalities. - *User-Centered Design*: Throughout the development process, a user-centered design approach was adopted. Regular user testing sessions and feedback loops ensured that the system was intuitive and met user needs. == Tools and Technologies Used The development of the One-Click Deployment system utilized a range of tools and technologies, selected for their efficiency, robustness, and compatibility with OSS deployment requirements. - *Kubernetes #footnote[https://kubernetes.io/]*: As the backbone of the system, Kubernetes was used for orchestrating container deployment, scaling, and management. - *Docker #footnote[https://docker.com]*: Docker was employed for containerizing applications, ensuring consistency across different deployment environments. - *Operator SDK #footnote[https://sdk.operatorframework.io/]*: The Operator SDK facilitated the development of the Kubernetes operator, a key component of the system that automates the deployment and management processes. - *Svelte #footnote[https://svelte.dev/] and Pocketbase #footnote[https://pocketbase.io]*: The frontend of the system was developed using Svelte, a modern framework for building web applications, while Pocketbase served as the backend database and API server. - *Git #footnote[https://git-scm.com/] and GitHub #footnote[https://git-scm.com/]Hub*: Git was used for version control, with GitHub hosting the project's code repository and facilitating collaboration among developers. - *CI/CD Tools*: Continuous Integration and Continuous Deployment were achieved using tools like GitHub Actions, automating the testing and deployment of code changes. By leveraging these tools and technologies, the One-Click Deployment system aims to provide a simplified, efficient, and scalable solution for OSS deployment, addressing the identified challenges and gaps in the current ecosystem. #pagebreak() == Open Source Availability The One-Click Deployment system is completely open source and is available under the Apache 2.0 #footnote[https://apache.org/licenses/LICENSE-2.0] license. The source code can be accessed through the following GitHub repositories: - *One-Click Kubernetes Operator*: #link("https://github.com/janlauber/one-click-operator") - *One-Click Main Application*: #link("https://github.com/janlauber/one-click") - *One-Click Documentation*: #link("https://github.com/janlauber/one-click-docs") By leveraging these tools and technologies, and making the system open source, we aim to provide a robust, efficient, and accessible solution for OSS deployment. This system simplifies the deployment process, making it accessible to a broader audience and addressing the key challenges identified in our research.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.3.1/src/version.typ
typst
Apache License 2.0
#let version = version(0,3,1)
https://github.com/wumin199/wumin199.github.io
https://raw.githubusercontent.com/wumin199/wumin199.github.io/main/source/_posts/2023/tools.md
markdown
--- title: 工欲善其事 date: 2023-03-09 21:48:52 tags: 工具 toc: true password: <PASSWORD> comment: false widgets: - type: toc position: right index: true collapsed: false depth: 3 --- 必先利其器 <!-- more --> ## 音视频 - [Abobo](http://www.aboboo.com/g/#/home) - 支持对语音、视频进行复读 - [金舟文字语音转换软件](https://www.callmysoft.com/yuyinzhuanhuan) - 需开通会员(已是会员) - 文字转语音,中英文都可以 -> 效果还可以 - 可用于中英文单词、句子、段落等的复读学习 - 也可以语音/视频转文字(效果未测试) -> 效果还行 - [讯飞听译](https://www.iflyrec.com/zhuanwenzi.html) - 付费,在线语音转文字,对英文语音识别比较好 - [有道智云](https://ai.youdao.com/#/) - 付费,用的其中的api功能,藤萝英语用到 - [ACONVERT](https://www.aconvert.com/) - 在线视频转音频 - 同时支持音频、视频格式转换 - [123apps](https://123apps.com/cn/) - 在线音频视频转换软件 - 各类下载 - [各平台视频下载](https://youtube.iiilab.com/)(bili/twitter/youtube/ins) - [YouTubeDownloader](https://en.savefrom.net/383/) - [YouTube字幕下载](https://downsub.com/) --- ## 图片 - [GitHub Proxy](https://ghproxy.com/) - [Linux下如何简单拼接图片:ImageMagick](https://www.mintos.org/soft/combine-pictures.html) ``` powershell # 横轴拼接 convert 01.jpg 02.jpg +append 11.jpg # 众轴拼接 convert 01.jpg 02.jpg -append 22.jpg ``` ## 办公 - [ILovePDF](https://www.ilovepdf.com/) - pdf提取、合并、转换 - [AnyTXT Searcher](https://anytxt.net/) - AnyTXT Searcher 是一款免费、功能强大的本地文档和文本搜索应用程序,无需安装任何其他软件即可提取常用文档的文本,快速找到计算机上存在的任何单词 - 使用方法 - 打开AnyTXT Searcher,在搜索框输入关键字。 - 单击搜索框右侧“+”,修改搜索范围和搜索的文件类型。默认情况下,AnyTXT Searcher搜索本地磁盘的全部文件类型。 - 单击“开始”。 - 单击任一搜索结果,可预览匹配的文字片段。可在预览窗口中选择任意字词,右键选择“翻译”,即可调用谷歌或必应翻译。也可在预览窗口下方的搜索框中输入其他关键字,在该文件中进一步搜索。 - [Everything](https://www.voidtools.com/zh-cn/) - 查找文件名称 - [Snipaste](https://zh.snipaste.com/) - 截图软件,目前只有windows - Snipaste适用于截小图标和简单的图片标注 - [PicPick](https://picpick.app/zh/) - 截图软件,只有windows - PicPick适用于截大图和复杂的图片标注 - [ZLibrary](https://singlelogin.me/) - [Personal domain](https://lib-igucbsbsfx5cpiy3gvzjgci2.must.wf/) - [Markdown Tables](https://www.tablesgenerator.com/markdown_tables#) - [typst](https://typst.app/) - [Tutorial](https://typst.app/docs/tutorial/) - [Ref > Math](https://typst.app/docs/reference/math/), [Ref > Syntax](https://typst.app/docs/reference/syntax/#math), [Ref -> Symbols](https://typst.app/docs/reference/symbols/sym/) - [awesome-typst-cn](https://github.com/typst-cn/awesome-typst-cn) - [在线白板](https://excalidraw.com/) --- ## 其他 - [Clash_For_Windows](https://github.com/Fndroid/clash_for_windows_pkg) - [流量购买](https://beta.yahagi.vip/user)(多刷几次可以登录上去) - [设置方法](https://www.zrzz.site/posts/5760e5b0/) ![](/images/2023/net_work_setting.png) ``` localhost, 127.0.0.1/8, ::1 ``` - 建议经常更新profile或者重新下载 - [ChatGPT](https://chat.openai.com/chat) - 注册要点:Clash要把代理设置为韩国,日本,新加坡,或者美国;香港不行 - [OpenAI API](https://platform.openai.com/account/api-keys) - [ChatGPT中文版](https://marketplace.visualstudio.com/items?itemName=WhenSunset.chatgpt-china) - [GPT Prompts](https://github.com/f/awesome-chatgpt-prompts) - ChatGPT Plus付费:需要切换IP到其他国家,然后用国外信用卡付费 -> 找人代充 - [Unofficial ChatGPT Desktop](https://github.com/lencx/ChatGPT/releases) - copilot/cursor - [虚拟手机号码](https://sms-activate.org/cn) - [猎聘HR](https://h.liepin.com/account/login)(不要用国外ip地址,会被封号)
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-数据结构/字符串/外观数列.typ
typst
#import "../../../../lib.typ":* === #Title( title: [外观数列], reflink: "https://leetcode.cn/problems/count-and-say/description/", level: 2, )<外观数列> #note( title: [ 外观数列 ], description: [ 「外观数列」是一个数位字符串序列,由递归公式定义: countAndSay(1) = "1" countAndSay(n) 是 countAndSay(n-1) 的行程长度编码。 行程长度编码(RLE)是一种字符串压缩方法,其工作原理是通过将连续相同字符(重复两次或更多次)替换为字符重复次数(运行长度)和字符的串联。例如,要压缩字符串 "3322251" ,我们将 "33" 用 "23" 替换,将 "222" 用 "32" 替换,将 "5" 用 "15" 替换并将 "1" 用 "11" 替换。因此压缩后字符串变为 "23321511"。 给定一个整数 n ,返回 外观数列 的第 n 个元素。 ], examples: ([ 输入:n = 4 输出:"1211" 解释: countAndSay(1) = "1" countAndSay(2) = "1" 的行程长度编码 = "11" countAndSay(3) = "11" 的行程长度编码 = "21" countAndSay(4) = "21" 的行程长度编码 = "1211" ],[ 输入:n = 1 输出:"1" 解释: 这是基本情况。 ] ), tips: [ - $1 <= n <= 30$ ], solutions: ( ( name:[遍历生成], text:[ 1. 初始化字符串 `ans` 为 "1"。 2. 从2到n依次生成每一项报数序列: - 对当前的 `ans` 字符串,计算其报数结果。具体步骤如下: - 初始化一个空字符串 `cur`,用于存放当前项的报数结果。 - 遍历 `ans` 字符串,使用双指针来计数连续相同的字符数量。 - 当字符不相同时,将计数结果和字符追加到 `cur` 中。 - 将 `cur` 更新为新的 `ans`。 3. 最终返回 `ans`。 ],code:[ ```cpp class Solution { public: string countAndSay(int n) { string ans = "1"; // 初始值为 "1" for (int i = 2; i <= n; i++) { // 从第2项开始生成,直到第n项 string cur = ""; // 用于存放当前项的报数结果 for (int j = 0; j < ans.size(); j++) { // 遍历当前的 ans 字符串 int cnt = 1; // 计数器,统计相同字符的数量 // 统计相同字符的数量 while (j + 1 < ans.size() && ans[j] == ans[j + 1]) { j++; cnt++; } // 将计数结果和字符追加到 cur 中 cur += to_string(cnt) + ans[j]; } ans = cur; // 更新 ans 为当前项的报数结果 } return ans; // 返回第n项的报数结果 } }; ``` ]), ), gain:none, )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-25.typ
typst
Other
// Error: 10-24 the result is not a real number #calc.log(10, base: -1)
https://github.com/Nrosa01/TFG-2023-2024-UCM
https://raw.githubusercontent.com/Nrosa01/TFG-2023-2024-UCM/main/Memoria%20Typst/capitulos/1.Introduccion.typ
typst
== Motivación Los simuladores de arena fueron un subgénero emergente durante la década de los noventa, y continuaron siendo populares hasta principios de los años 2000. Durante ese tiempo, surgieron muchos programas y juegos que permitían a la gente interactuar con mundos virtuales llenos de partículas simuladas. Esto atrajo tanto a amantes de la simulación como a desarrolladores de videojuegos. Sin embargo, tras un período de relativa tranquilidad, estamos presenciando un nuevo auge del género de la mano de videojuegos como Noita o simuladores sandbox como Sandspiel. Este proyecto nace del deseo de sumergirnos en el mundo de los simuladores de arena. Queremos explorar sus diferentes aspectos y características así como entender mejor las ventajas y desventajas de diferentes enfoques de desarrollo de cara al usuario, para así poder contribuir a su evolución y expansión, ya que consideremos que es un subgénero que puede dar muy buenas experiencias de juego y de uso. En resumen, queremos entender y ayudar a mejorar los simuladores de arena para hacerlos más útiles y efectivos para los usuarios. == Objetivos <Objetivos> El principal objetivo de este TFG es estudiar el comportamiento y aprendizaje de usuarios haciendo uso de diferentes implementaciones de simuladores de arena. Se valorará la funcionalidad de cada implementación haciendo uso de los siguientes parámetros: - Comparación de rendimiento: se compararán bajo las mismas condiciones, tanto a nivel de hardware como en uso de partículas midiendo el rendimiento final conseguido. Este rendimiento se comparará haciendo uso de razón nº partículas / frames por segundo conseguidos. Idealmente se averiguará la mayor cantidad de partículas que cada simulador puede soportar manteniendo 60 fps. - Comparación de usabilidad: se estudiará el comportamiento de un grupo de usuarios para valorar la facilidad de uso y de entendimiento de sistemas de ampliación de los sistemas que permitan expansión por parte del usuario. Se valorará la rapidez para realizar un set de tareas asi como los posibles desentendimientos que puedan tener a la hora de usar el sistema. Con estos análisis, se pretende explorar las características que contribuyen a una experiencia de usuario óptima en un simulador de arena, tanto en términos de facilidad de uso como de rendimiento esperado por parte del sistema. Al comprender mejor estas características, se podrán identificar áreas de mejora y desarrollar recomendaciones para optimizar la experiencia general del usuario con los simuladores de arena. Nuestro objetivo es encontrar un balance entre rendimiento y facilidad de extensión que proporcione tanto un entorno lúdico a usuarios casuales como una base sólida de desarrollo para desarrolladores interesados en los simuladores de arena. == Plan de trabajo La metodología de trabajo a usar será una variante de scrum ajustada a nuestras necesidades. Se elaborará un tablero de tareas en el que se reflejarán las tareas a realizar, el estado de cada tarea y el tiempo estimado para su realización. No habrá reuniones diarias pero se fijarán tareas a realizar cada semana, así como reuniones semanales para revisar el estado del proyecto y ajustar el tablero de tareas en consecuencia. Por otro lado, se planean reuniones cada dos semanas con el tutor para revisar el estado del proyecto y recibir feedback sobre el trabajo realizado, así como orientación al respecto de las tareas a realizar en el futuro. Respecto al trabajo, lo primero será realizar una investigación preliminar sobre los conceptos fundamentales de los autómatas celulares y los simuladores de arena, así como de sistemas ya existentes para entender cómo se han abordado problemas en el pasado. Se espera que esta investigación dure aproximadamente dos meses. Tras esto se planea la realización de 4 implementaciones: - Simulación nativa base: Esta será la simulación usada de base para comparar las demás. Debe ser eficiente y sentar las bases de como se realiza el procesado de partículas. Esta implementación será difícil de ampliar debido a esto. Se espera realizar esta implementación en C o C++ debido a la familiaridad con el lenguaje. Se espera que esta implementación sea realizada entre un mes y un mes y medio. - Simulación en GPU: Esta implementación se realizará en un lenguaje de programación que permita la ejecución de código en GPU, como CUDA u OpenCL. El objetivo de esta implementación es explorar la viabilidad de realizar la simulación de partículas en GPU, así como comparar el rendimiento con las demás implementaciones. Se espera que esta implementación también sea difícil de ampliar. Se espera realizar esta implementación en un mes. - Simulación nativa ampliada con un lenguaje de script: Será necesario investigar y elegir un lenguaje de script que permita la ampliación de la simulación base de manera sencilla manteniendo el mayor rendimiento posible. Se espera realizar esta implementación entre uno y dos meses. - Simulación accesible mediante lenguaje de programación visual: Se investigarán librerías y frameworks que permitan definir código o datos mediante programación visual. Se espera que esta implementación sea la más sencilla de ampliar y la más accesible para usuarios no técnicos. Se investigará la posibilidad de ejecutar esta simulación en la web para mayor accesibilidad. Se espera realizar esta implementación entre uno y dos meses. Se considera la posibilidad de que se realicen más simuladores si la investigación da a conocer una posibilidad alternativa que aporte valor a la comparativa. Tras realizar las distintas implementaciones, se realizarán pruebas de usuario para comparar los resultados obtenidos por cada una de ellas. Se analizarán los datos obtenidos y se compararán los resultados para extraer conclusiones sobre las ventajas y desventajas de cada implementación. Se espera realizar estas pruebas en un periodo de dos a tres semanas. == Enlaces de interés Repositorio del proyecto: https://github.com/Nrosa01/TFG-2023-2024-UCM Simulación base en C++: https://youtu.be/Z-1gW8dN7lM Simulación en GPU: https://youtu.be/XyaOdjyOXFU Simulación con Lua: https://youtu.be/ZlvuIUjA7Ug Simulación web con Blockly: https://youtu.be/obA7wZbHb9M
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S5/AMT/docs/4-JDBCandJPA/jdbc.typ
typst
#import "/_settings/typst/template-note.typ": conf #show: doc => conf( title: [ Data tier and JDBC ], lesson: "AMT", chapter: "4. JDBC and JPA", definition: "Definition", col: 1, doc, ) = Résumé de l'API JDBC et des pilotes L'API JDBC est une interface Java qui permet aux applications Java d'interagir avec une base de données. Un pilote JDBC est une implémentation de cette API pour un SGBD spécifique. C'est une API de bas niveau qui demande beaucoup de code répétitif. Comprendre JDBC est essentiel en cas de problèmes de performance. == Connexion JDBC Une connexion JDBC est une session avec une base de données qui permet d'exécuter des requêtes SQL et de récupérer les résultats. Le pilote JDBC est chargé automatiquement si le fichier `.jar` du pilote est sur le classpath. Exemple de connexion à une base PostgreSQL : ```java Connection connection = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres" ); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT 1"); while (resultSet.next()) { System.out.println(resultSet.getInt(1)); } ``` = Source de données JDBC Une source de données JDBC est une fabrique de connexions JDBC. Elle est recommandée pour se connecter à une base de données. Exemple de création d'une source de données PostgreSQL : ```java PGSimpleDataSource dataSource = new PGSimpleDataSource(); dataSource.setServerName("localhost"); dataSource.setPortNumber(5432); dataSource.setDatabaseName("postgres"); dataSource.setUser("postgres"); dataSource.setPassword("<PASSWORD>"); ``` = Gestion des ressources Le nombre de connexions étant limité, il est important de libérer les connexions inutilisées. Les classes Connection, Statement et ResultSet implémentent l'interface AutoCloseable, ce qui permet d'utiliser l'instruction try-with-resources. ```java try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT 1")) { while (resultSet.next()) { System.out.println(resultSet.getInt(1)); } } catch (SQLException e) { // Gestion de l'erreur } ``` = Pool de connexions Le pool de connexions permet de réutiliser des connexions existantes pour éviter les coûts d'ouverture/fermeture fréquents. HikariCP et Apache DBCP sont des bibliothèques populaires pour la gestion de pool de connexions. Voici un exemple de configuration HikariCP : ```java HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:postgresql://localhost:5432/postgres"); config.setUsername("postgres"); config.setPassword("<PASSWORD>"); config.setMaximumPoolSize(10); DataSource dataSource = new HikariDataSource(config); ``` Bien que le pool de connexions optimise la gestion des connexions, il ne résout pas tous les problèmes, et dans certains cas, cela peut entraîner des blocages ou des "deadlocks".
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/goto_definition/label.typ
typst
Apache License 2.0
// compile:true #set heading(numbering: "1.") = Labeled <title_label> /* position after */ @title_label
https://github.com/jamesrswift/frackable
https://raw.githubusercontent.com/jamesrswift/frackable/main/README.md
markdown
The Unlicense
# The `frackable` Package <div align="center">Version 0.2.0</div> Provides a function, `frackable(numerator, denominator, whole: none)`, to typeset vulgar and mixed fractions. Provides a second `generator(...)` function that returns another having the same signature as `frackable` to typeset arbitrary vulgar and mixed fractions in fonts that do not support the `frac` feature. ```typ #import "@preview/frackable:0.2.0": * #frackable(1, 2) #frackable(1, 3) #frackable(3, 4, whole: 9) #frackable(9, 16) #frackable(31, 32) #frackable(0, "000") ``` ![plot](./example.png)
https://github.com/sitandr/typst-examples-book
https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/snippets/layout/duplicate.md
markdown
MIT License
# Duplicate content <div class="warning"> Notice that this implementation will mess up with labels and similar things. For complex cases see one below. </div> ```typ #set page(paper: "a4", flipped: true) #show: body => grid( columns: (1fr, 1fr), column-gutter: 1cm, body, body, ) #lorem(200) ``` ## Advanced ```typ /// author: frozolotl #set page(paper: "a4", flipped: true) #set heading(numbering: "1.1") #show ref: it => { if it.element != none { it } else { let targets = query(it.target, it.location()) if targets.len() == 2 { let target = targets.first() if target.func() == heading { let num = numbering(target.numbering, ..counter(heading).at(target.location())) [#target.supplement #num] } else if target.func() == figure { let num = numbering(target.numbering, ..target.counter.at(target.location())) [#target.supplement #num] } else { it } } else { it } } } #show link: it => context { let dest = query(it.dest) if dest.len() == 2 { link(dest.first().location(), it.body) } else { it } } #show: body => context grid( columns: (1fr, 1fr), column-gutter: 1cm, body, { let reset-counter(kind) = counter(kind).update(counter(kind).get()) reset-counter(heading) reset-counter(figure.where(kind: image)) reset-counter(figure.where(kind: raw)) set heading(outlined: false) set figure(outlined: false) body }, ) #outline() = Foo <foo> See @foo and @foobar. #figure(rect[This is an image], caption: [Foobar], kind: raw) <foobar> == Bar == Baz #link(<foo>)[Click to visit Foo] ```
https://github.com/mitex-rs/mitex
https://raw.githubusercontent.com/mitex-rs/mitex/main/CONTRIBUTING.md
markdown
Apache License 2.0
# Contributing to MiTeX ## Installing Dependencies You should install [Typst](https://github.com/typst/typst?tab=readme-ov-file#installation) and [Rust](https://www.rust-lang.org/tools/install) for running the build script. If you want to build the WASM plugin, you should also setup the wasm target by rustup: ```sh rustup target add wasm32-unknown-unknown ``` ## Build For Linux: ```sh git clone https://github.com/mitex-rs/mitex.git scripts/build.sh ``` For Windows: ```sh git clone https://github.com/mitex-rs/mitex.git .\scripts\build.ps1 ``` ## Fuzzing (Testing) The [afl.rs] only supports Linux. Installing [afl.rs] on Linux: ```bash cargo install cargo-afl ``` Building and fuzzing: ```bash cargo afl build --bin fuzz-target-mitex cargo afl fuzz -i local/seed -o local/fuzz-res ./target/debug/fuzz-target-mitex ``` To minimize test cases, using `afl-tmin` ```bash cargo afl tmin -i crash.tex -o minimized.tex ./target/debug/fuzz-target-mitex ``` ## Documents TODO. [afl.rs]: https://github.com/rust-fuzz/afl.rs
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/rounding/round-zero-positive/test.typ
typst
Apache License 2.0
#import "/src/lib.typ": * #set page(width: auto, height: auto, margin: 1cm) #metro-setup(round-mode: "places") #num(-0.001) #metro-setup(round-zero-positive: false) #num(-0.001)
https://github.com/crystalmaterial/typst
https://raw.githubusercontent.com/crystalmaterial/typst/main/template.typ
typst
Creative Commons Zero v1.0 Universal
#let script-size = 8pt #let footnote-size = 8.5pt #let small-size = 10pt #let normal-size = 13pt #let large-size = 15pt // task #let task(body, critical: false) = { set text(red) if critical [- #body] } // formula function #let formula(body, numbered: true) = figure( body, kind: "formula", supplement: [formula], numbering: if numbered { "1" }, ) // footnote #let footnote(n) = { let s = state("footnotes", ()) s.update(arr => arr + (n,)) locate(loc => super(str(s.at(loc).len()))) } #let has_notes(loc) = { state("footnotes", ()).at(loc).len() > 0 } #let print_footnotes(loc) = { let s = state("footnotes", ()) enum(tight: true, ..s.at(loc).map(x => [#x])) s.update(()) } // DOCUMENT #let article( title: "defined-into-document", // The article's title. subtitle: "defined-into-document", authors: (), // An array of authors. For each author you can specify a name, department, organization, location, and email. Everything but the name is optional. abstract: none, // Your article's abstract. Can be omitted if you don't have one. paper-size: "a4", // The article's paper size. Also affects the margins. bibliography-file: none, // The path to a bibliography file if you want to cite some external works. // The document's content. body, ) = { // Formats the author's names in a list with commas and a final "and". let names = authors.map(author => author.name) let author-string = if authors.len() == 2 { names.join(" and ") } else { names.join(", ", last: ", and ") } // Set document metdata. set document(title: title, author: names) // Set the body font. set text(size: normal-size, font: "New Computer Modern") // Configure the page. set page( paper: paper-size, // The margins depend on the paper size. margin: if paper-size != "a4-paper" { ( top: (116pt / 279mm) * 80%, left: (126pt / 216mm) * 80%, right: (128pt / 216mm) * 80%, bottom: (94pt / 279mm) * 80%, ) } else { ( top: 117pt, left: 118pt, right: 119pt, bottom: 96pt, ) }, // The page header should show the page number and list of authors, except on the first page. The page number is on the left for even pages and on the right for odd pages. header-ascent: 14pt, header: locate(loc => { let i = counter(page).at(loc).first() if i == 1 { return } set text(size: script-size) grid( columns: (6em, 1fr, 6em), if calc.even(i) [#i], align(center, upper( if calc.odd(i) { title } else { title } )), if calc.odd(i) { align(right)[#i] } ) }), // On the first page, the footer should contain the page number. footer-descent: 12pt, footer: locate(loc => { let i = counter(page).at(loc).first() if i == 1 { align(center, text(size: script-size, [#i])) } }) ) // Configure headings. set heading(numbering: "1.") show heading: it => { // Create the heading numbering. let number = if it.numbering != none { counter(heading).display(it.numbering) h(7pt, weak: true) } // Level 1 & 2 : smallcaps. Others : bold, without numbers set text(size: normal-size, weight: 400) if it.level == 1 or it.level == 2 { set text(size: 13pt) smallcaps[ #v(18pt, weak: true) #number #it.body #v(normal-size, weak: true) ] // counter(figure.where(kind: "formula")).update(0) } else { set text(size: 13pt) v(18pt, weak: true) // number let styled = if it.level == 3 { strong } else { emph } styled(it.body + [. ]) h(7pt, weak: true) } } // Configure lists and links. set list(indent: 24pt, body-indent: 5pt) set enum(indent: 24pt, body-indent: 5pt) show link: set text(font: "New Computer Modern Mono") // Configure citation and bibliography styles. set cite(style: "numerical", brackets: true) set bibliography(style: "apa", title: "References") // figures and formulas styles show figure.where(kind: "figure"): it => { show: pad.with(x: 23pt) set align(center) v(12.5pt, weak: true) // Display the figure's body. it.body // Display the figure's caption. if it.has("caption") { // Gap defaults to 17pt. v(if it.has("gap") { it.gap } else { 17pt }, weak: true) smallcaps[Figure] if it.numbering != none { [ #counter(figure).display(it.numbering)] } [. ] it.caption } v(15pt, weak: true) } show figure.where(kind: "formula"): it => align(center, block( above: 20pt, below: 18pt, { emph(it.body) v(if it.has("gap") { it.gap } else { 17pt }, weak: true) [(] if it.numbering != none { //counter(heading).display() it.counter.display(it.numbering) } [)] } )) // Display the title and authors. v(35pt, weak: true) align(center, upper({ v(50pt, weak: true) text(size: large-size, weight: 700, title) v(25pt, weak: true) text(size: footnote-size, subtitle) v(50pt, weak: true) })) align(center, for author in authors { let keys = ("title", "name") let dept-str = keys .filter(key => key in author) .map(key => author.at(key)) .join(", ") smallcaps(dept-str) linebreak() v(12pt, weak: true) } ) // Configure paragraph properties. set par(first-line-indent: 0em, justify: true) show par: set block(spacing: 0.9em, below:14.0pt) // Display the abstract if abstract != none { v(50pt, weak: true) set text(script-size) show: pad.with(x: 35pt) smallcaps[Abstract. ] abstract } // Display the article's contents. v(29pt, weak: true) body // Display the bibliography, if any is given. if bibliography-file != none { show bibliography: set text(8.5pt) show bibliography: pad.with(x: 0.5pt) bibliography(bibliography-file) } // The thing ends with details about the authors. show: pad.with(x: 11.5pt) set par(first-line-indent: 0pt) set text(7.97224pt) for author in authors { let keys = ("department", "organization", "location") let dept-str = keys .filter(key => key in author) .map(key => author.at(key)) .join(", ") smallcaps(dept-str) linebreak() if "email" in author [ _Email address:_ #link("mailto:" + author.email) \ ] if "url" in author [ _URL:_ #link(author.url) ] v(12pt, weak: true) } }
https://github.com/tingerrr/masters-thesis
https://raw.githubusercontent.com/tingerrr/masters-thesis/main/src/figures/tables.typ
typst
#import "/src/util.typ": * #import "util.typ": * #let t4gl-analogies = table(columns: 2, align: left, table.header( i18n(de: [Signatur], en: [signature]), i18n(de: [C++ Analogie], en: [C++ analogy]) ), `T[N] name`, `std::array<T, N>`, `T[U] name`, `std::map<U, T> name`, `T[U, N] name`, `std::map<U, std::array<T, N>> name`, `T[N, U] name`, `std::array<std::map<U, T>, N> name`, align(center)[...], align(center)[...], )
https://github.com/KNnut/neoplot
https://raw.githubusercontent.com/KNnut/neoplot/main/pkg/lib.typ
typst
BSD 3-Clause "New" or "Revised" License
#import "neoplot.typ": exec
https://github.com/daniel-eder/typst-template-jku
https://raw.githubusercontent.com/daniel-eder/typst-template-jku/main/src/template/definitions/programmes.typ
typst
// SPDX-FileCopyrightText: 2023 <NAME> // // SPDX-License-Identifier: Apache-2.0 #let programmes = ( law: "Law" )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/linebreak-link_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #link("https://example.com/(ab") \ #link("https://example.com/(ab)") \ #link("https://example.com/(paren)") \ #link("https://example.com/paren)") \ #link("https://hi.com/%%%%%%%%abcdef") \
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/tuhi-labscript-vuw/0.1.0/template/main.typ
typst
Apache License 2.0
#import "@preview/tuhi-labscript-vuw:0.1.0": tuhi-labscript-vuw, lightgreen, middlegreen #let ornament = align(center + horizon,text(font:"Noto Color Emoji", size: 18pt)[🧉]) #show: tuhi-labscript-vuw.with( experiment: text[cup of tea\ preparation], script: "pre-lab script", illustration: align(center)[#image("figures/tea.jpg", width: 100%)], coursetitle: "preparation of tea", coursecode: "teas101") == overview In this experiment, you’ll be preparing a cup of tea. #lorem(50) #pagebreak() = preamble #lorem(30) == Experimental skills and concepts - Handling of a gaiwan - Mastering brewing times - Water-to-leaf ratio optimisation - Weighing leaves - Rinsing leaves == Maths and Physics - Temperature - Diffusion equation - Catalysis - Fluid dynamics - Heat transfer -- conduction, convection, radiation == Health and safety considerations #lorem(30) - Tetsubin handling - Boiling Water - Stove, hot plate - Pu'er knife - Mycotoxyns - Addiction #ornament #pagebreak() // subsequent pages have numbered sections #set heading(numbering: "1.") = Exploration phase #lorem(100) == first infusion - teaware heated up with 70º water - 4.5g leaves - 100mL water - 70º - 75s == second infusion - 70º water - 20s == third and subsequent infusions - 70º - 50s == final infusion - 90º - 1 minute #pagebreak() // subsequent pages have numbered sections #set heading(numbering: none) = Appendix: basic theory #lorem(50) $ frac(partial c, partial t) = upright(bold(nabla)) dot.op (D upright(bold(nabla)) c - upright(bold(v)) c) + R $ #lorem(30) $ rho frac(upright(D) upright(bold(u)), upright(D) t) = - nabla p + nabla dot.op bold(tau) + rho thin upright(bold(f)) $ #lorem(10) #ornament
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0750.typ
typst
Apache License 2.0
#let data = ( ("ARABIC LETTER BEH WITH THREE DOTS HORIZONTALLY BELOW", "Lo", 0), ("ARABIC LETTER BEH WITH DOT BELOW AND THREE DOTS ABOVE", "Lo", 0), ("ARABIC LETTER BEH WITH THREE DOTS POINTING UPWARDS BELOW", "Lo", 0), ("ARABIC LETTER BEH WITH THREE DOTS POINTING UPWARDS BELOW AND TWO DOTS ABOVE", "Lo", 0), ("ARABIC LETTER BEH WITH TWO DOTS BELOW AND DOT ABOVE", "Lo", 0), ("ARABIC LETTER BEH WITH INVERTED SMALL V BELOW", "Lo", 0), ("ARABIC LETTER BEH WITH SMALL V", "Lo", 0), ("ARABIC LETTER HAH WITH TWO DOTS ABOVE", "Lo", 0), ("ARABIC LETTER HAH WITH THREE DOTS POINTING UPWARDS BELOW", "Lo", 0), ("ARABIC LETTER DAL WITH TWO DOTS VERTICALLY BELOW AND SMALL TAH", "Lo", 0), ("ARABIC LETTER DAL WITH INVERTED SMALL V BELOW", "Lo", 0), ("ARABIC LETTER REH WITH STROKE", "Lo", 0), ("ARABIC LETTER SEEN WITH FOUR DOTS ABOVE", "Lo", 0), ("ARABIC LETTER AIN WITH TWO DOTS ABOVE", "Lo", 0), ("ARABIC LETTER AIN WITH THREE DOTS POINTING DOWNWARDS ABOVE", "Lo", 0), ("ARABIC LETTER AIN WITH TWO DOTS VERTICALLY ABOVE", "Lo", 0), ("ARABIC LETTER FEH WITH TWO DOTS BELOW", "Lo", 0), ("ARABIC LETTER FEH WITH THREE DOTS POINTING UPWARDS BELOW", "Lo", 0), ("ARABIC LETTER KEHEH WITH DOT ABOVE", "Lo", 0), ("ARABIC LETTER KEHEH WITH THREE DOTS ABOVE", "Lo", 0), ("ARABIC LETTER KEHEH WITH THREE DOTS POINTING UPWARDS BELOW", "Lo", 0), ("ARABIC LETTER MEEM WITH DOT ABOVE", "Lo", 0), ("ARABIC LETTER MEEM WITH DOT BELOW", "Lo", 0), ("ARABIC LETTER NOON WITH TWO DOTS BELOW", "Lo", 0), ("ARABIC LETTER NOON WITH SMALL TAH", "Lo", 0), ("ARABIC LETTER NOON WITH SMALL V", "Lo", 0), ("ARABIC LETTER LAM WITH BAR", "Lo", 0), ("ARABIC LETTER REH WITH TWO DOTS VERTICALLY ABOVE", "Lo", 0), ("ARABIC LETTER REH WITH HAMZA ABOVE", "Lo", 0), ("ARABIC LETTER SEEN WITH TWO DOTS VERTICALLY ABOVE", "Lo", 0), ("ARABIC LETTER HAH WITH SMALL ARABIC LETTER TAH BELOW", "Lo", 0), ("ARABIC LETTER HAH WITH SMALL ARABIC LETTER TAH AND TWO DOTS", "Lo", 0), ("ARABIC LETTER SEEN WITH SMALL ARABIC LETTER TAH AND TWO DOTS", "Lo", 0), ("ARABIC LETTER REH WITH SMALL ARABIC LETTER TAH AND TWO DOTS", "Lo", 0), ("ARABIC LETTER HAH WITH SMALL ARABIC LETTER TAH ABOVE", "Lo", 0), ("ARABIC LETTER ALEF WITH EXTENDED ARABIC-INDIC DIGIT TWO ABOVE", "Lo", 0), ("ARABIC LETTER ALEF WITH EXTENDED ARABIC-INDIC DIGIT THREE ABOVE", "Lo", 0), ("ARABIC LETTER FARSI YEH WITH EXTENDED ARABIC-INDIC DIGIT TWO ABOVE", "Lo", 0), ("ARABIC LETTER FARSI YEH WITH EXTENDED ARABIC-INDIC DIGIT THREE ABOVE", "Lo", 0), ("ARABIC LETTER FARSI YEH WITH EXTENDED ARABIC-INDIC DIGIT FOUR BELOW", "Lo", 0), ("ARABIC LETTER WAW WITH EXTENDED ARABIC-INDIC DIGIT TWO ABOVE", "Lo", 0), ("ARABIC LETTER WAW WITH EXTENDED ARABIC-INDIC DIGIT THREE ABOVE", "Lo", 0), ("ARABIC LETTER YEH BARREE WITH EXTENDED ARABIC-INDIC DIGIT TWO ABOVE", "Lo", 0), ("ARABIC LETTER YEH BARREE WITH EXTENDED ARABIC-INDIC DIGIT THREE ABOVE", "Lo", 0), ("ARABIC LETTER HAH WITH EXTENDED ARABIC-INDIC DIGIT FOUR BELOW", "Lo", 0), ("ARABIC LETTER SEEN WITH EXTENDED ARABIC-INDIC DIGIT FOUR ABOVE", "Lo", 0), ("ARABIC LETTER SEEN WITH INVERTED V", "Lo", 0), ("ARABIC LETTER KAF WITH TWO DOTS ABOVE", "Lo", 0), )
https://github.com/rinmyo/ruby-typ
https://raw.githubusercontent.com/rinmyo/ruby-typ/main/ruby.typ
typst
MIT License
#let _ruby(rt, rb, size, pos, dy, alignment, delimiter) = { if not ("center", "start", "between", "around").contains(alignment) { panic("'" + repr(alignment) + "' is not a valid ruby alignment") } if not (top, bottom).contains(pos) { panic("pos can be either top or bottom but '"+ repr(pos) +"'") } let extract_content(content, fn: it => it) = { let func = content.func() return if func == text or func == raw { (content.text, fn) } else { extract_content(content.body, fn: it => func(fn(it))) } } let rb_array = if type(rb) == "content" { let (inner, func) = extract_content(rb) inner.split(delimiter).map(func) } else if type(rb) == "string" { rb.split(delimiter) } else {(rb,)} assert(type(rb_array) == "array") let rt_array = rt.split(delimiter) if rt_array.len() != rb_array.len() { rt_array = (rt,) rb_array = (rb,) } let gutter = if (alignment=="center" or alignment=="start") { h(0pt) } else if (alignment=="between" or alignment=="around") { h(1fr) } box(style(st=> { let sum_body = [] let sum_width = 0pt let i = 0 while i < rb_array.len() { let (body, ruby) = (rb_array.at(i), rt_array.at(i)) let bodysize = measure(body, st) let rt_plain_width = measure(text(size: size, ruby), st).width let width = if rt_plain_width > bodysize.width {rt_plain_width} else {bodysize.width} let chars = if(alignment=="around") { h(0.5fr) + ruby.clusters().join(gutter) + h(0.5fr) } else { ruby.clusters().join(gutter) } let rubytext = box(width: width, align(if(alignment=="start"){left}else{center}, text(size: size, chars))) let textsize = measure(rubytext, st) let dx = textsize.width - bodysize.width let (t_dx, l_dx, r_dx) = if(alignment=="start"){(0pt, 0pt, dx)}else{(-dx/2, dx/2, dx/2)} let (l, r) = (i != 0, i != rb_array.len() - 1) sum_width += if l {0pt} else {t_dx} let dy = if pos == top {-1.5 * textsize.height - dy} else {bodysize.height + textsize.height/2 + dy} place( top+left, dx: sum_width, dy: dy, rubytext ) sum_width += width sum_body += if l {h(l_dx)} + body + if r {h(r_dx)} i += 1 } sum_body })) } #let get_ruby( size: .5em, dy: 0pt, pos: top, alignment: "center", delimiter: "|" ) = (rt, rb, alignment: alignment) => _ruby(rt, rb, size, pos, dy, alignment, delimiter) #let test() = [ #set box(stroke: red+.001pt) #set text(size: 50pt) #show: align.with(center) #let ruby = get_ruby(pos: bottom) #ruby("した")[下] #let ruby = get_ruby() #ruby("うえ")[上] ] //#test()
https://github.com/Gekkio/gb-ctr
https://raw.githubusercontent.com/Gekkio/gb-ctr/main/chapter/cartridges/mbc30.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "../../common.typ": * == MBC30 mapper chip MBC30 is a variant of MBC3 used by Japanese Pokemon Crystal to support a larger ROM chip and a larger RAM chip. Featurewise MBC30 is almost identical to MBC3, but supports ROM sizes up to 32 Mbit (256 banks of #hex("4000") bytes), and RAM sizes up to 512 Kbit (8 banks of #hex("2000") bytes). Information in this section is based on my MBC30 research. #warning[ The circuit board of Japanese Pokemon Crystal includes a 1 Mbit RAM chip, but MBC30 is limited to 512 Kbit RAM. One of the RAM address pins is unused, so half of the RAM is wasted and is inaccessible without modifications. So, the game only uses 512 Kbit and there is a mismatch between accessible and the physical amounts of RAM. ]
https://github.com/Sematre/typst-letter-pro
https://raw.githubusercontent.com/Sematre/typst-letter-pro/main/docs/letter-generic-layout.typ
typst
MIT License
#import "/src/lib.typ": letter-generic, address-tribox #let fbox(color, content) = rect(width: 100%, height: 100%, inset: 3pt, fill: color)[ #align(center + horizon)[ #rect(fill: white, text(size: 8pt, content)) ] ] #set par(justify: true) #set text(font: "Source Sans Pro", hyphenate: false) #show: letter-generic.with( header: fbox(yellow, "header"), footer: fbox(yellow, "footer"), address-box: fbox(gray, "address-box"), information-box: fbox(navy, "information-box"), reference-signs: ( (fbox(purple, "reference-signs[0]"), []), (fbox(purple, "reference-signs[1]"), []), (fbox(purple, "reference-signs[2]"), []), (fbox(purple, "reference‑signs[3]"), []), (fbox(purple, "reference-signs[4]"), []), ), page-numbering: (x, y) => "Page " + text(fill: eastern)[current-page] + " of " + text(fill: fuchsia)[page-count], margin: ( bottom: 3cm, ) ) #lorem(1000)
https://github.com/marcantoinem/CV
https://raw.githubusercontent.com/marcantoinem/CV/main/en/work-experience.typ
typst
#import "../src/style.typ": experience #let nuvu = { experience( "Nuvu Cameras", "Montréal, Canada", "May 2024 - Aug 2024", "Embedded Software Development Intern", [ - Developed testbenches for over *30 000 lines* of VHDL code to ensure the correct behavior of the new camera generation's FPGA with VUnit. - Deployed a full CI/CD pipeline on Jenkins to automate the testing of the FPGA firmware and ensure code quality. - Covered *95%* of the codebase with the testbenches to ensure the reliability of the code and discovered many bugs before they could reach the hardware. - Developed a RAM AXI4 Master controller in VHDL to interface the Microchip's FPGA with DDR3 and DDR4 RAM and reached debit over *48 Gb/s* to write a circular buffer of images taken by the camera. ], ) } #let charge = { experience( "Polytechnique Montréal", "Montréal, Canada", "Aug 2023 - Present", "Teaching Assistant", [ - Taught the following courses: object-oriented programming (INF1010) and digital systems design (INF3500) - Provided technical support and guidance to students, fostering a deeper understanding of course material. - Evaluated assignments, offering detailed feedback to promote student improvement. ], ) } #let lainco = { experience( "Lainco", "Terrebonne, Canada", "May 2023 - Aug 2023", "Software Developer Intern", [ - Produced powerful and user-friendly scripts to automate steel beam placement in CAD software that followed the mechanical engineer's specification automatically and saved up to *several weeks* of repetitive work for CAD designer on several projects. - Rewrote an entire legacy codebase from Python2 to Python3 to improve maintainability and readability. - Built a steel placement efficiency estimator in *Rust* to reduce the steel loss by *15%*. ], ) }
https://github.com/SillyFreak/typst-scrutinize
https://raw.githubusercontent.com/SillyFreak/typst-scrutinize/main/src/task-kinds/gap.typ
typst
MIT License
#let _grid = grid /// An answer filled in a gap in a text. If the document is not in solution mode, the answer is /// hidden but the width of the element is preserved. /// /// Example: /// /// #task-example(lines: "2-", ```typ /// #import task-kinds.gap: gap /// #set par(leading: 1em) /// This is a #gap(stretch: 200%)[difficult] question \ /// and it has #gap(placeholder: [...], width: 1cm, stroke: "box")[two] lines. /// ```) /// /// - answer (content): the answer to (maybe) display /// - placeholder (auto, content): the placeholder to display instead of hiding the answer. For the /// layout of exam and solution to match, this needs to have the same width as the answer. /// - width (auto, relative): the width of the region where an answer can be written /// - stretch (ratio): the amount by which the width of the answer region should be stretched /// relative to the required width of the provided solution. Can only be set to a value other /// than 100% if `width == auto`. /// - stroke (none, string, stroke): the stroke with which to mark the answer area. The special /// values `"underline"` or `"box"` may be given to draw one or four border lines with a default /// stroke. /// -> content #let gap( answer, placeholder: auto, width: auto, stretch: 100%, stroke: "underline", ) = context { import "../solution.typ" let (answer, width, stroke) = (answer, width, stroke) assert( width == auto or stretch == 100%, message: "a `stretch` value other than 100% is only allowed if `width == auto`.", ) assert( type(stroke) != str or stroke in ("underline", "box"), message: "for string values, only \"underline\" or \"box\" are allowed", ) answer = solution.answer(answer, placeholder: placeholder, place-args: arguments(center)) if stroke == "underline" { stroke = (bottom: 0.5pt) } else if stroke == "box" { stroke = 0.5pt } let answer-box = box.with( stroke: stroke, outset: (y: 0.4em), inset: (x: 0.4em), align(center, answer), ) if stretch != 100% { width = measure(answer-box()).width * stretch } answer-box(width: width) }
https://github.com/cadojo/vita
https://raw.githubusercontent.com/cadojo/vita/main/vita.typ
typst
MIT License
// // Preamble // #import "src/experience.typ": * #import "src/education.typ": * #import "src/projects.typ": * #import "src/skills.typ": * #import "src/socials.typ": * #let decorated(src, body) = { if src == none { body } else { stack(dir: ltr, move(dy: 0.4em, image(src, height: 1.5em)), h(0.5em), body) } } #let resume( name: none, email: none, phone: none, title: "Professional Resume", theme: rgb(120,120,120), body: stack(spacing: 1.25em, experiences(), degrees(), skills()), side: stack(projects(), socials(),), metadata, ) = { show link: underline set text( size: 9pt, ) set page( margin: ( "left": 0.3in, "right": 0.3in, "top": 1in, "bottom": 0.5in, ), background: place( right + bottom, rect( fill: theme, height: 100%, width: 33%, ) ), paper: "us-letter", header: grid( columns: (67%, 1fr, 29%), [ #set text(22pt, weight: "semibold") #if title == none {name} else {name + " " + $dot$ + " " + title} ], "", [ #set text(size: 11pt, white) #v(1em) #block( align(left)[ #stack( dir: ttb, spacing: 1.75em, phone, email, ) ] ) ] ), header-ascent: 0.5in, ) show heading.where(level: 1): set text(size: 20pt, theme.darken(10%)) show heading.where(level: 2): set text(size: 13pt) metadata grid( columns: (67%, 1fr, 29%), stack( dir: ttb, spacing: 1.5em, body, ), "", stack(dir: ttb)[ #locate( loc => { show heading.where(level: 1): set text(white) show heading.where(level: 1): set align(center) set text(white) side } ) ] ) } #let cv( name: none, email: none, phone: none, links: none, title: "Professional Resume", theme: rgb(120,120,120), body: stack(spacing: 1.25em, experiences(), degrees(), skills()), metadata ) = { let subtitle = (email, phone, ..links).join(" • ") let header = stack( spacing: 1.5em, text("<NAME>", size: 18pt), if subtitle.len() > 4 { subtitle } ) set page( margin: 1in, header: align(center, header), ) }
https://github.com/darioglasl/Arbeiten-Vorlage-Typst
https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/Anhang/04_Projektdokumentation/02_aufgabenstellung.typ
typst
=== Aufgabenstellung <appendixScope> Nachfolgend sind alle Original-Informationen aufgelistet, die zur Aufgabenstellung (@headingScope) verfügbar sind.
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/call_info/builtin_poly2.typ
typst
Apache License 2.0
#(/* position after */ rgb("#fff"))
https://github.com/MobtgZhang/sues-thesis-typst
https://raw.githubusercontent.com/MobtgZhang/sues-thesis-typst/main/paper/chapters/ch01.typ
typst
MIT License
#import "../info.typ": * = 绪论 <intro> == 关于Typst模板 本模板是本文为拓展同学门编写硕士学位论文而写的,本项目地址代码均在#link("https://github.com/mobtgzhang/sues-thesis-typst","GitHub")。 论文模板硕士学位论文模板目前问题比较小,可以尝试使用一段时间,所以可以尝试使用以下用其写一些基本的论文。 == 关于Typst Typst 是一门面向出版与学术写作的可编程标记语言,从2023年4月正式开源v0.1.0版本以来,到现在的2024年2月v0.10.0(2023年12月4日版本)。 这个项目是用Rust语言写的轻量级项目,相对于LaTeX,Typst较为轻量级、编译速度较快,而且语法相对来说较为简单,具有用户友好的文档和教程,适合于文档开发的操作。 目前相对来说对于中文支持比较好,特别是有了CJK语言的支持,成熟稳定了一些。 由于更新速度比较快,所以网上一些Typst教程可能随时失效,注意关注Typst社区最新版本的教程。 == 关于使用平台和方法 Typst是跨平台的文档标记语言,包括有Linux、MacOS和Windows环境中,具体安装方法如下所示: #figure( image("../figures/plugs.jpg", width: 80%), caption:"插件的安装方式" )<section01-plugs-vscode> + 安装VSCode:在微软VScode官方上下载即可; + 安装LSP:在左边的插件搜索栏中查找对应的插件即可,如#ref(<section01-plugs-vscode>) 所示。 + 最后可以通过同步编辑`typ`文件可以对文档进行编辑处理,如#ref(<section01-vscode>)所示。 #figure( image("../figures/vscode.jpg", width: 80%), caption:"VSCode 最后的显示结果" )<section01-vscode> == 相关学习资料 - #link("http://ai-assets.404.net.cn/pdf/typst/typst-zh_CN-20230409.pdf","Typst官方文档中文翻译版"); - #link("http://ai-assets.404.net.cn/pdf/typst/typst-zh_CN-20230409.pdf","Typst中文教程"); - #link("http://ai-assets.404.net.cn/pdf/typst/typst-zh_CN-20230409.pdf","Typst教程及其参考"); - #link("http://ai-assets.404.net.cn/pdf/typst/typst-zh_CN-20230409.pdf","Symbol符号速查表 "); - #link("http://ai-assets.404.net.cn/pdf/typst/typst-zh_CN-20230409.pdf","Awesome Typst中文版")。
https://github.com/QuadnucYard/pigeonful-typ
https://raw.githubusercontent.com/QuadnucYard/pigeonful-typ/main/examples/chh.typ
typst
MIT License
#import "../src/lib.typ": pigeonful #set page(width: auto, height: auto, margin: 4pt) #pigeonful( entries: ( "层次": [直博生], "单位": [华中科技大学], "院系": [计算机科学与技术学院], "专业": [计算机科学与技术(081200)], "学习方式": [全日制], "研究方向": [人工智能], "导师": [陈汉华], "专项计划类型": [普通计划], "就业类型": [非定向就业], ), notice-kind: "fushi", notifier: [华中科技大学招生办 2024-09-29 09:19], notice-body: [同学,你好!\ 陈汉华看上你了,点名要你直博。], acceptance: [您于9月29日 09:20接受了华中科技大学的复试通知], )
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/dynamic/pause.md
markdown
# `pause` as an alternative to `#one-by-one` There is yet another way to solve the same problem as `#one-by-one`. If you have used the LaTeX beamer package before, you might be familiar with the `\pause` command. It makes everything after it on that slide appear on the next subslide. Remember that the concept of "do something with everything after it" is covered by the `#show: ...` mechanism in Typst. We exploit that to use the `pause` function in the following way. ```typ {{#include pause.typ:6:12}} ``` This would be equivalent to: ```typ #one-by-one[ Show this first. ][ Show this later. ][ Show this even later. ][ That took aaaages! ] ``` and results in ![pause](pause.png) It is obvious that `pause` only brings an advantage over `#one-by-one` when you want to distribute a lot of code onto different subslides. **Hint:** You might be annoyed by having to manually number the pauses as in the code above. You can diminish that issue a bit by using a counter variable: ```typ Show this first. #let pc = 1 // `pc` for pause counter #{ pc += 1 } #show: pause(pc) Show this later. #{ pc += 1 } #show: pause(pc) Show this even later. #{ pc += 1 } #show: pause(pc) That took aaaages! ``` This has the advantage that every `pause` line looks identical and you can move them around arbitrarily. In later versions of this template, there could be a nicer solution to this issue, hopefully.
https://github.com/lrmrct/CADMO-Template
https://raw.githubusercontent.com/lrmrct/CADMO-Template/main/template/layout.typ
typst
#import "theorems.typ": counter_reset #let layout(doc) = [ #set page( paper: "a4", numbering: "i", number-align: right, margin: (x: 115pt, top: 109pt, bottom: 121pt), footer-descent: 18%, header: [ ] ) #set text( font: "tex gyre pagella", size: 11pt ) #set enum(numbering: "1.", indent: 1.23em, spacing: 11pt) #set list(marker: "-") #show raw: set text(font: "CMU Typewriter Text", size: 11pt) #set quote(block: true) #show quote: q => { v(0em) h(2.1em); q.body } #show math.equation: set text(font: "tex gyre pagella math") #set outline(depth: 3) #show outline.entry: it => { [ #it.body.children.at(0) #h(1em) #it.body.children.at(2) #h(0.7em) #box(width: 1fr, repeat[. #h(0.4em)]) #h(1.5em) #it.page ] } #show outline.entry.where( level: 1 ): it => { v(0.4em) if it.body.has("children") { [ #strong(it.body.children.at(0)) #h(1em) #strong(it.body.children.at(2)) #h(1fr) #strong(it.page) ] } else { strong(it.body); h(1fr); strong(it.page) } } #show outline: o => { heading(numbering: none)[Contents] strong()[ Contents #h(1fr) #context[ #counter(page).display(here().page-numbering()) ] ] o } #set heading(numbering: "1.1") #show heading.where(depth: 1): it => [ #counter_reset() #set align(center) #set text(font: "CMU Bright", weight: "extrabold", size: 22pt) #pagebreak() #v(4em) #if it.numbering != none { [ #set text(size: 14pt) Chapter #counter(heading).display( it.numbering ) ] } #line(length: 100%, stroke: 0.5pt) #set text(font: "cmu sans serif", weight: "bold") #it.body #v(-0.6em) #line(length: 100%, stroke: 0.5pt) #v(1.5em) ] #show heading.where(depth: 2): it => [ #set text(font: "cmu sans serif", weight: "bold", size: 14pt) #v(0.4em) #counter(heading).display( it.numbering ) #h(1em) #(it.body) #v(0.1em) ] #show heading.where(depth: 3): it => [ #set text(font: "cmu sans serif", weight: "bold") #v(0.5em) #counter(heading).display( it.numbering ) #h(1em) #(it.body) #v(0.6em) ] #show heading.where(depth: 4): it => [ #set text(font: "cmu sans serif", weight: "bold") #v(0.5em) #(it.body) #v(0.6em) ] #doc ]
https://github.com/furkan/cv
https://raw.githubusercontent.com/furkan/cv/main/modules/summary.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Summary") In my present role, I oversee the development of our telemetry server, manage a group of six engineers, and make sure that all of our procedures are well documented. In my previous role as a Machine Learning Engineer, I managed VPN and reverse SSH servers, maintained and refactored legacy AI systems, and trained object identification models using PyTorch. I am well versed Python, Docker, AWS, Git, and GitHub Actions. I am passionate about delivering value by solving real-world challenges, and I am committed to collaboration, continuous learning, and delivering high-quality results. My diverse experiences enable me to bring valuable perspectives to any team.
https://github.com/aagumin/cv
https://raw.githubusercontent.com/aagumin/cv/typst/content/personal.typ
typst
#import "@preview/grotesk-cv:0.1.2": * #import "@preview/fontawesome:0.2.1": * #let meta = toml("../info.toml") #let language = meta.personal.language == #fa-icon("brain") #h(5pt) #if language == "en" [Personality] else if language == "es" [Personalidad] #v(5pt) #if language == "en" [ - Analytic thinking - Quality conscious - Good communicator - Independent - Team player - Preemptive - Eager to learn ] else if language == "ru" [ - Pensamiento analítico - Consciente de la calidad - Buen comunicador - Independiente - Jugador de equipo - Preventivo - Ansioso por aprender ]
https://github.com/Servostar/dhbw-abb-typst-template
https://raw.githubusercontent.com/Servostar/dhbw-abb-typst-template/main/src/glossarium.typ
typst
MIT License
// .--------------------------------------------------------------------------. // | [email protected] with custom format | // '--------------------------------------------------------------------------' // Authors: ENIB-Community // Changed: <NAME> // Edited: 08.07.2024 // License: MIT // Customized version of https://github.com/ENIB-Community/glossarium/tree/release-0.4.1 // in order to conform to DHBW requirements in terms of format /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ // glossarium figure kind #let __glossarium_figure = "glossarium_entry" // prefix of label for references query #let __glossary_label_prefix = "glossary:" // global state containing the glossary entry and their location #let __glossary_entries = state("__glossary_entries", (:)) #let __glossarium_error_prefix = "glossarium error : " #let __query_labels_with_key(loc, key, before: false) = { if before { query( selector(label(__glossary_label_prefix + key)).before( loc, inclusive: false, ), loc, ) } else { query(selector(label(__glossary_label_prefix + key)), loc) } } // key not found error #let __not-found-panic-error-msg(key) = { __glossarium_error_prefix + "key '" + key + "' not found" } // Reference a term #let gls(key, suffix: none, long: none, display: none) = { context { let __glossary_entries = __glossary_entries.final(here()) if key in __glossary_entries { let entry = __glossary_entries.at(key) let gloss = __query_labels_with_key(here(), key, before: true) let is_first = gloss == () let entlong = entry.at("long", default: "") let textLink = if display != none { [#display] } else if ( is_first or long == true ) and entlong != [] and entlong != "" and long != false { [#entlong (#entry.short#suffix)] } else { [#entry.short#suffix] } [#link( label(entry.key), textLink, )#label(__glossary_label_prefix + entry.key)] } else { panic(__not-found-panic-error-msg(key)) } } } // Reference to term with pluralisation #let glspl(key, long: none) = { let suffix = "s" context { let __glossary_entries = __glossary_entries.final(here()) if key in __glossary_entries { let entry = __glossary_entries.at(key) let gloss = __query_labels_with_key(here(), key, before: true) let is_first = gloss == () let entlongplural = entry.at("longplural", default: "") let entlong = if entlongplural == [] or entlongplural == "" { // if the entry long plural is not provided, then fallback to adding 's' suffix let entlong = entry.at("long", default: "") if entlong != [] and entlong != "" { [#entlong#suffix] } else { entlong } } else { [#entlongplural] } let entplural = entry.at("plural", default: "") let short = if entplural == [] or entplural == "" { [#entry.short#suffix] } else { [#entplural] } let textLink = if ( is_first or long == true ) and entlong != [] and entlong != "" and long != false { [#entlong (#short)] } else { [#short] } [#link( label(entry.key), textLink, )#label(__glossary_label_prefix + entry.key)] } else { panic(__not-found-panic-error-msg(key)) } } } // show rule to make the references for glossarium #let make-glossary(body) = { show ref: r => { if r.element != none and r.element.func() == figure and r .element .kind == __glossarium_figure { // call to the general citing function gls(str(r.target), suffix: r.citation.supplement) } else { r } } body } #let __normalize-entry-list(entry_list) = { let new-list = () for entry in entry_list { new-list.push(( key: entry.key, short: entry.short, plural: entry.at("plural", default: ""), long: entry.at("long", default: ""), longplural: entry.at("longplural", default: ""), desc: entry.at("desc", default: ""), group: entry.at("group", default: ""), )) } return new-list } #let print-glossary( entry_list, show-all: false, disable-back-references: false, enable-group-pagebreak: false, ) = { let entries = __normalize-entry-list(entry_list) __glossary_entries.update(x => { for entry in entry_list { x.insert(entry.key, entry) } x }) let groups = entries.map(x => x.at("group")).dedup() for group in groups.sorted() { if group != "" [#heading(group, level: 1, outlined: false) ] for entry in entries.sorted(key: x => x.key) { if entry.group == group { [ #show figure.where(kind: __glossarium_figure): it => it.caption #figure( supplement: "", kind: __glossarium_figure, numbering: none, caption: { context { let key = if entry.key.ends-with("__glossary_entry") { entry.key.replace("__glossary_entry", "") } else { entry.key } let term_references = __query_labels_with_key(here(), key) if term_references.len() != 0 or show-all [ #let desc = entry.at("desc", default: "") #let long = entry.at("long", default: "") #let hasLong = long != "" and long != [] #let hasDesc = desc != "" and desc != [] #block( below: 1.5em, par(hanging-indent: 1em)[ #text(weight: "bold", entry.short) #if hasLong and hasDesc [ (#text(entry.long)) ] else if hasLong { text(entry.long) } #if hasDesc [ #sym.dash.en ] #if hasDesc [ #desc ] #if disable-back-references != true { term_references .map(x => x.location()) .sorted(key: x => x.page()) .fold( (values: (), pages: ()), ((values, pages), x) => if pages.contains( x.page(), ) { (values: values, pages: pages) } else { values.push(x) pages.push(x.page()) (values: values, pages: pages) }, ) .values .map(x => { let page-numbering = x.page-numbering() if page-numbering == none { page-numbering = "1" } link(x)[#numbering( page-numbering, ..counter(page).at(x), )] } ) .join(", ") } ], ) ] } }, )[] #label(entry.key) ] } } if enable-group-pagebreak { pagebreak(weak: true) } } };
https://github.com/CHHC-L/ciapo
https://raw.githubusercontent.com/CHHC-L/ciapo/master/examples/long-example-0/main.typ
typst
MIT License
#import "template.typ": diapo, transition, longpage, mcolor, bf, refpage #show: diapo.with( title: "Livella gratillo\nDoct rexytiner\nIespelitus otaratio eterniarea", author: "CHHC", email: "<EMAIL>", date: "2023-12-06", short-title: "Regulus", ) #outline(indent: auto, depth: 3) = Homework == h7 === Ex3. File I/O in C++ - File, string, standard input/output can all be converted into stream - Similar to `FILE*` in C - DO NOT forget to check whether the files are correctly opened - DO NOT forget to close the files #bf[Think: ] How to read a line that contains numbers separated by spaces? #pagebreak() #bf[Think: ] How to read a line that contains numbers separated by spaces? You can still manually read a line and convert the numbers. Or? One cpp-style-way is to take the advantages of `std::getline` and `std::istringstream`. ```cpp // Read a line from input. input can be a file or standard input. std::string line; std::getline(input, line); // Now line is one line std::istringstream iss(line); // Read numbers from iss while(iss >> num) { // Do something with num } ``` #pagebreak() #bf[Think: ] How to detect input errors? For example, if we use `cin>>a;` where `a` is an int, but the real input is not an integer. Maybe you can try `cin.fail()`, `cin.clear()` and `cin.ignore()`? #image("./BlobCat_Think.png", width: 10%) #pagebreak() === Ex4. Basic Programming $ cases( u_0 = a, u_(i+1) = cases(1/2 u_i &" if" n "is even", 3u_i + 1 &" if" n "is odd"), ) $ - Basic logic questions - Recall what is recursion - Think about Fibonacci sequence. How to find the $n$-th Fibonacci number? #pagebreak() === Ex5. From C to C++ Here are some questions you should think of: - What is `class` in C++? - What is OOP? - What is polymorphism in C++? - What is abstract class in C++? - What is `virtual` function in C++? What is virtual destructor and when to use it? - #link("https://stackoverflow.com/questions/461203/when-to-use-virtual-destructors")[This answer] might be of help. - What are the common containers in STL? How to use them? #pagebreak() == h8 === Ex1. Containers Basic C++ Containers library & Data structure. Make full use of #link("http://cppreference.com/")[cppreference]. Parameter `T` inside `<>` is called #bf[template parameter], deduced when compilation. - `std::array<T, N>`: static contiguous array - `std::vector<T>`: dynamic contiguous array. #bf[Random access] is supported. - `std::stack<T>`: a container providing stack (LIFO data structure) - `std::queue<T>`: a container providing queue (FIFO data structure) #longpage(2.5)[ ```cpp #include <array> #include <iostream> #include <queue> #include <stack> #include <string> #include <vector> using std::array; using std::cin; using std::cout; using std::queue; using std::stack; using std::string; using std::vector; // Instead of "using namespace std;" void ex1_reverse_array() { array<string, 10000> re; string word; size_t count = 0; while (cin >> word) re[count++] = word; for (auto iter = re.cbegin() + count - 1; iter != re.cbegin() - 1; --iter) { // do something with *iter } } void ex1_reverse_vector() { vector<string> re; string word; while (cin >> word) re.push_back(word); for (auto iter = re.crbegin(); iter != re.crend(); ++iter) { // do something with *iter } } void ex1_reverse_stack() { stack<string> re; string word; while (cin >> word) re.push(word); for (; !re.empty(); re.pop()) { // do something with re.top() }; } void ex1_ordered_queue() { queue<string> re; string word; while (cin >> word) re.push(word); for (; !re.empty(); re.pop()) { // do something with re.front() }; } ``` ] === Ex2. Class Implementation - Basic inheritance & polymorphism - Basic drawing in OpenGL - Draw hierarchy diagram === Ex3. Classes and OpenGL - Basic animation in OpenGL - Draw different figures in OpenGL - Line - Rectangle - Triangle - Polynomial - Circle - Combination of classes = Lab Refer to lab materials! Basically the most important things are those that appear repeatedly in every lab section ;D == lab9 - What is stack? - What is Postfix Expression? - How to use stack and implement the _Shunting Yard algorithm_ ? - Basic usage of `std::stack` #pagebreak() == lab10 Basic class design: - Methods - Attributes - Hierarchy (public, protected, private) - Abstract class (virtual functions) - Polymorphism (optional? depends on what Prof. said in lecture) #bf[Avoid diamond structure in class design!] Some design patterns (optional!): - Singleton - Factory Method - Observer - Adapter #refpage[ - #link("616.sb")[Cralia sarytie] - _Uaractive contactina maleficio_ ] #transition(accent-color: mcolor.lpink)[Break?]
https://github.com/VadimYarovoy/CourseWork
https://raw.githubusercontent.com/VadimYarovoy/CourseWork/main/typ/stage_2.typ
typst
#import "@preview/cetz:0.1.2" #import "@preview/tablex:0.0.6": * == Определить необходимые ресурсы для выполнения программного проекта Материальные ресурсы были определены из предположения, что работа над проектом ведется в дистанционном режиме. // Сотрудникам предоставляется только следующая техника на все время проекта: === Ресурсы *Материальные ресурсы* #align(center)[ #tablex( columns: 3, [Название], [Количество], [Комментарий], [Ноутбук], [9], [Предоставляются из резерва организации], [Сервер], [2], [Для тестирования и развертывания приложения Предоставляются из резерва организации], ) ] *Инструментальные*: #align(center)[ #tablex( columns: 3, [Название], [Количество], [Комментарий], [Fedora GNU/Linux], [9], [Операционная система, установленная на ноутбуках сотрудников. ОС распространяется *бесплатно*.], [Kubernetes], [1], [Система развертывания ПО. Используется для запуска систем инструментов разработки и тестовых стендов --- *бесплатно*], [Visual Studio Code],[8],[Используется для эффективного написания кода, отладки и разработки автоматизированных тестов. IDE распространяется *бесплатно*.], [Teams],[1],[Используется для комуникации. Закупаются *платные лицензии* для всех сотрудников.], [GitLab],[1],[Система управления репозиториями с кодом --- *бесплатно*], [GitLab CI/CD],[1],[Система CI/CD --- *бесплатно*], [Artifactory], [1], [Система трекинга программных артефактов --- *бесплатно*], [Allure], [1], [Система трекинга артефактов тестирования --- *бесплатно*], [Jira],[9],[Используется для отслеживания задач и хранения записей об ошибках. Закупаются *платные лицензии* для всех сотрудников.], [Confluence],[9],[Используется для ведения документации. Закупаются *платные лицензии* для всех сотрудников.], [ActiveDirectory],[9],[Система менеджмента единых аккаунтов сотрудников. Закупаются *платные лицензии* для всех сотрудников.], ) ] Все перечисленные ресурсы требуются на все время проекта === Штат проекта: Численность и объем занятости: - 6 разработчиков (40 час/нед) - 1 senior - 3 middle - 2 junior - 2 тестировщика (40 час/нед) - 1 middle - 1 junior - 1 Scrum Master (один из разработчиков, +4 час/нед) - 1 проектный менеджер (40 час/нед) === Финансовые ресурсы Часть зарплаты сотрудникам выплачивается после завершения проекта в случае, если заказчика удовлетворил результат. Это указывается в заключаемом договоре. Заработная плата для сотрудников проекта (включая налоги и отчисления): - Разработчики и тестировщики: - senior: $3x$ - middle: $2x$ - junior: $x$ - Scrum Master: $+0.1x$ - Проектный менеджер: $2.5x$ - Сумма з/п: $16.6x$ Текущих расходы: - Аренда, коммунальные услуги и др.: $20x$ - Плата за аппаратные средства (амортизированное): $10x$ - Плата за лицензии ПО: $5x$ - Сумма т/р: $35x$ Сумма расходов: $49.6x$ Амортизация рисков: $5%$ от суммы = $2.48$ Сумма: $52.08$ #import "@preview/plotst:0.1.0": * // create the sample data #let data = ((3, "(" + repr(calc.round(3 / 52.08, digits: 4) * 100) + "%) З/п Senior"), (6, "(" + repr(calc.round(6 / 52.08, digits: 3) * 100) + "%) З/п Middle"), (2, "(" + repr(calc.round(2 / 52.08, digits: 3) * 100) + "%) З/п Junior"), (0.1,"(" + repr(calc.round(0.1 / 52.08, digits: 3) * 100) + "%) З/п Scrum-master"), (20, "(" + repr(calc.round(20 / 52.08, digits: 3) * 100) + "%) Аренда и проч."), (10, "(" + repr(calc.round(10 / 52.08, digits: 3) * 100) + "%) Аппаратные средства"), (5, "(" + repr(calc.round(5 / 52.08, digits: 3) * 100) + "%) Лицензии ПО"), (2.48,"(" + repr(calc.round(2.48 / 52.08, digits: 3) * 100) + "%) Риски")) #let colors = ( color.mix((yellow, 100%), (red, 50%)) , color.mix((yellow, 100%), (red, 30%)) , color.mix((yellow, 100%), (red, 5%)) , color.mix((yellow, 100%), (red, 85%)) , color.mix((blue, 100%), (red, 50%)) , color.mix((blue, 100%), (red, 25%)) , color.mix((blue, 100%), (red, 12%)) , green ) // Skip the axis step, as no axes are needed // Put the data into a plot #let p = plot(data: data) // Display the pie_charts in all different display ways #align(center)[ #pie_chart(p, (100%, 20%), colors: colors, display_style: "hor-chart-legend", caption: [Финансовые ресурсы]) ] Компания представляет собой индивидуальное предприятие (ИП), которое работает с применением упрощенной системы налогообложения (УСН). Вариант УСН, который был выбран, называется "Доходы" и включает в себя налоговую ставку в размере 6% от общей выручки ИП #pagebreak()
https://github.com/chillcicada/typst-dotenv
https://raw.githubusercontent.com/chillcicada/typst-dotenv/main/README.md
markdown
MIT License
# tenv Parse a .env content. ## Usage ```typ #import "@preview/tenv.typ:0.1.1": parse_dotenv #let env = parse_dotenv(read(".env")) ``` ## Example ![Example](./example.png)
https://github.com/tingerrr/subpar
https://raw.githubusercontent.com/tingerrr/subpar/main/doc/manual.typ
typst
MIT License
#import "@local/mantys:0.1.4" as mantys #import "@preview/hydra:0.4.0": hydra #import "/src/lib.typ" as subpar #let package = toml("/typst.toml").package #let issue(n) = text( eastern, link("https://github.com/tingerrr/subpar/issues/" + str(n))[subpar\##n], ) #show: mantys.mantys.with( ..package, title: [subpar], date: datetime.today().display(), abstract: [ SUBPAR provides easy to use sub figures with sensible default numbering and an easy-to-use no-setup API. ], examples-scope: (subpar: subpar), ) #show raw: it => { show "{{VERSION}}": package.version it } = Manifest SUBPAR aims to be: - simple to use - importing a function and using it should be all that is needed - setup required to make the package work should be avoided - unsurprising - parameters should have sensible names and behave as one would expect - deviations from this must be documented and easily accesible to Typst novices - interoperable - SUBPAR should be easy to use with other packages by default or provide sufficient configuration to allow this in other ways - minimal - it should only provide features which are specifically used for sub figures If you think its behvior is surprising, you believe you found a bug or think its defaults or parameters are not sufficient for your use case, please open an issue at #text(eastern, link("https://github.com/tingerrr/subpar")[GitHub:tingerrr/subpar]). Contributions are also welcome! = Guide == Labeling Currently to refer to a super figure the label must be explicitly passed to `super` using `label: <...>`. == Grid Layout The default `super` function provides only the style rules to make sub figures correctly behave with respect to numbering. To arrange them in a specific layout, you can use any other Typst function, a common choice would be `grid`. #mantys.example[```typst #subpar.super( grid( [#figure([a], caption: [An image]) <fig1a>], [#figure([b], caption: [Another image]) <fig1b>], figure([c], caption: [A third unlabeled image]), columns: (1fr,) * 3, ), caption: [A figure composed of three sub figures.], label: <fig1>, ) We can refer to @fig1, @fig1a and @fig1b. ```] Because this quickly gets cumbersome, SUBPAR provides a default grid layout wrapper called `grid`. It provides good defaults like `gutter: 1em` and hides options which are undesireable for sub figure layouts like `fill` and `stroke`. To label sub figures simply add a label after a figure like below. #mantys.example[```typst #subpar.grid( figure([a], caption: [An image]), <fig2a>, figure([b], caption: [Another image]), <fig2b>, figure([c], caption: [A third unlabeled image]), columns: (1fr,) * 3, caption: [A figure composed of three sub figures.], label: <fig2>, ) We can refer to @fig2, @fig2a and @fig2b. ```] == Numbering `subpar` and `grid` take three different numberings: / `numbering`: The numbering used for the sub figures when displayed or referenced. / `numbering-sub`: The numbering used for the sub figures when displayed. / `numbering-sub-ref`: The numbering used for the sub figures when referenced. Similarly to a normal figure, these can be functions or string patterns. The `numbering-sub` and `numbering-sub-ref` patterns will receive both the super figure an sub figure number. == Supplements Currently, supplements for super figures propagate down to super figures, this ensures that the supplement in a reference will not confuse a reader, but it will cause reference issues in multilingual documents (see #issue(4)). #mantys.example[````typst #subpar.grid( figure(```typst Hello Typst!```, caption: [Typst Code]), <sup-ex-code1>, figure(lorem(10), caption: [Lorem]), columns: (1fr, 1fr), caption: [A figure containing two super figures.], label: <sup-ex-super1>, ) ````] When refering the the super figure we see "@sup-ex-super1", when refering to the sub figure of a different kind, we still see the same supplement "@sup-ex-code1". To turn this behavior off, set `propagate-supplement` to `false`, this will also resolve the issues from #issue(4). #mantys.example[````typst #subpar.grid( figure(```typst Hello Typst!```, caption: [Typst Code]), <sup-ex-code2>, figure(lorem(10), caption: [Lorem]), columns: (1fr, 1fr), propagate-supplement: false, caption: [A figure containing two super figures.], label: <sup-ex-super2>, ) ````] Now when refering the the super figure we see still see "@sup-ex-super2", but when refering to the sub figure of a different kind, we the inferred supplement "@sup-ex-code2". == Appearance The `super` and `grid` functions come with a few arguments to control how super or sub figures are rendered. These work similar to show rules, i.e. they receive the element they apply to and display them. / `show-sub`: Apply a show rule to all sub figures. / `show-sub-caption`: Apply a show rule to all sub figures' captions. #mantys.example[```typst #subpar.grid( figure(lorem(2), caption: [An Image of ...]), figure(lorem(2), caption: [Another Image of ...]), numbering-sub: "1a", show-sub-caption: (num, it) => { it.supplement [ ] num [: ] it.body }, columns: 2, caption: [Two Figures], ) ```] Unfortunately, to change how a super figure is shown without changing how a sub figure is shown you must use a regular show rule and reconstruct the normal appearance in the sub figures using `show-sub`. Subpar provides a default implementation for this: `subpar.default.show-figure`, it can be passed directly to `show-sub`. = Reference == Subpar The package entry point. #mantys.tidy-module(read("/src/lib.typ"), name: "subpar") == Default Contains default implementations for show rules to easily reverse show rules in a scope. #mantys.tidy-module(read("/src/default.typ"), name: "default")
https://github.com/glennib/terraform-workshop
https://raw.githubusercontent.com/glennib/terraform-workshop/main/README.md
markdown
# source for terraform workshop ## looking for terraform template code? [🔗](./terraform/) `cd terraform` ## dependencies - compiling presentation - [`typst`] - `sudo snap install typst` - converting PDF to SVGs (for figures) - [`pdfinfo`] - `sudo apt install poppler-utils` - [`pdf2svg`] - `sudo apt install pdf2svg` - presentation tools - [`pdfpc`] - `sudo apt install pdf-presenter-console` - for displaying presentation pdf - [`polylux2pdfpc`] - `cargo install --git https://github.com/andreasKroepelin/polylux/ --branch release` - for extracting presentation notes [`typst`]: https://github.com/typst/typst [`pdfinfo`]: https://www.xpdfreader.com/pdfinfo-man.html [`pdf2svg`]: https://github.com/dawbarton/pdf2svg [`pdfpc`]: https://polylux.dev/book/external/pdfpc.html [`polylux2pdfpc`]: https://polylux.dev/book/external/pdfpc.html#extracting-the-data--polylux2pdfpc ## compiling ```bash make compile-handout # Compile the handout version of the presentation make compile # Compile the presentation make present # Run presentation make present-without-notes # Run presentation without notes make terraform-concepts # Convert the pdf of figures to svg files ```
https://github.com/lucifer1004/leetcode.typ
https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/leetcode.typ
typst
#import "helpers.typ": * #align(center)[ #box(baseline: 12pt)[#image("images/logo.png", height: 48pt)] #h(12pt) #text(48pt)[*Leetcode.typ*] ] #v(2em) #outline() #counter(page).update(0) #set smartquote(enabled: false) #set par(justify: true) #set page(numbering: "1") #set heading(numbering: (..nums) => { let chars = str(nums.pos().at(0)).clusters().rev() while chars.len() < 4 { chars.push("0") } chars.rev().join() + "." }) #show heading: it => { if it.level == 1 { pagebreak(weak: true) } it v(1em) } #include "problems/p0001.typ" #include "problems/p0002.typ" #include "problems/p0003.typ" #include "problems/p0004.typ" #include "problems/p0005.typ" #include "problems/p0006.typ" #include "problems/p0007.typ" #include "problems/p0008.typ" #include "problems/p0009.typ" #include "problems/p0010.typ" #include "problems/p0011.typ" #include "problems/p0012.typ" #include "problems/p0013.typ" #include "problems/p0014.typ" #include "problems/p0015.typ" #include "problems/p0016.typ" #include "problems/p0017.typ" #include "problems/p0018.typ"
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/visualize/shape-aspect.typ
typst
Apache License 2.0
// Test that squares and circles respect their 1-1 aspect ratio. --- // Test relative width and height and size that is smaller // than default size. #set page(width: 120pt, height: 70pt) #set align(bottom) #let centered = align.with(center + horizon) #stack( dir: ltr, spacing: 1fr, square(width: 50%, centered[A]), square(height: 50%), stack( square(size: 10pt), square(size: 20pt, centered[B]) ), ) --- // Test alignment in automatically sized square and circle. #set text(8pt) #box(square(inset: 4pt)[ Hey there, #align(center + bottom, rotate(180deg, [you!])) ]) #box(circle(align(center + horizon, [Hey.]))) --- // Test that minimum wins if both width and height are given. #stack( dir: ltr, spacing: 2pt, square(width: 20pt, height: 40pt), circle(width: 20%, height: 100pt), ) --- // Test square that is limited by region size. #set page(width: 20pt, height: 10pt, margin: 0pt) #stack(dir: ltr, square(fill: forest), square(fill: conifer)) --- // Test different ways of sizing. #set page(width: 120pt, height: 40pt) #stack( dir: ltr, spacing: 2pt, circle(radius: 5pt), circle(width: 10%), circle(height: 50%), ) --- // Test that square doesn't overflow due to its aspect ratio. #set page(width: 40pt, height: 25pt, margin: 5pt) #square(width: 100%) #square(width: 100%)[Hello there] --- // Size cannot be relative because we wouldn't know // relative to which axis. // Error: 15-18 expected length or auto, found ratio #square(size: 50%)
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/prob/lectures/2024-09-27.typ
typst
#import "/utils/math.typ": * = Формула Байеса $ P(H_i | A) = P(A H_i) / P(A) = (P(H_i) P(A | H_i)) / (sum_(j = 1)^n P(H_j) P(A | H_j)) $ $ sum_(i = 1)^n P(H_i) = 1 $ $ sum_(i = 1)^n P(H_i | A) = 1 $ == Задача #figure( caption: [Условие], table( columns: 3, table.header[*Завод*][*Процент поставленных деталей*][*Вероятность исправной детали*], [№ 1], $65%$, $0.9$, [№ 2], $35%$, $0.8$, ) ) $A$ --- деталь с дефектом оказалась в самолете $H_1$ --- деталь взяли и 1-ого завода $ P(H_1) = 0.65 $ $ P(A | H_1) = 0.1 $ $H_2$ --- деталь взяли и 2-ого завода $ P(H_1) = 0.35 $ $ P(A | H_1) = 0.2 $ $ P(A) = P(H_1) P(A | H_1) + P(H_2)P(A | H_2) = 0.65 dot 0.1 + 0.35 dot 0.2 $ $ P(H_1 | A) = (P(H_1) P(A | H_1)) / P(A) = 65 / 135 = 0.48 $ $ P(H_2 | A) = (P(H_2) P(A | H_1)) / P(A) = 70 / 135 = 0.52 $ = Случайные величины #def[ #defitem[Случайная величина (СВ)] --- величина, которая после эксперимента принимает заранее неизвестное значение. Числовая функция $xi: Omega-> RR$, которая удовлетворяет условию измеримости #footnote[почти всегда исполняется]: $ forall x in RR: { omega: xi(omega) <= x } in cal(A) $ ] #figure( caption: [Пример с кубиком], table( columns: 6, stroke: none, $Omega = {$, $omega_1,$, $omega_2,$, $...,$, $omega_6$, $}$, $$, $arrow.b$, $arrow.b$, $$, $arrow.b$, $$, $xi = {$, $1,$, $2,$, $...,$, $3$, $}$, ) ) #def[ #defitem[Функция распределения (вероятностей)] случайно величины $xi$ называется функция $ F_xi (x) = P(omega: xi(omega) <= x) $ ] Свойства $F(x)$: + $F(+oo) = 1$ $F(-oo) = 0$ $forall x: 0 <= F(x) <= 1$ + $F(x)$ не убывает: $x_1 < x_2 => F(x_1) <= F(x_2)$ + $F(x)$ непрерывна справа: $ F(x_0) = lim_(epsilon -> 0+) F(x_0 + epsilon), $ где $x_0$ --- точка разрыва Если некоторая $F(x)$ удовлетворяет условиям, то она является функцией распределения некоторой величины. Случайные величины: - Дискретные - Непрерывные = Дискретные случайные величины #def[ Случайную величину называют #defitem[дискретной], если множество её возможных значений конечно или счетно. ] #def[ #defitem[Ряд распределения] для дискретной СВ --- табличка из $xi$ в $P$: #figure( table( columns: 5, $xi$, $x_1$, $x_2$, $...$, $x_n$, $P$, $p_1$, $p_2$, $...$, $p_n$, ) ) ] #blk(title: "Пример")[ #figure( table( columns: 4, $xi$, $-1$, $0$, $2$, $P$, $0.2$, $0.3$, $0.5$, ) ) $ x < -1: F(x) = 0 $ $ F(-1) = 0.2 $ $ F(-0.5) = 0.2 $ $ F(0) = 0.2 + 0.3 $ $ F(2) = 1 $ $ x > 2: F(x) = 1 $ ] == Числовые характеристики дискретных случайных величин === Математическое ожидание #def[ #defitem[Математическим ожиданием $E$ (среднее значение)] дискретной СВ $xi$ называется число $ E xi = sum_(i = 1)^oo x_i p_i $ Предполагается, что ряд $sum_(i = 1)^oo abs(x_i) p_i$ сходится ]
https://github.com/Nianyi-GSND-Projects/GSND-5130-GP1
https://raw.githubusercontent.com/Nianyi-GSND-Projects/GSND-5130-GP1/master/Draft%201/Team%20Agreement.typ
typst
#set page(paper: "us-letter") #let team_name = "[team name]" #{ set align(center) set text(17pt, weight: "bold") text[ Team Agreement of #set text(style: "italic") #team_name ] } #text(style: "italic")[#team_name] is group \#2 for group work \#1 of GSND 5130; all members of which are randomly assigned by the professor. Under the group work requirements, and for establishing a behavior synchronization amongst the group members, this team agreement is drafted and proposed to be applied on all members. This agreement takes effect from the day it is signed by all members, and automatically ends on the day which the final task of the group work is accomplished. = Members #let member(body, role: "", mail: "") = { show link: set text(font: "Consolas") [#body, #role #link("mailto:" + mail)[<#mail>]] } - #member( role: "Lead Interviewer", mail: "<EMAIL>" )[<NAME>] - Design the interview process for the research. - Conduct and take written records of the interviews. - #member( role: "Data Analyzer", mail: "<EMAIL>" )[<NAME>] - Code the interview results into categories. - Analyze the data and draw conclusions from them. - #member( role: "Report Editor", mail: "<EMAIL>" )[<NAME>] - Write the assigned documents and research reports. - Typeset the documents with good readability. = Goals With this project being the very first group work of the GSND 5130, all team members hope to practice and establish a basic understanding towards a basic framework of an academical research. During the period of this project, the team will explore the causes of why Minecraft players often get tired of new savegames after a short period of time. A qualitative research on the topic will be conducted, with the classical methods including in-person interviews and/or online surveys. Each team member is assigned with a role for the project. Alex, being a former student in journalling, will take the role of the lead interviewer. He will design and conduct most of the interviews with the subjects and taken written records of the interview results. Shencheng will then perform qualitative analyzing methods on the results, code them into categories and summarize out clear conclusions. Lastly, Nianyi will collect all the information and typeset them into a final research report, due to his previous experience in typesetting and academical writing. Hopefully, each member could gain experiences of coorperating on a formal research and use them in future academical careers! = Behavioral Expectations To ensure a smooth cooperation between team members, the following behavioral expectations are to be obeyed by every members: - Respect each other. Treat each other as equal co-workers. Talk to team members as you would to other people. Never put irresponsible blames on any members, including yourself. - Reply promptly. Teamwork affairs are expected to be done in an coorperative way. Promptly replying to team members' messages is a precondition of cooperation. Don't let your teammates hang. - Get work done on time. Everybody should be responsible for their part of works. You need to finish your works on time regularly to be reliable. - Hold each other accountable. A team member's responsibility not only includes speed, but also quality. If you find someone is not doing their work well, feel free to point it out, but only with solid reasons. - Spread work appropriately. Do not fight for credits that you don't earn. = In-team Communication - For regular communication, a discord group chat is set up. All quick discussions over simple topics go on here. - For complex topics, use discord voice calls. - For even more complex or important topics, an in-person meeting is required. Such meetings should be planned ahead for at least one day, at an approriate time when all attending members are available. Meeting plannings could go in the discord server, via email, or any other effective ways. - Unnecessary phone calls should be avoided, especially at nights. = Decision Making - Important decisions should be made in an in-person meeting and only when every members agreed. - It is allowed to change a previous team decision, but the proposing member must provide sufficient reasons, and other members should be given sufficient time and freedom to decide whether agree or not. - In case a conflict arises, the following method should be used for final decision: - On professional topics, align with the member who is most skilled in the field; - Otherwise, vote. = Signatures #{ set align(center) set text(size: 14pt) let sig_length = 10em let placeholder(length: 1em) = { box(width: length, stroke: (bottom: 0.5pt)) } let sig_line() = { placeholder(length: sig_length) } let sig_date() = { box(stroke: none)[ #set align(center) #placeholder(length: 2em) / #placeholder(length: 2em) / #placeholder(length: 4em) ] } v(2em) table(columns: 3, stroke: none, row-gutter: 1em, sig_line(), sig_line(), sig_line(), sig_date(), sig_date(), sig_date(), ) }
https://github.com/DustVoice/dustypst
https://raw.githubusercontent.com/DustVoice/dustypst/main/langs.typ
typst
#let en = ( lang: "en", outline: "Chapters", packages: "Packages", note: "Note", tip: "Tip", important: "Important", warning: "Warning", caution: "Caution", ) #let de = ( lang: "de", outline: "Inhaltsverzeichnis", packages: "Pakete", note: "Anmerkung", tip: "Hinweis", important: "Wichtig", warning: "Warnung", caution: "Achtung", ) #let default_lang = en
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/patterns.typ
typst
// https://typst.app/project/pts91Veybk4FG5vSt7FKVk // patterns is how you make a chessboard // fill can be a pattern ... but strokes can also be a pattern // // todo: // // applications: chess-board ... from FEN // given a position ... find the next best position // typst will take over typesetting // it is the modern way of doing pdfs // best practices will emerge over time // javascript to typ ? rotational geometries // #let pattern-factory(fn, ..sink) = { // do the sizes // even an image can be a pattern // this is such an amazing language and tool } #let pat = pattern(relative: "parent", size: (30pt, 30pt), { place(line(start: (0%, 0%), end: (100%, 100%))) }) //#rect(fill: pat, width: 30pt, height: 30pt, stroke: 1pt) #let pat = pattern(size: (30pt, 30pt))[ #let n = 10 #for i in range(-n, n) { let unit = 5 // points to the southeast (y = -1x) // let start = (0% + unit * i * 1pt, 0%) // let end = (100% + i * unit * 1pt, 100%) // points to the northwest (y = 1x) let start = (0% + unit * i * 1pt, 100%) let end = (100% + i * unit * 1pt, 0%) place(line(start: start, end: end)) // different unit types can be merged together ... amazing // } ] #let size = 30 #rect(fill: pat, width: size * 1pt, height: size * 1pt, stroke: 1pt)
https://github.com/mitex-rs/mitex
https://raw.githubusercontent.com/mitex-rs/mitex/main/packages/mitex/lib.typ
typst
Apache License 2.0
#import "mitex.typ": mitex-wasm, mitex-convert, mitex-scope, mitex, mitext, mimath, mi
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/jogs/0.2.0/lib.typ
typst
Apache License 2.0
#let jogs-wasm = plugin("jogs.wasm") /// Run a Javascript code snippet. /// /// # Arguments /// * `code` - The Javascript code string to run. /// /// # Returns /// The result of the Javascript code. The type is the typst type which most closely resembles the Javascript type. /// /// # Example /// ```typ /// let result = eval-js("1 + 1") /// ``` #let eval-js(code) = if type(code) == "string" { cbor.decode(jogs-wasm.eval(bytes(code))) } else { cbor.decode(jogs-wasm.eval(bytes(code.text))) } #let compile-js(code) = if type(code) == "string" { jogs-wasm.compile(bytes(code)) } else { jogs-wasm.compile(bytes(code.text)) } #let list-global-property(bytecode) = cbor.decode(jogs-wasm.list_property_keys(bytecode)) #let call-js-function(bytecode, function-name, ..args) = cbor.decode(jogs-wasm.call_function(cbor.encode(( bytecode: bytecode, function_name: function-name, arguments: args.pos(), ))))
https://github.com/nafkhanzam/typst-common
https://raw.githubusercontent.com/nafkhanzam/typst-common/main/src/common/dates.typ
typst
//~ Dates #let today = datetime.today() #let display-year = today.display("[Year]") //~ Indonesian Dates #let ID-day = ("Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Min"); #let ID-days = ("Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu"); #let ID-month = ("Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des"); #let ID-months = ( "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember", ); #let ID-display-year = display-year #let ID-display-today = today.display("[day padding:none]") + " " + ID-months.at(today.month() - 1) + " " + display-year
https://github.com/Nrosa01/TFG-2023-2024-UCM
https://raw.githubusercontent.com/Nrosa01/TFG-2023-2024-UCM/main/Memoria%20Typst/capitulos/1.Introduction.typ
typst
== Motivation Sand simulators were a prominent subgenre during the 1990s, and remained popular until the early 2000s. During that time, many programs and games emerged that allowed people to interact with virtual worlds filled with simulated particles. This attracted both simulation lovers and video game developers. However, after a period of relative calm, we are witnessing a renaissance of the genre thanks to video games like Noita or sandbox simulators like Sandspiel. This project comes from the desire to immerse ourselves in the world of sand simulators. We want to explore its different aspects and characteristics as well as better understand the advantages and disadvantages of different development approaches for the user, in order to contribute to its evolution and expansion, since we consider that it is a subgenre that can provide very good gaming and user experiences. In short, we want to understand and help improve arena simulators to make them more useful and effective for users. == Objectives <Objectives> The main objective of this TFG is to study the behavior and ease of learning of different users using different implementations of sand simulators. The functionality of each implementation will be assessed using the following parameters: - Performance comparison: they will be compared under the same conditions, both at the hardware level and in the use of particles, measuring the final performance achieved. This performance will be compared using the ratio of number of particles / frames per second achieved. Ideally, you will find out the largest number of particles that each simulator can support while maintaining 60 fps. - Comparison of usability: the behavior of a group of users will be studied to assess the ease of use and understanding of expansion systems that allow expansion by the user. The speed of completing a set of tasks will be assessed, as well as any possible misunderstandings they may have when using the system. With these analyses, we aim to explore the characteristics that contribute to an optimal user experience in an arena simulator, both in terms of ease of use and expected performance of the system. By better understanding these characteristics, areas for improvement can be identified and recommendations developed to optimize the overall user experience with arena simulators. Our goal is to find a balance between performance and extensibility that provides both a playful environment for casual users and a development base for developers interested in arena simulators. == Work plan The work methodology to be used will be a variant of Scrum tailored to our needs. A task board will be created to reflect the tasks to be performed, the status of each task, and the estimated time for their completion. There will be no daily meetings, but to-do tasks will be assigned weekly, along with weekly meetings to review the project status and adjust the task board accordingly. Additionally, bi-weekly meetings with the supervisor are planned to review the project status and receive feedback on the work done, as well as guidance on future tasks. Regarding the work, the first step will be to conduct preliminary research on the fundamental concepts of cellular automata and sand simulators, as well as existing systems to understand how problems have been approached in the past. This research is expected to take approximately two months. After this, four implementations are planned: - Base native simulation: This will be the simulation used as the baseline for comparing the others. It must be efficient and establish the foundations of particle processing. This implementation will be difficult to expand due to this. It is expected to be implemented in C or C++ due to familiarity with the language. This implementation is expected to take between one and one and a half months. - GPU simulation: This implementation will be done in a programming language that allows GPU code execution, such as CUDA or OpenCL. The goal of this implementation is to explore the feasibility of performing particle simulation on the GPU and to compare its performance with the other implementations. This implementation is also expected to be difficult to expand. It is expected to be completed in one month. - Native simulation extended with a scripting language: It will be necessary to research and choose a scripting language that allows the base simulation to be easily extended while maintaining the highest possible performance. This implementation is expected to take between one and two months. - Simulation accessible via visual programming language: Libraries and frameworks that allow code or data to be defined through visual programming will be investigated. This implementation is expected to be the easiest to expand and the most accessible for non-technical users. The possibility of running this simulation on the web for greater accessibility will be explored. This implementation is expected to take between one and two months. The possibility of creating more simulators will be considered if the research reveals an alternative that adds value to the comparison. After completing the different implementations, user tests will be conducted to compare the results obtained from each. The data obtained will be analyzed, and the results will be compared to draw conclusions about the advantages and disadvantages of each implementation. These tests are expected to take two to three weeks. == Relevant links #set text(10pt) Project repository: https://github.com/Nrosa01/TFG-2023-2024-UCM Base C++ simulation: https://youtu.be/Z-1gW8dN7lM GPU simulation: https://youtu.be/XyaOdjyOXFU Simulation with Lua: https://youtu.be/ZlvuIUjA7Ug Web simulation with Blockly: https://youtu.be/obA7wZbHb9M
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/02-measure-theory/01-set-systems.typ
typst
#import "../../utils/core.typ": * == Системы множеств #denote[ $A union.sq B$ --- объединение $A$ и $B$, такое, что $A sect B != nothing$. $union.sq.big_(k = 1)^n A_k$ --- объединение множеств $A_1, ..., A_n$ и $A_j sect A_j = nothing$ для всех $i != j$. Такие объединения называются _дизъюнктными объединениями_, а множества из них называют _дизъюнктными_. ] #def[ ${E_alpha}$ --- разбиение множества $E$, если $ E = union.sq.big_(alpha in I) E_alpha. $ ] #notice(name: "Напоминание")[ $ X without union.big_(alpha in I) E_alpha &= sect.big_(alpha in I)(X without E_alpha), \ X without sect.big_(alpha in I) E_alpha &= union.big_(alpha in I)(X without E_alpha). $ ] #def(label: "def-sigma-delta-props")[ $Aa$ --- семейство подмножеств множества $X$. Будем говорить, что множество имеет свойства: - $(sigma_0)$, если $A, B in Aa$, то $A union B in Aa$ - $(delta_0)$, если $A, B in Aa$, то $A sect B in Aa$ - $(sigma)$, если $A_n in Aa space forall n in NN$, то $union.big_(n = 1)^oo A_n in Aa$ - $(delta)$, если $A_n in Aa space forall n in NN$, то $sect.big_(n = 1)^oo A_n in Aa$ ] #def(label: "def-symm-system")[ $Aa$ --- симметричная система, если $A in Aa ==> X without A in Aa.$ ] #pr[ Пусть $Aa$ симметричная система множеств. Тогда $ (sigma_0) <==>^rf("def-sigma-delta-props") (delta_0) space #[и] space (sigma) <==>^rf("def-sigma-delta-props") (delta). $ ] #proof[ "$<==$" $ X \\ (A union B) = (X \\ A) sect (X \\ B) $ "$==>$" $ X \\ (A sect B) = (X \\ A) union (X \\ B) $ ] #def(label: "def-algebra")[ Система множеств $Aa$ называется _Алгеброй_, если $Aa$ --- симметричная система#rf("def-symm-system") и $(sigma_0)$, $(delta_0)$#rf("def-sigma-delta-props") и $nothing in Aa$, то есть если $A, B in Aa$, то $X without A$, $X without B$, $A union B$ и $A sect B$ лежат в системе $Aa$. ] #def(label: "def-salgebra")[ $Aa$ -- $sigma$-алгебра, если $Aa$ -- алгебра и $(sigma), (delta) in Aa$ ] #props(label: "sigma-algebra-props")[ 1. Если $Aa$ --- $sigma$-алгебра, то $Aa$ --- алгбера. 2. Если $Aa$ --- алгебра, то $X in Aa$. 3. Если $Aa$ --- алгебра, $A, B in Aa$, то $A without B in Aa$. 4. Если $Aa$ --- алгебра, то $A_1, ..., A_n in Aa ==> union.big_(j = 1)^n A_j, sect.big_(j = 1)^n A_j in Aa$. ] #proof[ 3. $A without B = A sect (X without B)$ 4. Индукция ] #examples[ 1. Ограниченные в $RR^n$ и их дополнения --- алгебра, но не $sigma$-алгебра. 2. $2^X$ --- и алгебра, и $sigma$-алгебра. 3. _Индуцированная алгебра_ ($sigma$-алгебра): \ $Aa subset 2^X$ --- алгебра, $Y subset X$, $Bb := {A sect Y bar A in Aa}$ --- алгебра подмножеств в $Y$. #proof[ $B in Bb <==> B = B' sect Y, B' in Aa ==> Y without B = Y without (B' sect Y) = Y without B' = (Y without B') sect Y\ (Y without B') in Aa ==> Y without B in Bb$ $B_1 in Bb, B_2 in Bb <==> ... ==> B_1 sect B_2 = (Y sect B_1 ') sect (Y sect B_2 ') = Y sect (B_1 ' sect B_2 ')\ (B_1 ' sect B_2 ') in A ==> B_1 sect B_2 in Bb$ ] 4. Пусть $Aa_alpha$ --- алгебра/$sigma$-алгебра подмножеств в $X$. Тогда $sect.big_(alpha in I) Aa_alpha$ --- алгебра ($sigma$-алгебра) подмножеств в $X$. 5. Пусть $A$ и $B$ --- множества. Наименьшая алгебра, содержащая $A$ и $B$ - все объединения подмножеств ${A without B, B without A, A sect B, X without (A union B)}$, всего $2^4 = 16$ множеств. #figure(grid(columns: 8, gutter: 0.3cm, ..for atom in range(16) { let plot = cetz.canvas(length: 0.25cm, { import cetz.draw: * let c = luma(90%) rect((-3.5, -2.5), (3.5, 2.5), fill: if atom < 8 {c} else {blue.lighten(50%)}) rect((-3, -2), (1, 1), fill: if calc.rem(atom, 8) < 4 {c} else {red.lighten(50%)}) rect((-2, -1), (3, 2), fill: if calc.rem(atom, 4) < 2 {c} else {green.lighten(50%)}) rect((-2, -1), (1, 1), fill: if calc.rem(atom, 2) < 1 {c} else {yellow.lighten(50%)}) }) (plot,) })) ] #let Ee = $cal(E)$ #let Rr = $cal(R)$ #th(label: "borel-set")[ $Ee$ --- система подмножеств $X$. Тогда существует наименьшая по включению $sigma$-алгебра подмножеств в $X$, содержащая $Ee$. ] #proof[ Рассмотрим всевозможные $sigma$-алгебры $Aa_alpha supset Ee$ $ ==> sect.big_(alpha in I) Aa_alpha space #[--- $sigma$-алгебра и она содержит $Ee$] $ ] #def(glue: true)[ Такая#rf("borel-set") $sigma$-алгебра называется _Борелевской оболочкой множества $Ee$_. Обозначается $Bb(Ee)$. ] #def(label: "borel-algebra")[ Минимальная $sigma$-алгебра, содержащая все открытые множества в $RR^n$ называется _Борелевской $sigma$-алгеброй_. Обозначается $Bb^n$. ] #notice[ $underbrace(Bb^n, "континуум") != underbrace(2^RR^n, #[больше \ континуума])$ // много и очень много // дохуя и пиздец дохуя ] #def(label: "def-ring")[ $Rr$ --- _кольцо_ подмножеств $X$, если $A, B in Rr ==> A union B, A sect B, A without B in Rr$. Пустые кольца не рассматриваются. ] #notice[ $ nothing in Rr space #[так как $A without A = nothing$] $ $X$ не обязательно лежит в $Rr$. \ Если $X$ лежит в $Rr$, то $Rr$ --- алгебра. ] #def(label: "def-semiring")[ $Pp$ --- _полукольцо_ подмножеств $X$, если 1. $nothing in Pp$ 2. $A, B in Pp ==> A sect B in Pp$ 3. $A, B in Pp ==> exists Q_1, ..., Q_m in Pp$ такие, что $A without B = union.sq.big_(j=1)^m Q_j$ ] #examples[ 1. Все возможные полуинтервалы $lr((a, b]) in RR$ --- полукольцо. 2. $Aa := { lr((a, b]) bar a, b in QQ }$ ] #lemma(label: "lem-disjoint-union")[ $union.big A_n = union.sq.big (A_n without union.big_(k = 1)^(n - 1) A_k)$ ] #proof[ Пусть $B_n := A_n without union.big_(k = 1)^(n - 1) A_k subset A_n$. Если $i < j$, то $ B_j sect A_i = nothing ==> B_j sect B_i = nothing. $ Значит $B_j$ --- дизъюнктны. - "$supset$": $A_n supset B_n$ - "$subset$": Берем все $x in union.big A_n$. Пусть $m$ --- наименьший номер, для которого $x in A_m$. Тогда $x in B_m$. ] #th(label: "semiring-disjoint-union")[ $Pp$ --- полукольцо, $P_1, P_2, ... in Pp$. Тогда 1. $display(P without union.big_(j = 1)^n P_j = union.sq.big_(i = 0)^m Q_i)$ для некоторых $Q_i in Pp$. 2. $display(union.big_(k = 1)^n P_k = union.sq.big_(k = 1)^n union.sq.big_(j = 1)^m_k Q_(k j))$, где $Q_(k, j) in Pp$ и $Q_(k j) subset P_k$. 3. В 2) можно написать счетное объединение. ] #proof[ 1. Индукция по $n$: $ P without union.big_(j=1)^(n-1) P_j = union.sq.big_(i=1)^m Q_i \ P without union.big_(j=1)^n P_j = (P without union.big_(j=1)^(n-1) P_j) without P_n = (union.sq.big_(i=1)^m Q_i) without P_n = union.sq.big_(i=1)^m (Q_i without P_n). $ 2. $ union.big_(k = 1)^n P_k = union.sq.big_(k = 1)^n (P_k without union.big_(j = 1)^(k - 1) P_j) = union.sq.big_(k - 1)^n union.sq.big_(j = 1)^(m_k) Q_(k j). $ ] #let Qq = $cal(Q)$ #th(name: [декартово произведение полуколец], label: "cartesian-semiring-prod")[ $Pp$ --- полукольцо подмножества $X$, $Qq$ --- полукольцо подмножества $Y$. $ Pp times Qq = {A times B: A in Pp, B in Qq} space #[--- полукольцо подмножеств в $X times Y$]. $ ] #proof[ $nothing in Pp times Qq$ Пусть $A_1 times B_1$ и $A_2 times B_2 in Pp times Qq$. Тогда $ (A_1 times B_1) sect (A_2 times B_2) = (A_1 sect A_2) times (B_1 sect B_2) in Pp times Qq. $ $ (A_1 times B_1) without (A_2 times B_2) = A_1 times (B_1 without B_2) union.sq (A_1 without A_2) times (B_1 sect B_2) =\ union.sq.big_(j=1)^m underbrace(A_1 times Q_j, in Pp times Qq) union.sq union.sq.big_(i = 1)^n (underbrace(P_i times (B_1 sect B_2), in Pp times Qq)) $ ] #def(label: "def-cell")[ Пусть $a, b in RR^m$. _Открытым параллелепипедом_ $(a, b)$ называется $ (a_1, b_1) times (a_2, b_2) times ... times (a_m, b_m). $ _Замкнутым параллелепипедом_ $[a, b]$ называется $ [a_1, b_1] times [a_2, b_2] times ... times [a_m, b_m]. $ _Ячейкой_ $(a, b]$ называется $ lr((a_1, b_1]) times lr((a_2, b_2]) times ... times lr((a_m, b_m]). $ ] #pr(label: "cell-through-cuboid")[ Непустая ячейка представляется в виде счетного пересечения убывающей последовательности вложенных открытых параллелепипедов и в виде счетного объединения возрастающей последовательности вложенных замкнутых параллелепипедов. ] #proof[ $ A_n &:= [a_1 + 1/n, b_1] times [a_2 + 1/n, b_2] times ... times [a_m + 1/n, b_m] \ U_n &:= (a_1, b_1 + 1/n) times (a_2, b_2 + 1/n) times ... times (a_m, b_m + 1/n) \ $ ] #denote(label: "def-R-cells")[ $ Pp^m := { "ячейки в" RR^m } supset Pp^m_QQ := { #block[ячейки в $RR^m$ у которых все \ координаты всех вершин рациональны] } $ ] #th(label: "cells-semiring")[ $Pp^m$ и $Pp_(QQ)^m$ --- полукольца ] #th(label: "open-through-cell")[ Всякое непустое открытое множество $G subset RR^m$ представляется в виде дизъюнктного объединения счетного числа ячеек, которые вместе с замыканием содержатся в $G$. Более того, ячейки можно брать с рациональными координатами. ] #let Cl = math.op("Cl") #proof[ #figure[ #image("../../images/pupailupa.svg", width: 50%) ] $ x in G ==> exists r in RR space overline(B)_r (x) subset G ==> \ exists C_x in Pp_(QQ)^m space C_x subset overline(B)_r (x) space ("смотри картинку") ==> \ G = Union_(x in G) C_x $ Это счетное объединение, поскольку все ячейки имеют рациональные координаты, а значит, его можно переделать в дизъюнктное не испортив ячеек. ] #follow(label: "borel-set-over-cells")[ Борелевская оболочка ячеек $Bb(Pp^m) = Bb(Pp_(QQ)^m) = Bb^m$ ] #proof[ 1. Знаем, что $Pp^m supset Pp_(QQ)^m ==> Bb(Pp^m) supset Pp_(QQ)^m ==> Bb(Pp^m) supset Bb(Pp_(QQ)^m)$ (Из-за минимальности#rf("borel-set")) 2. Любое открытое множество --- счетное объединение ячеек с рациональными координатами вершин#rf("open-through-cell"), поэтому открытые множества лежат в $Bb(Pp_(QQ)^m) ==> Bb^m subset Bb(Pp_(QQ)^m)$ 3. Знаем, что ячейка --- счетное пересечение открытых множеств#rf("cell-through-cuboid"), значит, что все ячейки содержаться в $Bb^m ==> Bb(Pp^m) subset Bb^m$. ]
https://github.com/Functional-Bus-Description-Language/Specification
https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/expressions.typ
typst
#pagebreak() = Expressions An expression is a formula that defines the computation of a value by applying operators and functions to operands. ``` expression ::= bool_literal | integer_literal | real_literal | string_literal | bit_string_literal | time_literal | declared_identifier | qualified_identifier | unary_operation | binary_operation | function_call | subscript | parenthesized_expression | range_expression | expression_list ``` The function call is used to call one of built-in functions. `function_call ::= declared_identifier`*`(`*` [ expression { `*`,`*` expression } ] `*`)`* The subscript is used to refer to a particular element from the expression list. `subscript ::= declared_identifier`*`[`*` expression `*`]`* The parenthesized expression may be used to explicitly set order of operations. `parenthesized_expression ::= `*`(`*` expression `*`)`* The expression list may be used to create a list of expressions. `expression_list ::= `*`[`*` [ expression { `*`,`*` expression } ] `*`]`* == Operators === Unary Operators `unary_operation ::= unary_operator expression` `unary_operator ::= unary_arithmetic_operator | unary_bitwise_operator` `unary_arithmetic_operator ::= `*`-`* `unary_bitwise_operator ::= `*`!`* #set align(center) #block(breakable:false)[ #table( stroke: none, align: center, columns: (2cm, 3cm, 3cm, 3cm), table.vline(x: 1, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 2, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 3, start: 1, stroke: (thickness: 0.1pt)), table.cell(colspan: 4)[FBDL unary operators], table.hline(), [*Token*], [*Operation*], [*Operand Type*], [*Result Type*], table.hline(), [`-`], [Opposite], [Integer \ Real], [Integer \ Real], table.hline(stroke: (thickness: 0.1pt)), [`!`], [Negation], [Bit string \ Integer], [Bit string \ Integer], ) ] #set align(left) === Binary Operators `binary_operation ::= expression binary_operator expression` ``` binary_operator ::= binary_arithmetic_operator | binary_bitwise_operator | binary_comparison_operator | binary_logical_operator | binary_range_operator ``` `binary_arithmetic_operator ::= `*`+`*` | `*`-`*` | `*`*`*` | `*`/`*` | `*`%`*` | `*`**`* `binary_bitwise_operator ::= `*`<<`*` | `*`>>`* `binary_comparison_operator ::= `*`==`*` | `*`!=`*` | `*`<`*` | `*`<=`*` | `*`>`*` | `*`>=`* `binary_logical_operator ::= `*`&&`*` | `*`||`* `binary_range_operator ::= `*`:`* #set align(center) #block(breakable:false)[ #table( stroke: none, align: center, columns: (1.5cm, 3cm, 4cm, 4cm, 2.5cm), table.vline(x: 1, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 2, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 3, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 4, start: 1, stroke: (thickness: 0.1pt)), table.cell(colspan: 5)[FBDL binary arithmetic operators], table.hline(), [*Token*], [*Operation*], [*Left Operand Type*], [*Right Operand Type*], [*Result Type*], table.hline(), [\ \ `+`], [\ \ Addition], [Integer \ Integer \ Real \ Real \ Time], [Integer \ Real \ Integer \ Real \ Time], [Integer \ Real \ Real \ Real \ Time], table.hline(stroke: (thickness: 0.1pt)), [\ `-`], [\ Subtraction], [Integer \ Integer \ Real \ Real], [Integer \ Real \ Integer \ Real], [Integer \ Real \ Real \ Real], table.hline(stroke: (thickness: 0.1pt)), [\ \ `*`], [\ \ Multiplication], [Integer \ Integer \ Real \ Real \ Integer \ Time], [Integer \ Real \ Integer \ Real \ Time \ Integer], [Integer \ Real \ Real \ Real \ Time \ Time], table.hline(stroke: (thickness: 0.1pt)), [\ `-`], [\ Division], [Integer \ Integer \ Real \ Real], [Integer \ Real \ Integer \ Real], [Real \ Real \ Real \ Real], table.hline(stroke: (thickness: 0.1pt)), [`%`], [Remainder], [Integer], [Integer], [Integer], table.hline(stroke: (thickness: 0.1pt)), [\ `**`], [\ Exponentiation], [Integer \ Integer \ Real \ Real], [Integer \ Real \ Integer \ Real], [Integer \ Real \ Real \ Real], ) ] #block(breakable:false)[ #table( stroke: none, align: center, columns: (1.5cm, 3cm, 4cm, 4cm, 2.5cm), table.vline(x: 1, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 2, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 3, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 4, start: 1, stroke: (thickness: 0.1pt)), table.cell(colspan: 5)[FBDL binary bitwise operators], table.hline(), [*Token*], [*Operation*], [*Left Operand Type*], [*Right Operand Type*], [*Result Type*], table.hline(), [`<<`], [Left Shift], [Integer], [Integer], [Integer], table.hline(stroke: (thickness: 0.1pt)), [`>>`], [Right Shift], [Integer], [Integer], [Integer], table.hline(stroke: (thickness: 0.1pt)), [`&`], [And], [Bit String \ Integer], [Bit String \ Integer], [Bit String \ Integer], table.hline(stroke: (thickness: 0.1pt)), [`|`], [Or], [Bit String \ Integer], [Bit String \ Integer], [Bit String \ Integer], table.hline(stroke: (thickness: 0.1pt)), [`^`], [Xor], [Bit String \ Integer], [Bit String \ Integer], [Bit String \ Integer], ) ] #block(breakable:false)[ #table( stroke: none, align: center, columns: (1.5cm, 3cm, 4cm, 4cm, 2.5cm), table.vline(x: 1, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 2, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 3, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 4, start: 1, stroke: (thickness: 0.1pt)), table.cell(colspan: 5)[FBDL binary comparison operators], table.hline(), [*Token*], [*Operation*], [*Left Operand Type*], [*Right Operand Type*], [*Result Type*], table.hline(), [\ `==`], [\ Equality], [Integer \ Integer \ Real \ Real], [Integer \ Real \ Integer \ Real], [Bool \ Bool \ Bool \ Bool], table.hline(stroke: (thickness: 0.1pt)), [\ `!=`], [\ Nonequality], [Integer \ Integer \ Real \ Real], [Integer \ Real \ Integer \ Real], [Bool \ Bool \ Bool \ Bool], table.hline(stroke: (thickness: 0.1pt)), [\ `<`], [\ Less Than], [Integer \ Integer \ Real \ Real], [Integer \ Real \ Integer \ Real], [Bool \ Bool \ Bool \ Bool], table.hline(stroke: (thickness: 0.1pt)), [\ `<=`], [\ Less Than \ or Equal], [Integer \ Integer \ Real \ Real], [Integer \ Real \ Integer \ Real], [Bool \ Bool \ Bool \ Bool], table.hline(stroke: (thickness: 0.1pt)), [\ `>`], [\ Greater Than], [Integer \ Integer \ Real \ Real], [Integer \ Real \ Integer \ Real], [Bool \ Bool \ Bool \ Bool], table.hline(stroke: (thickness: 0.1pt)), [\ `>=`], [\ Greater Than \ or Equal], [Integer \ Integer \ Real \ Real], [Integer \ Real \ Integer \ Real], [Bool \ Bool \ Bool \ Bool], ) ] #block(breakable:false)[ #table( stroke: none, align: center, columns: (1.5cm, 3cm, 4cm, 4cm, 2.5cm), table.vline(x: 1, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 2, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 3, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 4, start: 1, stroke: (thickness: 0.1pt)), table.cell(colspan: 5)[FBDL binary logical operators], table.hline(), [*Token*], [*Operation*], [*Left Operand Type*], [*Right Operand Type*], [*Result Type*], table.hline(), [`&&`], [Short-circuiting \ logical AND], [Bool], [Bool], [Bool], table.hline(stroke: (thickness: 0.1pt)), [`||`], [Short-circuiting \ logical OR], [Bool], [Bool], [Bool], ) ] #block(breakable:false)[ #table( stroke: none, align: center, columns: (1.5cm, 3cm, 4cm, 4cm, 2.5cm), table.vline(x: 1, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 2, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 3, start: 1, stroke: (thickness: 0.1pt)), table.vline(x: 4, start: 1, stroke: (thickness: 0.1pt)), table.cell(colspan: 5)[FBDL binary range operator], table.hline(), [*Token*], [*Operation*], [*Left Operand Type*], [*Right Operand Type*], [*Result Type*], table.hline(), [`:`], [Range], [Integer], [Integer], [Range], ) ] #set align(left) The bool data type is not valid operand type for the most of the binary operations. However, as there is the rule for implicit conversion from the bool data type to the integer data type, all operations accepting the integer operands work also for the bool operands. == Functions The FBDL does not allow defining custom functions for value computations. However, FBDL has following built-in functions: *`abs`*`(x integer|real) integer|real` \ #pad(left: 1em)[ The `abs` function returns the absolute value of `x`. ] *`bool`*`(x integer) bool` \ #pad(left: 1em)[ The `bool` function returns a value of the bool type converted from a value `x` of the integer type. If `x` equals 0, then the `false` is returned. In all other cases the `true` is returned. ] *`ceil`*`(x real) integer` \ #pad(left: 1em)[ The `ceil` function returns the least integer value greater than or equal to `x`. ] *`floor`*`(x real) integer` \ #pad(left: 1em)[ The `floor` function returns the greatest integer value less than or equal to `x`. ] *`log2`*`(x real) integer|real` \ #pad(left: 1em)[ The `log2` function returns the binary logarithm of `x`. ] *`log10`*`(x real) integer|real` \ #pad(left: 1em)[ The `log10` function returns the decimal logarithm of `x`. ] *`log`*`(x, b real) integer|real` \ #pad(left: 1em)[ The `log` function returns the logarithm of `x` to the base `b`. ] *`u2`*`(x, w integer) integer` \ #pad(left: 1em)[ The `u2` function returns two’s complement representation of `x` as an integer assuming width `w`. For example, `u2(-1, 8)` returns `255`. ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/cjk-punctuation-adjustment_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(width: 21em) #set text(lang: "zh", region: "CN", font: "Noto Serif CJK SC") // These examples contain extensive use of Chinese punctuation marks, // from 《Which parentheses should be used when applying parentheses?》. // link: https://archive.md/2bb1N (〔中〕医、〔中〕药、技)系列评审 (长三角[长江三角洲])(GB/T 16159—2012《汉语拼音正词法基本规则》) 【爱因斯坦(Albert Einstein)】物理学家 〔(2009)民申字第1622号〕 “江南海北长相忆,浅水深山独掩扉。”([唐]刘长卿《会赦后酬主簿所问》) 参看1378页〖象形文字〗。(《现代汉语词典》修订本)
https://github.com/darioglasl/Arbeiten-Vorlage-Typst
https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/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: "", subtitle: "", university: "", semester: "", arbeit: "", bibliographyFilePath: "", abstract: [], managementSummary: [], authors: (), supervisors: (), industrialPartners: (), date: none, logoIndustrialPartner: none, ostLogo: none, enableOutlines: true, body, ) = { // Set the document's basic properties. set document(author: authors.map(a => a.name), title: title) set text(font: "Linux Libertine", lang: "de") show math.equation: set text(weight: 400) show link: underline set page(numbering: none) let headingFont = "Arial"; show heading.where(level: 1): h => { v(50pt) align(right, text(size: 1.7em, font: headingFont, h)) } show heading.where(level: 2): h => { text(size: 1.1em, font: headingFont, h) } show heading.where(level: 3): h => { text(size: 1.1em, font: headingFont, h) } show heading.where(level: 4): h => { text(size: 1.05em, font: headingFont, h) } // --- Title page --- // Logos if logoIndustrialPartner != none and ostLogo != none { // TODO: align it properly grid( columns: (1fr, 1fr), gutter: 1em, image(logoIndustrialPartner, width: 65%), image(ostLogo, width: 100%), ) } v(6fr) smallcaps(text(1.1em, [#date - #arbeit #semester])) v(0.6fr) text(2em, weight: 700, title) if subtitle != "" { v(0.3fr) text(1.3em, subtitle) } // Author information. pad( top: 1em, right: 16%, grid( columns: (1.3fr, 1fr, 1fr, 1fr), gutter: 2em, [#smallcaps("Studierende:")], ..authors.map(author => align(start)[ *#author.name* \ #author.email ]), ), ) // Supervisor information. pad( top: 0.7em, right: 20%, grid( columns: (1.3fr, 3fr), gutter: 1em, [#smallcaps("Betreuer:")], ..supervisors.map(sv => align(start)[ *#sv.name* \ #sv.email ]), ), ) // Industrial partner information. pad( top: 0.7em, right: 20%, grid( columns: (1.3fr, 3fr), gutter: 1em, [#smallcaps("Industrie-Partner:")], ..industrialPartners.map(ip => align(start)[ *#ip.name* \ #ip.company \ #ip.email ]), ), ) v(2.4fr) pagebreak() // --- Abstract page --- set par(justify: true) set page( numbering: "I", number-align: center, header: [ #set text(10pt) #smallcaps(title) #h(1fr) #text(date) ] ) counter(page).update(1) v(1fr) align(center)[ #heading( outlined: false, numbering: none, bookmarked: true, text(0.85em, smallcaps[Abstract]) ) ] v(10pt) abstract v(1.618fr) pagebreak() // --- Management Summary page --- v(1fr) align(center)[ #heading( outlined: false, numbering: none, bookmarked: true, text(0.85em, smallcaps[Management Summary]), ) ] v(10pt) managementSummary v(1.618fr) pagebreak() // --- Table of contents --- { show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) strong(it) } heading(outlined: false,numbering: none, bookmarked: true, [Inhaltsverzeichnis]) outline(depth: 3, indent: true, title: none) } pagebreak() // --- Main body --- set page(numbering: "1 / 1", number-align: center) set heading(numbering: "1.1", supplement: [Kapitel]) body pagebreak() set heading(numbering: "A.1") counter(heading).update(0) // --- Outlines --- if enableOutlines { heading("Glossar") include "glossar.typ" pagebreak() heading("Tabellenverzeichnis") outline(title: none, target: figure.where(kind: table)) pagebreak() heading("Abbildungsverzeichnis") outline(title: none, target: figure.where(kind: image)) pagebreak() heading("Codeverzeichnis") outline(title: none, target: figure.where(kind: "Code-Fragment")) pagebreak() } // Bibliography if bibliographyFilePath != "" { heading("Bibliographie") bibliography(bibliographyFilePath, title: none, style: "ieee") pagebreak() } include "Anhang/00_index.typ" }
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/uebungen/5/main.typ
typst
= Heaps == Mergesort und Quicksort === Mergesort ==== Rekursionsbaum #import "/notizen/sortieralgorithmen/mergesort/recursion.typ": mergesort_recursion #{ set align(center) set text(size: 11pt) set table.cell(inset: (x: 1pt, y: 2pt), stroke: none) show table: box.with(stroke: 1pt) mergesort_recursion( (-5, 13, -32, 7, -3, 17, 23, 12, -35, 19), spacing: 0pt ) } ==== In Python ```python def merge(a, i, j, l): while i < j and j <= l: if a[j] < a[i]: a.insert(i, a.pop(j)) j += 1 i += 1 def mergesort(a, f, l): if f >= l: return m=(f+l)//2 mergesort(a, f, m) mergesort(a, m+1, l) merge(a, f, m+1, l) a=[-5, 13, -32, 7, -3, 17, 23, 12, -35, 19] mergesort(a, 0, len(a)-1) print(a) ``` === Heapsort ==== Demonstration 0. Eingabe #import "heap.typ": heap #let nums = (-5, 13, -32, 7, -3, 17, 23, 12, -35, 19) #heap(nums) 1. BuildHeap #include "buildheap.typ" 2. Sortieren #include "heapsort.typ" ==== In Python 1. Heapify (a: Eingabeliste, i: Wurzel, n: Heapgröße, j: Maximum) ```python j = max( i, 2*i+1, 2*i+2, key=lambda i: a[i] if i < n else -math.inf ) if i != j: a[i], a[j] = a[j], a[i] heapify(a, j, n) ``` 2. BuildHeap (a: Eingabeliste) ```python for i in range(len(a)//2-1, -1, -1): heapify(a, i, len(a)) ``` 3. HeapSort (a: Eingabeliste) ```python build_heap(a) for i in range(len(a)-1, 0, -1): a[0], a[i] = a[i], a[0] heapify(a, 0, i) ```
https://github.com/JvandeLocht/assignment-template-typst-hfh
https://raw.githubusercontent.com/JvandeLocht/assignment-template-typst-hfh/main/layout/registration_certificate.typ
typst
MIT License
#import "/utils/formfield.typ": * #let registrationCertificate( author: "", birthdate: datetime, title: "", degree: "", program: "", supervisor: "", startDate: datetime, submissionDate: datetime, currentDate: datetime, body, ) = { // Set the document's basic properties. set page( margin: (left: 20mm, right: 20mm, top: 20mm, bottom: 20mm), ) // Save heading and body font families in variables. let body-font = "New Computer Modern" let sans-font = "New Computer Modern Sans" // Set body font family. set text( font: body-font, size: 12pt, lang: "en" ) align( right, stack( dir: ttb, spacing: 10pt, image("/figures/tum_logo.png", width: 20%), text(font: sans-font, weight: "bold", "Technical University \n of Munich") ) ) v(1.5cm) align(left, text(font: sans-font, 1.3em, weight: "bold", "Bestätigung zur Anmeldung der " + degree + "arbeit")) grid( columns: 2, row-gutter: 10mm, column-gutter: 6mm, formField("Name der/des Studierenden", author, length: 90%), formField("Geburtsdatum", birthdate.display("[day].[month].[year]"),length: 90%), formField("Studiengang", program, length: 90%), formField("Titel der Arbeit", title, length: 90%) ) v(1.5cm) "Hiermit bestätigen wir, dass der Kandidat/die Kandidatin sich am " + startDate.display("[day].[month].[year]") + " zur " + degree + "arbeit angemeldet hat. \n" body v(1.5cm) grid( columns: 2, column-gutter: 2cm, formField("Datum", currentDate.display("[day].[month].[year]"), length: 90%), formField(supervisor, " ", length: 90%) ) }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/frac-02.typ
typst
Other
// Test large fraction. $ x = (-b plus.minus sqrt(b^2 - 4a c))/(2a) $
https://github.com/Clay438/3bao-hbut-typst
https://raw.githubusercontent.com/Clay438/3bao-hbut-typst/master/每科三问.typ
typst
#set page(width: 29.7cm,height: 21cm,margin:(top:3cm,bottom:3.8cm,left: 3.2cm,right: 3.8cm,)) #let heiti = ("Times New Roman", "Heiti SC", "Heiti TC", "SimHei") #let songti = ("Times New Roman", "Songti SC", "Songti TC", "SimSun") #let fangson = ("Times New Roman", "FangSong SC", "FangSong TC", "SimSun") #align(center, text(size:16pt,font: heiti,weight: "bold")[ 湖北工业大学 2023/2024 学年(上)本科生课程问题探究活动记录表 ]) #text(15pt,font: songti,weight: "bold")[课程:学号:姓名:班级:成绩:] #table( align: (horizon), rows: (0.7cm,auto,auto,auto,auto), columns: (2cm,auto,auto,auto,2.68cm), inset: 14pt, [#text(14pt,font: songti,weight: "bold")[序号];], [#text(14pt,font: songti,weight: "bold")[问题(或课题)];], [#text(14pt,font: songti,weight: "bold")[提出问题缘由];], [#text(14pt,font: songti,weight: "bold")[初步研究思考或方向];], [#text(14pt,font: songti,weight: "bold")[备注];], [#text()[1]], [这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试], [这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试], [这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试], table.cell(rowspan: 3)[#text(10.5pt,font: songti)[(本栏填写学生对问题或课题进行深入研究之后,是否形成较为成熟的作品,如学术论文初稿、专利申报、实物产品等,具体的作品内容另外附页。本栏为加分项)]], [2], [这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试], [这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试], [], [3], [这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试这是一个测试,这是一个测试,这是一个测试,这是一个测试,这是一个测试], [], [], [#text(14pt,font: songti)[教师评分]], [#text(14pt,font: songti)[占比40%]], [#text(14pt,font: songti)[占比30%]], [#text(14pt,font: songti)[占比30%]], [#text(14pt,font: songti)[0-20分]], ) #text(12pt,font: fangson)[【注】 1.本表由每位学生自主提出与本课程相关的最有价值(或最有代表性)的三个问题(或课题);2.教师评阅每科三问时,根据问题的深度与创新性(占比40%)、提出问题的缘由(占比30%)、初步研究思考(占比30%),进行综合评分,备注栏作为加分项,按0-20分进行评价;3.本表作为过程性考核之一,计入总评成绩。]
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/05-complex-functions/08-generating-functions.typ
typst
#import "../../utils/core.typ": * == Производящие функции #ticket[Производящие функции. Операции с производящими функциями. Задача о размене.] #remind(name: "<NAME>")[ Если $A(z) = sum_(n = 0)^oo a_n z^n$, и $B(z) = sum_(n = 0)^oo b_n z^n$. Тогда $ A(z) B(z) = sum_(n = 0)^oo c_n z^n, "где" c_n = a_0 b_n + a_1 b_(n-1) + a_2 b_(n-2) + ... + a_n b_0. $ $c_n$ --- свертка последовательностей $a_n$ и $b_n$. ] #def[ Если $a_n$ --- последовательность ответов, то можно записать следующую функцию, которая называется _производящей функцией последовательности_: $ A(z) = sum_(n = 0)^oo a_n z^n. $ Естественно, мы хотим чтобы у этой функции был хоть какой-то радиус сходимости, то есть чтобы коэффициенты не росли быстрее чем $O(n^c)$. ] #example(name: "Задача о размене")[ Пусть у нас есть монетки номиналом $1$, $2$, $5$, и $10$, в неограниченом количестве. Сколькими способами можно разменять $n$ монеток? Рассмотрим функцию, $ A(z) = (1+z+z^2&+z^3+...) (1+z^2+z^4+z^6+...) \ &(1+z^5+z^10+z^15+...) (1+z^10+z^20+z^30+...), $ Тогда коэффициент при $z^n$ равен количеству способов разменять $n$ монеток, или количетсво способов представить $n$ в виде $a + 2b + 5c + 10d$. Можно свернуть геометрические прогрессии: $ A(z) = 1/(1-z) dot 1/(1-z^2) dot 1/(1-z^5) dot 1/(1-z^10). $ ] #ticket[Производящая функция для числа разбиений натуральных чисел. <NAME>.] #def[ Пусть $H subset NN$. Обозначим $p(n, H)$ --- количество способов представить $n$ в виде суммы элементов из $H$. ] #notice[ $ sum_(n = 0)^oo p(n, H) z^n = product_(k in H) 1/(1 - z^k). $ ] #notice[ Если на каждое слагаемое есть ограничение на количество слагаемых ($<= r$ раз, скажем), то $ Ff(z) = product_(k in H) (1 + z^k + ... + z^(k r)) = product_(k in H) (1 - z^((r+1)k)) / (1 - z^k). $ ] #def[ $p(n)$ --- число разбиений, то есть $p(n, NN)$. ] #notice(name: "<NAME>")[ $p(n) sim 1/(4n sqrt(3)) e^(pi sqrt(2/3) sqrt(n))$. Очев#footnote[нет]. ] #th(name: "Эйлера")[ Число разбиений $n$ на нечетные слагаемые равно числу разбиений $n$ на различные слагаемые. ] #proof[ Число разбиений числа на нечетные слагаемые равно $ Aa(z) = product_(n = 1)^oo 1/(1-z^(2n - 1)) = product_(n = 1)^oo (1-z^(2n))/(1-z^n). $ Последнее равенство верно, так как в знаменателе у нас произведения по всем $n$, а в числителе только по чётным, поэтому в итоге в знаменателе остаётся только произведение по нечётным. Теперь раскроем числитель каждого множителя как разность квадратов и получим $ product_(n = 1)^oo (1-z^(2n))/(1-z^n) = product_(n = 1)^oo ((cancel(1-z^n))(1 + z^n))/(cancel(1-z^n)) = product_(n = 1)^oo (1 + z^n), $ а это число разбиений на различные слагаемые (каждое слагаемое берём не более $1$-го раза). ] #exercise[ Придумать явную биекцию. ] #ticket[Диагонализация степенных рядов.] #example(name: "диагонализация степенных рядов")[ Пусть имеется $ F(z, w) = sum_(n,m = 0)^oo a_(n m) z^n w^m, $ который сходится при $abs(z) < R$ и $abs(w) < R$. Хотим придумать производящую функцию для диагонали $a_(n n)$, то есть $sum_(n = 0)^oo a_(n n) z^n$. Такая производящая функция по двум переменным зачастую пишется намного проще, чем по одной. Например, для биномиальных коэффициентов: $ sum_(n, m = 0)^oo C_(n + m)^n z^n w^m = sum_(k = 0)^oo underbrace(sum_(n = 0)^k C_k^n z^n w^(k - n), (z+w)^k) = sum_(k = 0)^oo (z + w)^k = 1/(1 - z - w). $ При $abs(z), abs(w) < 1/2$ ряд сходится. Попробуем его диагонализировать: $ F(z, w/z) = sum_(m, n)^oo a_(n m) z^n w^m z^(-m). $ В таком ряде коэффициент перед $z^0$ это $sum_(m = 0)^oo a_(m m) w^m$. А мы умеем находить такой коэффициент по теореме Коши: $ 1/(2pi i) integral_(abs(z) = r) F(z, w/z) (dif z)/z = 1/(2pi i) integral_(abs(z) = r) sum_(m, n = 0)^oo a_(n m) w^m z^(n - m - 1) dif z. $ Здесь мы рассмотрели маленькое $r$ ($0 < r < R$, $abs(w)/r = abs(w/z) = R$), поэтому, так как мы внутри круга сходимости, есть равномерная сходимость: $ 1/(2pi i) integral_(abs(z) = r) sum_(m, n = 0)^oo a_(n m) w^m z^(n - m - 1) dif z = 1/(2pi i) sum_(m, n = 0)^oo a_(n m) w^m underbrace(integral_(abs(z) = r) z^(n - m - 1) dif z, 0 "при" n != m\,\ 2pi i "при" n = m) = sum_(m = 0)^oo a_(m m) w^m. $ Возвращаемся к нашему примеру. $ 1/(2pi i) integral_(abs(z) = r) F(z, w/z) (dif z)/z = 1/(2pi i) integral_(abs(z) = r) 1/(1-z-w/z) (dif z)/z = 1/(2pi i) integral_(abs(z) = r) (dif z)/(-z^2 + z - w) = sum res. $ Где у этой функции вычеты? Когда обнуляется знаменатель, то есть $ z^2 - z + w = 0 ==> z = (1 plus.minus sqrt(1 - 4w))/2. $ Корень со знаком "$+$" нас не интересует, потому что он не попадает в круг маленького радиуса, да и вообще в нем исходный ряд расходится. Значит $ sum res = res_(z = (1 - sqrt(1 - 4w))/2 ) = lr(1/(-z^2 + z - w)' |)_(z = (1 - sqrt(1 - 4w))/2) = lr(1/(-2z + 1) |)_(z = (1 - sqrt(1 - 4w))/2) = 1/sqrt(1 - 4w). $ Получается, $ sum_(n = 0)^oo C_(2n)^n w^n = 1/sqrt(1 - 4w). $ ] #ticket[Произведение Адамара рациональных функций. Способ вычисления произведения Адамара.] #example(name: "произведение Адамара")[ Пусть есть две производящие функции $Aa(z) = sum_(n = 0)^oo a_n z^n$ и $Bb(z) = sum_(n = 0)^oo b_n z^n$. Хотим найти _произведение Адамара_ --- производящую функцию $ Aa dot.circle Bb = sum_(n = 0)^oo a_n b_n z^n. $ Как его искать? Через тот же метод с диагонализацией. Рассматриваем $ Ff(z, w) = Aa(z) Bb(z) = sum_(n,m=0)^oo a_n b_m z^n w^m $ и нужно найти "диагональ" $sum_(n = 0)^oo a_n b_n w^n$. ] #def[ Последовательность $a_n$ назовем _квазимногочленом_ (или _квазиполиномом_), если $a_n = p_1 (n) q_1^n + p_2 (n) q_2^n + ... + p_k (n) q_k^n$, где $p_1$, $p_2$, ..., $p_k$ --- многочлены, а $q_1, q_2, ..., q_k in RR$ различные числа. ] #lemma[ Производящая функция рациональна тогда и только тогда, когда последовательность --- квазимногочлен. ] #proof[ - "$==>$": $Aa(z)$ --- рациональная, значит ее можно представить как линейную комбинацию простейших (вида $1/(z - a)^k$). Надо научиться раскладывать ее $ 1/(z - a)^k = (-1)^k/(1 - z/a)^k dot (1/a)^k = (-1/a)^k dot sum_(n = 0)^oo (k^overline(n) z^n)/(a^n n!), $ Коэффициент перед $z^n$: $ (-1/a)^k dot (k (k + 1) ... (k + n - 1))/(a^n n!) = C_(k + n - 1)^(k - 1) dot (-1/a)^k dot 1/a^n = C_(k + n - 1)^n dot (-1/a)^k dot 1/a^n newline(=) ((k + n - 1)(k + n - 2)...(n + 1))/(k-1)! dot (-1/a)^k dot 1/a^n. $ Это квазимногочлен. Значит каждая простейшая раскладывается в квазимногочлен, и их линейная комбинация тоже. - "$<==$": Достаточно понять для одного "коэффициента", $a_n = p(n) q^n$. Представим многочлен в виде $ p(n) = c_k dot (n + k) (n + k - 1)...(n + 1) + c_(k - 1) dot (n + k - 1) (n + k - 2)...(n + 1) + ... + c_0. $ Тогда достаточно понять для $ b_n = (n + k) (n + k - 1) ... (n + 1) q^(n + k), $ для $k = 0$, $a_n = q^n$ и $ 1/(1 - q z) = sum_(n = 0) q^n z^n, $ а чтобы получить остальные коэффициенты, надо продифференцировать: $ (1/(1 - q z))' = sum_(n = 1)^oo n q^n z^(n - 1) = sum_(n = 0)^oo (n + 1) q^(n + 1) z^n. $ ] #th[ Произведение Адамара рациональных функций --- рациональная функция. ] #proof[ $Aa, Bb$ --- рациональные, значит $a_n$, $b_n$ --- квазимногочлены, значит $a_n b_n$ --- квазимногочлен, значит $Aa dot.circle Bb$ рациональная. ] #ticket[Метод Дарбу.] #example(name: "<NAME>")[ Наша цель: оценивать скорость роста коэффициентов производящих функций. Пусть имеется фукнция $f(z) = sum_(n = 0)^oo a_n z^n$, $R$ --- конечный радиус сходимости (если коэффициенты ряда убывают так быстро, что радиус сходимости бесконечность, вряд ли такой ряд нужен в комбинаторике, где обычно последовательности целочислены). Тогда на границе круга сходимости есть особая точка. План такой: давайте вычтем из функции главную часть ряда Лорана в этой точке. В точке появится голоморфность. Будем продолжать так делать, пока все изолированные особые точки на границе круга сходимости не исчезнут (тут приходится просто надеятся, что они изолированы, и что их конечное количество). После этого радиус сходимости увеличивается. Разложив в нем функцию в ряд Тейлора, можно оценить скорость роста коэффициентов исходной функции, пользуясь скоростью роста коэффициентов разложения главных частей ряда Лорана. Сейчас на примере будет понятнее. Рассмотрим функцию (положим $f(0) = +sqrt(2) > 0$): $ f(z) = sqrt(2 - z)/(1 - z)^2. $ Особая точка на границе круга сходимости одна: $z = 1$, и это полюс второго порядка. Чтобы "погасить" эту особенность, надо вычесть главную часть ряда Лорана в этой точке. Она равна $ 1/(1 - z)^2 - 1/(2(1 - z)) =: g(z), $ что получается разложением числителя в ряд по степеням $(1 - z)$. Тогда $ f(z) - g(z) = sqrt(2 - z)/(1 - z)^2 - 1/(1-z)^2 + 1/(2(1 - z)) = sum_(n = 0)^oo b_n z^n $ голоморфна в $z = 1$, и радиус сходимости расширяется до $2$ (точка ветвления $sqrt(2 - z)$). Значит $b_n = o((2 - eps)^(-n))$. А коэффициенты $g(z)$ мы знаем, найдем и вычтем их: $ 1/(1 - z)^2 = sum_(n = 0)^oo (n + 1)z^n, quad 1/(1 - z) = sum_(n = 0)^oo z^n. $ а тогда $ a_n = (n + 1) - 1/2 + b_n = n + 1/2 + o((1/(2 - eps))^n). $ Вот и оценка на коэффициенты. В простых случаях (когда на границе круга сходимости конечное число *изолированных* особых точек) такой метод работает. ] #example[ Рассмотрим $ f(z) = e^z/sqrt(1 - z) = sum_(n = 0)^oo a_n z^n. $ Радиус сходимости у этой функции равен $1$, но теперь на границе точка ветвления $z = 1$. Однако мы можем эту особенность "улучшить". Вычтем из функции $e/sqrt(1 - z)$: $ f(z) - e/sqrt(1 - z) = (e^z - e)/sqrt(1 - z) = sum_(n = 0)^oo b_n z^n. $ Теперь если разложить числитель в ряд в 1, получится, что функция ведет себя как $O(sqrt(1-z))$: $ f(z) - e/sqrt(1 - z) = e dot (e^(z - 1) - 1)/(sqrt(1 - z)) = e dot (sum_(k = 1)^oo 1/k! (z - 1)^k)/(sqrt(1 - z)). $ Не достаточно мало, чтобы прямо сказать асимптотику, как в прошлом примере, но зато хоть как-то стремиться к нулю. Тогда, разложив $1/sqrt(1 - z)$ в ряд, $ a_n = b_n + e dot (1/2)^overline(n)/n!. $ Оценим последний ряд: $ (1/2 dot 3/2 dot ... dot (1/2 + n - 1))/n! = ((2n - 1) dot (2n - 3) dot ... dot 1)/(2^n dot n!) = (2n)!/((2n)!! dot n! dot 2^n) = (2n)!/(4^n (n!)^2) = C_(2n)^n/4^n sim 1/sqrt(pi n). $ Можно проверить, что $b_n = O(1/(n sqrt(n)))$, и наша оценка на ряд совпадает с оценкой на $a_n$, то есть $a_n sim 1/sqrt(pi n)$. Здесь у нас не получилось найти скорость роста точнее, но придется довольствоваться чем имеем. ] #notice[ Полезный факт. Если $f in H(abs(z) < R)$, $R > 1$, $f(1) != 0$, $alpha != 0, -1, -2, ...$. Тогда коэффициент $f(z)/(1 - z)^alpha$ эквиватентен $f(1) dot binom(n + alpha - 1, n)$. ]
https://github.com/0warning0error/typst-yats
https://raw.githubusercontent.com/0warning0error/typst-yats/main/example.typ
typst
Apache License 2.0
#import "yats.typ": serialize,deserialize #{ let obj = ( name : "0warning0error", age : 100, height : 1.8, birthday : datetime(year : 1998,month : 7,day:8), hobbies : ("jumping",("swiming","learning English,日本語"),regex("fund"),none,true,duration(),type(int),"思密达") ) deserialize(serialize(obj)) }
https://github.com/LDemetrios/TypstParserCombinators
https://raw.githubusercontent.com/LDemetrios/TypstParserCombinators/master/combinators.typ
typst
// Utility functions (mostly clojure-core rewritten) #let force(x) = if ( type(x) == dictionary and x.at("very-special-key") == "delay" ) { (x.data)() } else { x } #let delay(x) = (very-special-key: "delay", data: x) #let comp(f, g) = it => f(g(it)) #let partial(f, ..x) = (..y) => f(..x, ..y) #let cons(x, y) = (x, ..y) #let conj(x, y) = (..x, y) #let apply(f, ..args, argsColl) = f(..args, ..argsColl) #let constantly(x) = (..y) => x #let stringify(..values) = for v in values.pos() { v } #let reduce(f, coll) = { if coll.len() == 0 { f() } else if coll.len() == 1 { coll.at(0) } else { let x = coll.at(0) let i = 1 while i < coll.len() { x = f(x, coll.at(i)) i += 1 } x } } #let reduce_v(f, val, coll) = { let x = val let i = 0 while i < coll.len() { x = f(x, coll.at(i)) i += 1 } x } // Basic result manipulations #let result(value, tail) = (valid:true, value:value, tail:tail) #let fail-r = (valid:false, value:none, tail:none) #let map-result(f) = res => if res.valid { result(f(res.value), res.tail) } else { res } // Simple parsers #let noparse(value) = s => result(value, s) #let char-p(predicate) = s => { if (s.len() > 0 and predicate(s.first())) { result(s.first(), s.slice(1)) } else { fail-r } } #let char-list(s) = char-p(c => c in s) #let char-not-p(predicate) = char-p(c => not predicate(c)) #let char-not-list(s) = char-p(c => c not in s) #let exactly(s) = inp => { if (inp.starts-with(s)) { result(s, inp.slice(s.len())) } else { fail-r } } #let exactly-as(s, v) = inp => { if (inp.starts-with(s)) { result(v, inp.slice(s.len())) } else { fail-r } } // Basic combinators #let combine(f, a, b) = s => { let ar = force(a)(s) if ar.valid { let br = force(b)(ar.tail) map-result(valueb => f(ar.value, valueb))(br) } else { ar } } #let either(a, b) = s => { let ar = force(a)(s) if ar.valid { ar } else { force(b)(s) } } #let map-p(f, parser) = comp(map-result(f), parser) // Ignoring #let ignored = "abracadabra" #let ignore(parser) = map-p(constantly(ignored), parser) #let iconj(coll, value) = if (value == ignored) { coll } else { conj(coll, value) } // Sequences #let seq(..parsers) = reduce_v(partial(combine, iconj), noparse(()), parsers.pos()) #let seqf(f, ..parsers) = map-p(partial(apply, f), seq(..parsers)) #let seqn(n, ..parsers) = seqf((..vs) => vs.pos().at(n), ..parsers) // Grammar constructions #let or-p(parser, ..parsers) = reduce_v(either, parser, parsers.pos()) #let opt(parser) = or-p(parser, noparse(none)) #let star(parser) = s => { let coll = () let rem = s let res = parser(s) while res.valid { coll.push(res.value) rem = res.tail res = parser(rem) } result(coll, rem) } #let plus(parser) = seqf(cons, parser, star(parser)) // Representations #let stringifing(parser) = map-p(partial(apply, stringify), parser) #let whole_parser(parser) = s => { let res = parser(s) if not res.valid { "Couldn't parse: " + s } else if "" != res.tail { "Remained: " + res.tail } else { res.value } } #let char-regex-p(reg) = char-p(it => it.match(regex(reg)) != none) #let skip(s) = ignore(exactly(s))
https://github.com/EpicEricEE/typst-marge
https://raw.githubusercontent.com/EpicEricEE/typst-marge/main/tests/resolve/padding/test.typ
typst
MIT License
#import "/src/resolve.typ": resolve-padding #context assert.eq(resolve-padding(none), (left: 0pt, right: 0pt)) #context assert.eq(resolve-padding(2pt), (left: 2pt, right: 2pt)) #context assert.eq(resolve-padding(1em), (left: 11pt, right: 11pt)) #context assert.eq(resolve-padding((left: 1pt)), (left: 1pt, right: 0pt)) #context assert.eq(resolve-padding((left: 1pt, right: 2pt)), (left: 1pt, right: 2pt)) #context assert.eq(resolve-padding((end: 2pt)), (left: 0pt, right: 2pt)) #context assert.eq(resolve-padding((outside: 2pt)), (left: 0pt, right: 2pt)) #{ set text(dir: rtl) context assert.eq(resolve-padding((end: 2pt)), (right: 0pt, left: 2pt)) } #{ set page(binding: right) context assert.eq(resolve-padding((outside: 2pt)), (left: 2pt, right: 0pt)) }
https://github.com/bevrist/resume
https://raw.githubusercontent.com/bevrist/resume/main/Resume.typ
typst
#show heading: set text(font: "Helvetica Neue") #set text(font: ("Helvetica Neue",)) #show link: underline #set page(margin: (x: 0.9cm, y: 1.3cm)) // #set par(justify: true) #set list(marker: "-") #let dividerLine() = {v(-3pt); line(length: 100%); v(-5pt)} #grid( columns: (1fr, 1fr), text( size: 40pt, font: ("Helvetica Neue"))[ <NAME> ], align(right)[ (909) 230-0226 #h(1pt) #box(image(height: 0.7em,"images/phone.svg")) #h(1pt) \ <EMAIL> #box(image(height: 0.7em,"images/email.svg")) \ #link("https://evri.st")[https://evri.st] #box(image(height: 0.7em,"images/website.svg")) ], ) Computer Science and Cybersecurity professional focused on DevSecOps, CI/CD Systems, Test Automation, Containerized Software, and System Security. Skilled in Software Development, Cloud Computing, Kubernetes, Release Automation, and Provisioning/Configuration Management. Interested in a DevSecOps or Software Engineering positions. == Technology Skills #dividerLine() - *Languages:* Golang, Python 3, Bash, C\#, C++, SQL, Java, Javascript, Dart. - *Technologies:* Kubernetes, Openshift, Docker, Ansible, Terraform, Git, MongoDB, PostgresSQL. - *Platforms:* Google Cloud, AWS, GitLab, Azure DevOps. - Experience with Agile & rapid prototyping techniques. - Virtual Reality programming and game design (Unreal Engine 5, Unity). - Familiar with RHEL7-8, CentOS, Ubuntu Server, and Debian. == Education & Certifications #dividerLine() *Kubernetes Administration* #h(3pt)--#h(3pt) Linux Foundation #h(1fr) May 2020 \ *CompTIA Security+* #h(5pt)--#h(5pt) CompTIA #h(1fr) September 2018 \ *Bachelors - Computer Science* #h(5pt)--#h(5pt) California State University, San Bernardino #h(1fr) June 2020 \ - NSA/DHS Center of Academic Excellence in Cyber Defense - National Science Foundation CyberCorps Scholarship for Service. *Certification - Cyber Security* #h(5pt)--#h(5pt) California State University, San Bernardino #h(1fr) June 2020 \ - National Science Foundation CyberCorps Scholarship for Service. *Associates of Science - Computer Science, Mathematics, Physics* #h(5pt)--#h(5pt) Crafton Hills College #h(1fr) March 2018 \ == Employment #dividerLine() *Lawrence Livermore National Laboratory* #h(3pt)--#h(3pt) DevOps Engineer #h(1fr) September 2021 -- Present \ - Worked on large scale distributed Kubernetes compute platform to run large machine learning and statistical models. - Built systems for continuous integration, deployment & release automation of software and infrastructure. - Developed Kubernetes operator for interfacing with High Performance Computing clusters. *MITRE Corporation* #h(3pt)--#h(3pt) Software Engineer #h(1fr) July 2020 -- September 2021 \ - Built container focused CI/CD and Security pipelines for a wide range of software projects, advised developers on container development and microservice best practices. - Developed and deployed microservice software and automation toolchains involving Kubernetes. - Packaged legacy non-cloud-native applications inside containers for deployment in Kubernetes. *MITRE Corporation* #h(3pt)--#h(3pt) Software Engineering Intern #h(1fr) June 2019 -- July 2020 \ - Built software CI/CD pipelines and deployed automated software build systems. Performed automated server deployment and configuration. Performed academic trade study on networking protocols and their functionality in degraded wireless networking environments. *CSU San Bernardino* #h(3pt)--#h(3pt) Cyber Security Research Lab Technician #h(1fr) August 2018 -- June 2020 \ - Present Technology Seminars for both students and faculty. - Monitor and mentor students in the research lab, perform Floor Marshal duties, conduct research and development on new technologies and systems for the university. *B<NAME> Enterprises* #h(3pt)--#h(3pt) Web Administrator#h(1fr) March 2016 -- January 2018 \ - Responsible for managing and updating product information and inventory for the company website, as well as improving site visibility and accessibility. Software: Wordpress, mySQL, Microsoft Access, and Python 3. #pagebreak() == Honors & Awards #dividerLine() National Science Foundation Scholarship For Service CyberCorps \ Boy Scouts of America Eagle Scout Rank -- Redlands Troop 11 \ FIRST Robotics Competition Regional Winner \ == Projects #dividerLine() *Virtual Reality “Secure Operations Center” (VR_SOC)* - Lead Engineer. Responsible for project management and team organization, as well as C\# programming, 3D modeling, and designing Virtual Reality interfaces and interactions. - Developed VR SOC using unity, capable of multi-user networking across the world for secure communication in the event of a cyber-related attack. *Artificial Intelligence Medical Trainer* #h(3pt)--#h(3pt) CSU San Bernardino Innovation Lab - Used Machine Learning and AI techniques to create an intelligent “patient” which can prepare medical students for real life interactions with real patients by simulating and communicating symptoms of patients, which the students then attempt to diagnose. *Virtual Machine Infrastructure Automation* #h(3pt)--#h(3pt) CSU San Bernardino Cyber Lab - Working on a system for building custom virtual machines based on faculty needs on the fly. - Using Packer and Ansible to automate the process of creating and configuring virtual machines for multiple different hypervisors at once. *FIRST Robotics Competition* #h(3pt)--#h(3pt) Yucaipa High School Mentorship - Mentored Yucaipa High School Robotics team and helped lead them to winning 3 regional competitions. Focused on Java programming of robotic components and electrical design. *Infosec Club Drones Project* #h(3pt)--#h(3pt) CSU San Bernardino InfoSEC Club - Co-leader of the drone project for CSU San Bernardino Infosec Club - Teaching students how to safely fly quadcopters as well as building and programming drones - Performing research on drone automation, vision, and self-navigation technologies. #dividerLine() #grid( columns: (1fr, 1fr), gutter: 20pt, [ = Competitions *Cal Poly Missa ITC* #h(1fr) 2020 - Information Technology Competition - 1st place team *AWS Hackathon* #h(1fr) 2020 - Web Application Hackathon at CSUSB *Google Cloud Platform Hackathon* #h(1fr) 2019 - Web Application Hackathon at CSUSB *SFSCON 2018* #h(1fr) 2018 - iCTF competition at SFScon *DEFCON 2018* #h(1fr) 2018 - OSINT iCTF competition at DefCon ], align(left)[ = Affiliations *InfoSec Club* #h(3pt)--#h(3pt) CSU San Bernardino - (September 2018 -- June 2020) *Virtual Reality Club* #h(3pt)--#h(3pt) CSU San Bernardino - (December 2019 -- July 2020) *Computer Science Club* #h(3pt)--#h(3pt) CSU San Bernardino - (September 2018 -- June 2020) *FBI Infragard* #h(3pt)--#h(3pt) LA Chapter - (September 2018 - Present) ], )
https://github.com/yonatanmgr/university-notes
https://raw.githubusercontent.com/yonatanmgr/university-notes/main/0366-%5BMath%5D/globals/functions.typ
typst
// Math functions #let iffd = $arrow.double.b.t$ #let uu = $union$ #let uud = $union.dot$ #let nn = $sect$ #let bs = $without$ #let ub = $union.big$ #let sb = $sect.big$ #let symd = $triangle.t.stroked$ #let iff = $<=>$ #let tb(exp, top, bottom) = $attach(limits(#exp), b: #bottom, t: #top)$ #let bv(f, s) = $#f bar.v_#s$ #let id(s) = $"id"_#s$ #let Id(s) = $"Id"_#s$ #let inv(f) = $#f^(-1)$ #let Im(f) = $"Im"(#f)$ #let dom(f) = $"dom"(#f)$ #let seq = $subset.eq$ #let suq = $supset.eq$ #let xx = $times$ #let A1 = $A_1$ #let A2 = $A_2$ #let B1 = $B_1$ #let B2 = $B_2$ #let RNN = $RR^+_0$ #let QED = place(left, dy: -0.2cm, dx: -0.6cm, $qed$) #let bar(x) = $overline(#x)$ #let of = $compose$ #let pm = $plus.minus$ #let char(f) = $"char"(#f)$ #let liminff(x) = $limits(lim)_(n->oo) #x$ #let limitn = $limits(lim)_(n->oo)$ #let limto(n) = $limits(lim)_(x->#n)$ #let arrl = $arrow.l.double$ #let an = $a_n$ #let ank = $a_n_k$ #let suminf(a,k) = $sum_(#k=1)^oo #a _#k$ #let arrr = $arrow.r.double$ #let inv(f) = $#f^(-1)$ #let trs(A) = $#A^t$
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/enum_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page 0. Before first! 1. First. 2. Indented + Second
https://github.com/fredguth/mwe-quarto-typst-error
https://raw.githubusercontent.com/fredguth/mwe-quarto-typst-error/main/README.md
markdown
## A Quarto Manuscript Template This is a template repo for generating a manuscript from Quarto that accompanies the tutorial at: [Quarto Manuscripts: VS Code](https://quarto.org/docs/manuscripts/authoring/vscode.html) # mwe-quarto-typst-error
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/set-03.typ
typst
Other
// Test that scoping works as expected. #{ if true { set text(blue) [Blue ] } [Not blue] }
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/03-lebesgue-integral/!sec.typ
typst
#import "../../config.typ" = <NAME> #include "01-integral-definition.typ" #include "02-summable-functions.typ" #include "03-limit-integral-perm.typ" #include "04-measure-product.typ" #include "05-var-substitution.typ"
https://github.com/3akev/autofletcher
https://raw.githubusercontent.com/3akev/autofletcher/main/manual.typ
typst
MIT License
#import "@preview/tidy:0.2.0" #import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge, shapes #import "@preview/autofletcher:0.1.0": placer, place-nodes, edges, tree-placer, circle-placer, arc-placer #let scope = ( diagram: diagram, node: node, edge: edge, placer: placer, place-nodes: place-nodes, edges: edges, tree-placer: tree-placer, circle-placer: circle-placer, arc-placer: arc-placer, shapes: shapes, ) #let version = "0.1.1" #let example(code) = { { set text(7pt) box(code) } {eval(code.text, mode: "markup", scope: scope)} } #set heading(numbering: "1.1") #align(center)[#text(2.0em, `autofletcher`)] #align(center)[#text(1.0em, [_version #version _])] #v(1cm) This module provides functions to (sort of) abstract away manual placement of coordinates by leveraging typst's partial function application. #outline(depth: 3, indent: auto) = Introduction The main entry-point is `place-nodes()`, which returns a list of indices and a list of partially applied `node()` functions, with the pre-calculated positions. All coordinates here are elastic, as defined in the fletcher manual. Fractional coordinates don't work that well, from what I've seen. == About placers A placer is a function that takes the index of current child, and the total number of children, and returns the coordinates for that child relative to the parent. Some built-in placers are provided: - `placer()` which allows easily creating placers from a list of positions. This should be good enough for most uses. See #link(label("flowchart"))[this example] - `arc-placer()` and its special instance `circle-placer` are built-in placers for circular structures. See #link(label("arc"))[these examples] - `tree-placer`, which places nodes as children in a tree. See #link(label("tree"))[this example] It's relatively easy to create custom placers if needed. See #link(label("custom"))[here] == About spread It appears that fletcher "squeezes" large distances along the left-right axis, as long as the coordinates in-between are empty. This is why it's useful to spread out the first generation of children, even by a large factor. Their children would then occupy the spaces in-between instead of overlapping. This, however, does not appear to be true for the up-down axis. = Examples Import the module with: #raw(lang: "typst", "#import \"@preview/autofletcher:" + version + "\": *") == Flowchart <flowchart> #example(```typst #diagram( spacing: (0.2cm, 1.5cm), node-stroke: 1pt, { let r = (0, 0) let flowchart-placer = placer((0, 1), (1, 0)) node(r, [start], shape: shapes.circle) // question is a node function with the position pre-applied let ((iquestion, ), (question, )) = place-nodes(r, 1, flowchart-placer, spread: 20) question([Is this true?], shape: shapes.diamond) edge(r, iquestion, "-|>") let ((iend, ino), (end, no)) = place-nodes(iquestion, 2, flowchart-placer, spread: 10) end([End], shape: shapes.circle) no([OK, is this true?], shape: shapes.diamond) edge(iquestion, iend, "-|>", label: [yes]) edge(iquestion, ino, "-|>", label: [no]) edge(ino, iend, "-|>", label: [yes], corner: right) edge(ino, r, "-|>", label: [no], corner: left) }) ```) == Tree diagram <tree> #example(```typst #diagram( spacing: (0.0cm, 0.5cm), { let r = (0, 0) node(r, [13]) let (idxs0, (c1, c2, c3)) = place-nodes(r, 3, tree-placer, spread: 10) c1([10]) c2([11]) c3([12]) edges(r, idxs0, "->") for (i, parent) in idxs0.enumerate() { let (idxs, (c1, c2, c3)) = place-nodes(parent, 3, tree-placer, spread: 2) c1([#(i * 3 + 1)]) c2([#(i * 3 + 2)]) c3([#(i * 3 + 3)]) edges(parent, idxs, "->") } }) ```) == Arc placer <arc> with `circle-placer`: #example(```typst #diagram( spacing: (1.5cm, 1.5cm), node-stroke: 1pt, { let r = (0, 0) let (idxs, nodes) = place-nodes(r, 12, circle-placer) for (i, ch) in nodes.enumerate() { ch([#{i + 1}], shape: shapes.circle) } edge(idxs.at(0), idxs.at(7), "-|>") edge(idxs.at(3), idxs.at(8), "-|>") edge(idxs.at(4), idxs.at(1), "-|>") edge(idxs.at(10), idxs.at(1), "-|>") edge(idxs.at(6), idxs.at(11), "-|>") }) ```) With `arc-placer`: #example(```typst #diagram( spacing: (1.5cm, 1.5cm), { let placer = arc-placer(-30deg, length: calc.pi, radius: 1.2) let r = (0, 0) node(r, [root]) let (idxs, nodes) = place-nodes(r, 5, placer, spread: 1) for (i, ch) in nodes.enumerate() { ch([#{i + 1}]) } edges(r, idxs, "->") }) ```) == Custom placers <custom> If the built-in placers don't fit your needs, you can create a custom placer; that is, a function that calculates the relative positions for each child. It should accept, in order: + (`int`) the index of the child + (`int`) the total number of children and it should return a pair of coordinates, `(x, y)`. #example(```typst #let custom-placer(i, num-total) = { // custom logic here let x = i - num-total/2 let y = calc.min(- x, + x) + 1 return (x, y) } #diagram({ let r = (0, 0) node(r, [root]) let (idxs, nodes) = place-nodes(r, 7, custom-placer, spread: 1) for (i, ch) in nodes.enumerate() { ch([#i]) } edges(r, idxs, "-|>") }) ```) #pagebreak(weak: true) = API reference #set heading(numbering: none) #let docs = tidy.parse-module(read("autofletcher.typ")) #tidy.show-module(docs, style: tidy.styles.default)
https://github.com/emanuel-kopp/uzh-mnf-phd
https://raw.githubusercontent.com/emanuel-kopp/uzh-mnf-phd/main/template/main.typ
typst
#import "@local/uzh-mnf-phd:0.1.0": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: main_doc.with( title: "The Title of Your Thesis", // Rules for Capitalization in Titles: // - Capitalize nouns, pronouns, verbs (including conjugated forms of to be), adjectives, and adverbs. // - Lowercase definite and indefinite articles (a, an, the). // - Lowercase all prepositions when used strictly as prepositions. // - Capitalize prepositions when used as adverbs or adjectives: Straighten Up and Fly Right. // - Lowercase usage of “to” in all situations – whether as a preposition or as part of an infinitive. // - Capitalize the second part of a hyphenated compound: Research-Based Teaching and Learning. author: "Name Surname", // (State your first name(s) in the form you prefer; at least one first name must be written out in full. // This information will be used for the doctorate diploma.) heimatort: "Place of Origin", // Non-Swiss: Nationality [e.g. aus Frankreich, aus der V.R. China] // Swiss: place of citizenship and canton [e.g. von Uster ZH] land: "Schweiz", // Set to "Schweiz" by default, change for non-swiss citizens examinators: ( // (list other members with their academic titles, first name(s) written out in full, "Prof. Dr. Head of Commit", // Head of committe "Dr. First P. Inv", // Your PI (if not same person as head of committee) "Prof. Dr. Other Memebr", "Prof. Dr. <NAME>", ), PI_is_head: true, // Define if your head of committee is also your first PI date: "2025" // Year of submission ) // Include the separate files here = Summary #include "chapters/summary_eng.typ" = General Introduction #include "chapters/general_intro.typ" = Chapter 1 #include "chapters/chapter_1.typ" = Chapter 2 #include "chapters/chapter_2.typ" #bibliography("library.bib", style: "elsevier-harvard")
https://github.com/protohaven/printed_materials
https://raw.githubusercontent.com/protohaven/printed_materials/main/common-tools/laser-large_format.typ
typst
#import "/meta-environments/env-templates.typ": * = Large Format Laser The Large Format Laser can etch or cut various materials with precision. == Notes === Safety *Do not leave the laser running unattended.* Lasers can cause fires. If your workpiece catches fire and the fire is not handled promptly, the fire can get out of control, and create an extreme hazard. Always keep watch over your running job, and be ready to extinguish any small fires with the nearby spray bottle, and/or hit the emergency stop if the laser goes out of control. *Keep the laser door closed during normal operation.* The door protects those nearby from any possible eye damage or skin burns should the laser hit any reflective material. *Make sure the fan is running before cutting or etching.* Running the laser on certain materials can produce gasses and make the studio environment unpleasant: the fans will pull the gasses outside. // https://ehs.mit.edu/wp-content/uploads/MITEHS_Laser_Cutter_Guidance.pdf // https://www.cncsourced.com/guides/laser-cutter-safety-hazards/ === Common Hazards Some materials may heat up enough from the laser to catch fire. In case of a small fire, use the water spray bottles to quickly douse any small flames. // In the case of a larger fire, use the fire extinguisher in the kitchen area. Some materials may produce toxic gas when cut or etched. Make sure the material you are cutting or etching is not listed in the @laser-prohibited-materials subsection. Depending on the material, laser cutting may produce sharp edges. Always handle materials carefully after they have been cut. === Care Use care when opening and closing the cover; do not let the cover slam closed. The shock of letting the cover fall freely onto the chassis can damage the laser tube. // === Use // // === Consumables // // === Tooling === Materials Protohaven carries a small selection of acrylic and plywood sheets for use with the large format lasers. A list of @sources-for-materials is included in the References section. ==== Prohibited Materials <laser-prohibited-materials> Some materials are dangerous to etch or cut in the laser cutter: the process may cause a fire hazard, or introduce dangerous gasses into the studio space. The following materials are prohibited for use in the laser cutter: #block[ #set text(size: 9pt) #let pro_materials = csv("/data-reference/large_format_laser/prohibited_materials.csv").map(l => l.slice(0,-1)) #let table_header = pro_materials.remove(0) #table( columns: (auto, auto), stroke: none, inset: 5pt, fill: (_, y) => if calc.odd(y) { color.tablegrey }, table.header(..table_header.map(h => strong(h))), table.hline(), ..pro_materials.flatten() ) ] ==== Approved Materials #block[ #set text(size: 9pt) #let app_materials = csv("/data-reference/large_format_laser/rabbit_approved_materials.csv").map(l => ((l.at(0),) + (l.at(1),) + (l.at(5),) + (l.at(8),))) #let table_header = app_materials.remove(0) #table( columns: (15em, auto,auto,auto), align: (col, row) => (left+top,center+top,center+top,left+top).at(col), stroke: none, inset: 5pt, fill: (_, y) => if calc.odd(y) { color.tablegrey }, table.header(..table_header.map(h => strong(h))), table.hline(), ..app_materials.flatten() ) ] == Parts of the Laser Cutter === Front Quarter View #figure( image("./images/large_format_laser-front_quarter-annotated.png", width: 100%), caption: [Annotated front-quarter view of the large format laser.], ) === Control Panel #figure( image("./images/large_format_laser-control_panel-default.jpeg", width: 60%), caption: [The control panel for the large format laser in the default view.], ) <large_format_laser-control_panel> === On/Off Switch Turn the key to the right (clockwise) to power on the laser. Turn the key to the left (counter-clockwise) to power off the laser. === Emergency Stop Switch Press the emergency stop switch to power off the laser. To re-enable the laser, pull up on the emergency stop button while twisting clockwise. === Lid The lid must be closed for the laser to fire. Always close the lid gently to avoid damaging the laser tube. Check to make sure that nothing is in the way (pieces of paper, material scraps, etc.) that may keep the lid open and interrupt the laser. === Lens Carriage The lens carriage moves the laser over the workpiece during a cut. === Bed The bed supports the workpiece. The bed can be raised and lowered to adjust the focus of the laser. === Control Panel Use the control panel to adjust the bed and lens carriage, set the origin, and other functions. Many functions can also be used through LightBurn. === Spray Bottle A spray bottle filled with water is kep on the right side of the cabinet. Use the spray bottle to quickly douse small material fires. === Magnets A collection of magnets are kept on the left side of the cabinet. Use these magnets to anchor the workpiece to the bed. == Basic Operation + @set-up-the-laser + @laser-workholding + @focus-the-lens + @set-the-origin + @set-up-the-job-in-lightburn + @run-the-job-on-the-laser + @cleaning-up === Set Up the Laser <set-up-the-laser> + Turn on the large format laser. + Make sure chiller is powered on and working. \ _Look for the green status light on the front of the chiller._ + Make sure the exhaust fan is running. + Carefully open the lid.\ _The lid is heavy; letting the lid slam closed will damage the laser._ + Secure the workpiece to the grid. \ _use the provided mounting magnets to hold the workpiece in place._ + Position the laser head over the workpiece. \ _Use the directional buttons to move the laser head across the bed._ === Workholding <laser-workholding> Use magnets to secure the workpiece to the grid. Make sure that the laser's path won't cause the laser to cut the magnets, or for the laser head to crash into the magnets. === Focus the Lens <focus-the-lens> Use a focus block on the workpiece to set the height of the lens and bring it into focus. + Press the *Z/U* button to change to bed height control.\ _The screen will display a menu with *Z move* highlighted in blue._ + Press the *←* (right arrow) and *→* (left arrow) buttons to align the focus gauge to the second ring of the lens carriage.\ _The right arrow lowers the bed, and the left arrow raises the bed._ + Press the *Esc* button to return to the main screen. #figure( image("./images/rabbit-focus_block.jpeg", width:60%), caption: [Lens carriage aligned with the focus gauge (40mm).], ) === Set the Origin <set-the-origin> + Position the laser head over the workpiece at the location you want to set as a boundry for your art. \ _Use the directional buttons to move the laser head across the bed._ - #h(0.48em)_Optional:_ Press the *Pulse* button to verify the exact location. 2. Press the *Origin* button to set the origin point for the job. === Set up the Job in LightBurn <set-up-the-job-in-lightburn> _These steps detail loading a single vector art file into LightBurn, and using that file to run a job with the laser. LightBurn is capable of much more: with LightBurn, we can load, manipulate, and compose multiple images into one job. For more about LightBurn, please see @software-lightburn. _ ==== Import the Art + Open LightBurn on the computer connected to the large format laser. + Click *File > Import*. + Select the art file to import. The art will be automatically placed on the LightBurn canvas. You may need to zoom and/or pan the view to see all of the art. ==== (Optional) Manipulate the Art LightBurn is a capable image editor, and has many features that a specific to preparing artwork for the laser. Work that is commonly done in LightBurn prior to cutting or etching: - Duplicating the art to cut multiple copies. - Putting portions of the art into layers, for different cuts and/or ordering the cuts. ==== Set the Reference Origin Set the reference origin in LightBurn with the Job Origin tool: #figure( image("./images/lightburn-ss-job_origin.png", height: 1in), caption: [The Job Origin tool, currently set with the origin at the upper left.], ) ==== Set the Speed and Power In the *Cuts/Layers* panel, each layer will have a listed speed and power in the *Spd/Pwr* column. These settings must be adjusted for the material (wood, acrylic, natural leather) and purpose (cutting or etching). To adjust the speed and power settings: + Click on the value in this column to bring up the *Cut Settings Editor* dialog box. #figure( image("./images/lightburn-ss-cut_settings-top_half.png", width:60%), caption: [The top half of the Cut Settings Editor dialog box.], ) + Use this dialog box to adjust the *Speed* and *Max Power* settings for the cut. + Click *OK*. See @rabbit-speed-and-power-settings for good starting speed and power values for materials. === Run the Job on the Laser <run-the-job-on-the-laser> + Check the footprint of your job.\ _In LightBurn, press the Rectangular *Frame* button to command the laser to trace out the box boundary of the job, or the Circular *Frame* button to trace out the exact boundary of the job. The laser will trace out the area of the job. Make sure that the traced path does not leave the media, or run over any of the hold-down magnets._ + Press the start button. + Monitor the machine until the job is complete.\ _While the job is running, remain nearby the laser to make sure nothing goes wrong._ === Cleaning Up <cleaning-up> + Power off the Laser. + Reset any modified computer settings to default. + Vacuum the interior so material does not build up beneath the honeycomb. + Recycle waste in the single-stream scrap bins. Report any maintenance needs or concerns at protohaven.org/maintenance, or by alerting a shop tech on duty. If the single-stream scrap bins become full, alert a shop tech. == Reference === Speed and Power Settings For Common Materials <rabbit-speed-and-power-settings> #block[ #set text(size: 8pt) #let app_materials = csv("/data-reference/large_format_laser/rabbit_approved_materials.csv").map(l => if l.at(6) != "" { ((l.at(0),) + (l.at(2),) + (l.at(3),) + (l.at(4),) + (l.at(6),) + (l.at(7),) )} else {}).filter(l => l != none) #let table_header = app_materials.remove(0) #table( columns: (15em, auto, auto, auto, auto, auto), align: (col, row) => (left+top,center+top,center+top,center+top,center+top,center+top).at(col), stroke: none, inset: 5pt, fill: (_, y) => if calc.odd(y) { color.tablegrey }, table.header(..table_header.map(h => strong(h))), table.hline(), ..app_materials.flatten() ) ] === Sources for Materials <sources-for-materials> A small selection of acrylic and plywood is available for purchase at the Protohaven shop. #block[ #set text(size: 8pt) #let app_materials = csv("/data-reference/large_format_laser/rabbit_approved_materials.csv").map(l => if l.at(-1) != "" { ((l.at(0),) + (l.at(-1),))} else {}).filter(l => l != none) #let table_header = app_materials.remove(0) #table( columns: (15em, auto), align: (col, row) => (left+top,left+top).at(col), stroke: none, inset: 5pt, fill: (_, y) => if calc.odd(y) { color.tablegrey }, table.header(..table_header.map(h => strong(h))), table.hline(), ..app_materials.flatten() ) ]
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/unterrichtsplanung/jahres_und_sequenzplanung.typ
typst
Other
#import "/src/template.typ": * == #ix("Jahres-", "Jahresplanung") und #ix("Sequenzplanung") #todo[Jahres- und Sequenzplanung beschreiben.]