repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/Manato1fg/My-Typst-Template
https://raw.githubusercontent.com/Manato1fg/My-Typst-Template/main/README.md
markdown
MIT License
# My-Typst-Template Typst 用のテンプレート(随時更新) ## 使用しているフォント [夜永オールド明朝](https://booth.pm/ja/items/3489185) ## Library @preview/ctheorems:1.1.0" @preview/physica:0.9.2"
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history_CN/2018/WS-07.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (1 - 32)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [1], [丁宁], [CHN], [3421], [2], [朱雨玲], [MAC], [3388], [3], [刘诗雯], [CHN], [3325], [4], [陈梦], [CHN], [3307], [5], [王曼昱], [CHN], [3295], [6], [伊藤美诚], [JPN], [3241], [7], [陈幸同], [CHN], [3143], [8], [木子], [CHN], [3136], [9], [孙颖莎], [CHN], [3116], [10], [石川佳纯], [JPN], [3114], [11], [武杨], [CHN], [3072], [12], [冯亚兰], [CHN], [3031], [13], [顾玉婷], [CHN], [3023], [14], [芝田沙季], [JPN], [2992], [15], [冯天薇], [SGP], [2973], [16], [平野美宇], [JPN], [2972], [17], [韩莹], [GER], [2966], [18], [文佳], [CHN], [2958], [19], [郑怡静], [TPE], [2942], [20], [何卓佳], [CHN], [2939], [21], [陈可], [CHN], [2936], [22], [索菲亚 波尔卡诺娃], [AUT], [2924], [23], [胡丽梅], [CHN], [2922], [24], [田志希], [KOR], [2920], [25], [徐孝元], [KOR], [2914], [26], [#text(gray, "李晓丹")], [CHN], [2903], [27], [金宋依], [PRK], [2902], [28], [杜凯琹], [HKG], [2898], [29], [佐藤瞳], [JPN], [2879], [30], [伯纳黛特 斯佐科斯], [ROU], [2878], [31], [李倩], [POL], [2869], [32], [桥本帆乃香], [JPN], [2866], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (33 - 64)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [33], [安藤南], [JPN], [2865], [34], [王艺迪], [CHN], [2863], [35], [加藤美优], [JPN], [2858], [36], [张蔷], [CHN], [2854], [37], [车晓曦], [CHN], [2853], [38], [GU Ruochen], [CHN], [2849], [39], [佩特丽莎 索尔佳], [GER], [2845], [40], [伊丽莎白 萨玛拉], [ROU], [2837], [41], [张瑞], [CHN], [2831], [42], [张墨], [CAN], [2830], [43], [布里特 伊尔兰德], [NED], [2827], [44], [长崎美柚], [JPN], [2826], [45], [石洵瑶], [CHN], [2822], [46], [早田希娜], [JPN], [2818], [47], [单晓娜], [GER], [2814], [48], [CHA Hyo Sim], [PRK], [2814], [49], [侯美玲], [TUR], [2804], [50], [EKHOLM Matilda], [SWE], [2801], [51], [#text(gray, "金景娥")], [KOR], [2794], [52], [SAWETTABUT Suthasini], [THA], [2782], [53], [杨晓欣], [MON], [2782], [54], [傅玉], [POR], [2766], [55], [孙铭阳], [CHN], [2765], [56], [#text(gray, "帖雅娜")], [HKG], [2764], [57], [KIM Nam Hae], [PRK], [2754], [58], [#text(gray, "SHENG Dandan")], [CHN], [2754], [59], [LIU Xi], [CHN], [2753], [60], [李皓晴], [HKG], [2752], [61], [李洁], [NED], [2748], [62], [SOO Wai Yam Minnie], [HKG], [2747], [63], [浜本由惟], [JPN], [2743], [64], [倪夏莲], [LUX], [2739], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (65 - 96)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [65], [李佼], [NED], [2738], [66], [刘佳], [AUT], [2736], [67], [<NAME>], [GER], [2735], [68], [玛利亚 肖], [ESP], [2726], [69], [POTA Georgina], [HUN], [2723], [70], [#text(gray, "姜华珺")], [HKG], [2714], [71], [WU Yue], [USA], [2712], [72], [HAPONOVA Hanna], [UKR], [2712], [73], [刘高阳], [CHN], [2712], [74], [曾尖], [SGP], [2707], [75], [崔孝珠], [KOR], [2707], [76], [梁夏银], [KOR], [2706], [77], [森樱], [JPN], [2706], [78], [李芬], [SWE], [2706], [79], [李恩惠], [KOR], [2705], [80], [李时温], [KOR], [2695], [81], [妮娜 米特兰姆], [GER], [2694], [82], [李佳燚], [CHN], [2694], [83], [森田美咲], [JPN], [2693], [84], [MATSUZAWA Marina], [JPN], [2687], [85], [BALAZOVA Barbora], [SVK], [2681], [86], [<NAME>], [SLO], [2678], [87], [刘斐], [CHN], [2676], [88], [<NAME>], [KOR], [2675], [89], [<NAME>], [JPN], [2674], [90], [<NAME>], [CZE], [2671], [91], [<NAME>], [KOR], [2671], [92], [<NAME>], [UKR], [2669], [93], [MAEDA Miyu], [JPN], [2662], [94], [ZHANG Sofia-Xuan], [ESP], [2649], [95], [阿德里安娜 迪亚兹], [PUR], [2649], [96], [<NAME>], [AUT], [2647], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (97 - 128)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [97], [<NAME>], [SGP], [2643], [98], [MIKHAILOVA Polina], [RUS], [2632], [99], [SHIOMI Maki], [JPN], [2632], [100], [KIM Youjin], [KOR], [2631], [101], [#text(gray, "RI Mi Gyong")], [PRK], [2630], [102], [ZHOU Yihan], [SGP], [2625], [103], [#text(gray, "SONG Maeum")], [KOR], [2622], [104], [大藤沙月], [JPN], [2620], [105], [张安], [USA], [2618], [106], [木原美悠], [JPN], [2616], [107], [NG Wing Nam], [HKG], [2614], [108], [于梦雨], [SGP], [2613], [109], [陈思羽], [TPE], [2613], [110], [#text(gray, "VACENOVSKA Iveta")], [CZE], [2610], [111], [VOROBEVA Olga], [RUS], [2607], [112], [LIN Chia-Hui], [TPE], [2607], [113], [#text(gray, "CHOI Moonyoung")], [KOR], [2607], [114], [PARTYKA Natalia], [POL], [2606], [115], [玛妮卡 巴特拉], [IND], [2606], [116], [HUANG Yi-Hua], [TPE], [2602], [117], [KATO Kyoka], [JPN], [2598], [118], [<NAME>], [ROU], [2591], [119], [PASKAUSKIENE Ruta], [LTU], [2585], [120], [PROKHOROVA Yulia], [RUS], [2585], [121], [<NAME>], [HUN], [2581], [122], [SABITOVA Valentina], [RUS], [2566], [123], [SO Eka], [JPN], [2565], [124], [邵杰妮], [POR], [2563], [125], [笹尾明日香], [JPN], [2561], [126], [TIAN Yuan], [CRO], [2561], [127], [CHOE Hyon Hwa], [PRK], [2559], [128], [DVORAK Galia], [ESP], [2559], ) )
https://github.com/Cheng0Xin/typst-libs
https://raw.githubusercontent.com/Cheng0Xin/typst-libs/master/acg-comment/comment.typ
typst
#let create-comment-img(img-src) = image(img-src, height: 1.5cm) #let create-comment(img-src, text-src) = block( breakable: false, stroke: 0.5pt + rgb("#5E1675"), radius: 5pt, inset: (x: 2pt, y: 4pt), stack( dir: ltr, create-comment-img(img-src), align(start+horizon, box(width: 90%, text[#text-src])) ) ) #let pm-comment(text) = create-comment("figure/pm.jpg", text) #let toothless-comment(text) = create-comment("figure/toothless.jpg", text) #let cat-comment(text) = create-comment("figure/cat.png", text)
https://github.com/jassielof/cv
https://raw.githubusercontent.com/jassielof/cv/main/doc/typst/cv-es.typ
typst
#import "template.typ": * #show: resume #header( name: "<NAME>", phone: "+591 7 508 1884", email: "<EMAIL>", linkedin: "jassiel-ovando", github: "jassielof", gitlab: "jassiel", // site: "jassielof", location: "Santa Cruz, Bolivia", ) #resume_heading[Educación] #edu_item( name: "Universidad Privada de Santa Cruz de la Sierra", degree: "Ingenieria de Sistemas", location: "Santa Cruz, Bolivia", date: "Feb. 2021 -- Presente" ) #edu_item( name: "<NAME>", degree: "Bachiller en Humanidades", location: "Santa Cruz, Bolivia", date: "Feb. 2012 - Dic. 2020" ) #resume_heading[Experiencia] #exp_item( role: "Ayudante de Cátedra en Fundamentos de Programación (C++)", name: "Universidad Privada de Santa Cruz de la Sierra", location: "Santa Cruz, Bolivia", date: "Sep. 2023 -- Dic. 2023", [Ayudé a los estudiantes a comprender conceptos básicos de programación y resolver problemas de programación en C++.], [Además de poder corregir errores en el código de los estudiantes y ayudarlos a mejorar su estilo de código.] ) #exp_item( role: "Desarrollador FullStack (ASP.Net Core)", name: "Universidad Privada de Santa Cruz de la Sierra", location: "Santa Cruz, Bolivia", date: "Ene. 2024 -- Presente", [Desarrollo] ) #resume_heading("Proyectos") #project_item( name: "Gestión para Veterinarias y Hotel de Mascotas", skills: "Python, Django, PostgreSQL", date: "Nov. -- Dic. 2023", [Desarrollé un sistema para la gestión de una veterinaría como proyecto final para la materia de _Base de Datos_ en base a requerimientos, además de algunas funcionalidades adicionales como generación de reportes.], [La modeloación de la base datos se realizó con sus tres faces (conceptual, lógica y física) y se implementó en PostgreSQL, con prevía ayuda visual de _PlantUML_.], [Para la presentación de reportes se utilizó _LaTeX_, con la inclusión del código de modelos (PostgreSQL y ORM/Python/Django), populación de tablas para pruebas, y funcionalidades adicioneles en Python.] ) #resume_heading("Habilidades") #skill_item( category: "Lenguages", skills: "Python, C++, PostgreSQL, PlantUML, LaTeX" ) #skill_item( category: "Frameworks", skills: "Django" ) #skill_item( category: "Herramientas de Desarrollo", skills: "CMake, Git, GitHub, Visual Studio Code, Visual Studio, CLion, PyCharm, Jupyter Notebook, Linux (Debian/Ubuntu), Windows" ) #skill_item( category: "Libraries", skills: "NumPy, SciPy" )
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Physique_Rev_12_01_2023.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "Physique Rev 12 01 2023", authors: ( "<NAME>", ), date: "30 Octobre, 2023", ) #set heading(numbering: "1.1.") Partie 1 QCM 1 1.a c 2.c b 3.a c 4.d QCM 2 1. b c 2. b 3. c b 4. b 5. QCM 3 1. c 2. b 3. b Partie 2 QCM 1 1. b 2. a 3. b d 4. b QCM 2 1. a 2. c 3. a b d 4. a b c QCM 3 1. a b c 2. b 3. b c Partie 3 QCM 1 1. b c 2. d 3. a b c 4. b QCM 2 1. c 2. a 3. b QCM 3 1. Car elle est incolore 2. Cu^2+
https://github.com/chamik/gympl-skripta
https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-autori/nezval.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/helper.typ": autor #autor("<NAME>", "1900", "1958 (58 let)", "básník, spisovatel, překladatel", "gymnázium v Třebíči", "poetismus, surrealismus", "/cj-autori/media/nezval.jpg") Roku 1922 vstoupil do Devětsilu, v jeho rámci se podílel na založení poetismu, nového básnického směru. Chtěl najít metodu, jak nahlížet na život, aby byl básní. Postupně se stal politickým iniciátorem českého avantgardního hnutí. Roku 1924 vstoupil do KSČ. Nějakou dobu působil jako dramaturg Osvobozeného divadla, kde se sblížil s Voskovcem a Werichem. Publikoval v Rudém právu, Tvorbě, Odeonu, Nové scéně, Lidových novinách atd. Nezval žil bohémským životem, byl to sukničkář. Rozepsal (avšak nedokončil) učebnici o astrologii ve kterou silně věřil a byl jí fascinován celý život; sám sobě předpověděl, že zemře o Velikonoce a opravdu zemřel o Velikonoční neděli. Mezi jeho známá díla patří: 1. *Abeceda* –- 4 až 2verší, asociace představ tvarů jednotlivých písmen abecedy; knižní vydání Abecedy byl výsledek spolupráce v oblasti knižní tvorby, na které se podí<NAME> (verše), <NAME> (typografie) a <NAME>á (taneční kompozice na téma písmen abecedy). 2. *<NAME>* -- Des Grieux se má stát knězem, ale zamiluje se do krásné Manon, kvůli níž se knězem nestane. Později se s Manon rozchází a stává se knězem, po dalším setkání s ní jí opět podléhá. Manon je nakonec vyslána do Ameriky (za trest), ale dříve, než se tam dostane, zemře na lodi Des Grieuxovi v náručí. *Současníci*\ _<NAME>_ -- Na vlnách TSF, 1925\ _<NAME>_ -- Abeceda (typografie), 1926\ _<NAME>_ -- Těžká hodina (@hodina[]), 1922 #pagebreak()
https://github.com/konradroesler/lina-skript
https://raw.githubusercontent.com/konradroesler/lina-skript/main/numla.typ
typst
#import "utils.typ": * #import "template.typ": uni-script-template #show: doc => uni-script-template( title: [Vorlesungsskript], author: [<NAME>], module-name: [Num. Lin. Algebra], doc ) = Einleitung Wichtige Aufgabenklassen der linearen Algebra sind #bold[lineare Gleichungssysteme]. Gegeben: $A in RR^(m times n), b in RR^m$ Gesucht: Ein/alle $x in RR^m$ mit $A x = b$ Herkunft: #boxedlist[ "direkt" aus der Anwendung, z.B. Beschreibung von Netzwerken, Tragwerk ][ "indirekt" als Diskretisierung von stationären Prozessen, z.B. Belastung einer Membran ][ "mittelbar" durch die Linearisierung nichtlinearer Modelle, z.B. Newton-Verfahren, Approximation von Lösungen gewöhnlicher DGL, notwendige Optimalitätsbedingungen ] Klassifizierung: #boxedlist[ $m = n$: $A$ quadratisch Generische Situation: $A$ regulär $==> exists!$ Lösung ][ $m < n$: "Unterbestimmtes System" Generische Situation: $ rg(A) = m "(Vollrang)" \ A corres [ A_1 A_2 ] quad A_1 in RR^(m times m) $ Lösungsmenge: $ cal(L) = { x in RR^n | A x = b } = { x = x^+ + h, h in ker(A) } $ $=$ ($n-m$)-dimensionale lineare Mannigfaltigkeit Gesucht ist dann z.B. norm-minimale Lösung (Kap. 5) ] #boxedlist[ $m > n$: "Überbestimmtes System" $ "lösbar" <==> b in im(A) = { y in RR^m | exists x: A x = y } $ Generisch nicht lösbar! Sinnvoll: Bestimme $macron(x) in RR^m$, so dass $ norm(A macron(x) - b) = min_(x in RR^m) norm(A x - b) $ $norm(space)$ $corres$ geeignete Norm, $macron(x)$ $corres$ Bestapproximierender für diese Norm. Mögliche Ansätze: #boxedlist[ $norm(space)_oo$: $norm(A x - b)_oo = max_(1 <= i <= m) abs((A x - b)_i)$ Ein nichtglattes Optimierungsproblem auch als lineares Optimierungsproblem fomulierbar, schwierig zu lösen für $m$ bzw. $n$ groß. ][ $norm(space)_1$: $norm(A x - b)_1 = sum_(i=1)^m abs(A x - b)$ Wie bei $norm(space)_oo$ stückweise lineares Optimierungsproblem. Aber stabil gegen Ausreißer. ][ $norm(space)_2$: $norm(A x - b)_2^2 = sum_(i=1)^m ((A x - b)_i)^2$ $corres$ lineares Quadratmittelproblem, kleinste Quadrateproblem (Kap. 5) ] ] Verfahren zur Lösung von LGS: Direkte Verfahren: #boxedlist[ Transformation der Daten $(A, b)$ in endlich viele in ein leichter zu lösendes LGS $tilde(A) x = tilde(b)$ $corres$ CG-Verfahren ][ Transformationen lassen sich oftmals als Faktorisierung von $A$ interpretieren $ A = L dot R quad "bzw." quad A = Q dot R $ ][ Dafür i.d.R. Zugriff auf Elemente von $A$ $==>$ limitiert die Größe der Matrix! ] Kap. 2-5 Indirekte Verfahren: #boxedlist[ Ausgehend von einem Startvektor $x^0$ Iteration zur Berechnung von $x^k$ mit $A x^k approx b$ Hierbei wird oftmals nur das Matrix-Vektor-Produkt $A v$ benötigt! (Kap. 6) ][ Eigenwertprobleme Stabilitätsanalyse von Bauwerken. Verfahren dazu: numerische Optimierung ] #pagebreak() = Das Gauß-Verfahren I Jetzt: $A in RR^(m times n), b in RR^n, quad x: A x = b$? #theorem("2.1")[ #bold[Existenz und Eindeutigkeit einer Lösung] Sei $A in RR^(m times n)$ eine Matrix mit $det(A) != 0$ und $b in RR^n$. Dann existiert genau ein $x in RR^n$ mit $ A x = b $ ] #startproof lineare Algebra #endproof $==>$ Anwendung von Algorithmen zur Berechnung von $x$ sinnvoll! Wie? == Gaußsche Eliminationsverfahren und LR-Zerlegung $corres$ direktes Verfahren für quadratische System Erste Idee: Systeme spezieller Struktur, z.B. $ R x = c, quad R = mat(r_(1 1), ..., r_(1 n);0,dots.down,dots.h;0,0,r_(m n)) in RR^(n times n), quad c = vec(c_1, dots.v, c_n) in RR^n $ $R x = c$ $ &r_(n n) x_n = c_n ==> x_n = c_n / r_(n n), quad r_(n n) != 0 \ &r_(n-1 n-1) x_(n -1) + r_(n-1 n) x_n = c_(n-1) \ &x_(n-1) = (c_(n-1) - r_(n-1 n) x_n)/r_(n-1 n-1), quad r_(n-1 n-1) != 0 $ #pagebreak() #bold[Algorithmus 2.2:] Rückwärtssubsitution $ x_n = c_n / r_(n n) quad "falls" r_(n n) != 0 \ dots.v \ x_i = (c_i - sum_(j = i+1)^n r_(i j) x_j) / r_(i i) quad "falls" r_(i i) != 0 \ dots.v \ x_1 = (c_1 - sum_(j = 2)^n r_(1 j) x_j) / r_(1 1) quad "falls" r_(1 1) != 0 $ Algo. 2.2 anwendbar, wenn $det(R) != 0$ (vgl. Theo. 2.1) Wichtiger Aspekt dieser Vorlesung: Aufwandsabschätzung Aufwand: $i$-te Zeile je $n-i$ Additionen und Multiplikationen und 1 Division insgesamt: $ sum_(i = 1)^n (i-1) = (n(n-1))/2 = cal(O)(n^2) $ Addition und Multiplikationen und $n$ Divsionen.
https://github.com/ParaN3xus/typress
https://raw.githubusercontent.com/ParaN3xus/typress/main/README.md
markdown
MIT License
# Typress [![Open Source License](https://img.shields.io/github/license/paran3xus/typress?logo=github)](https://opensource.org/license/mit) [![Hugging Face Weights](https://img.shields.io/badge/Weights-TypressOCR-yellow.svg?logo=huggingface)](https://huggingface.co/paran3xus/typress_ocr) [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/paran3xus/typress_ocr_space) Typst Mathematical Expression OCR based on [TrOCR](https://github.com/microsoft/unilm/tree/master/trocr). ## Install ### Clone the Repository Clone this repo and enter it: ```sh git clone https://github.com/ParaN3xus/typress cd typress ``` Install dependencies: We use [Poetry](https://python-poetry.org/) to manage project dependencies. If you don't have Poetry installed, please follow the instructions on the [Poetry installation page](https://python-poetry.org/docs/). ```sh poetry install poetry shell ``` ### TODO: PyPI ## Run ### Development Run #### Run Typress Web server Ensure you are in the repo root directory and execute ```sh python -m typress ``` ### Production Run #### Set Up .env Create a .env file in the repo root directory with the following content: ```sh MODEL_PATH=path/to/your/model API_ROOT_URL=https://api.example.com/typress ``` #### Run WSGI To run the application in production mode, it is recommended to use a production-grade WSGI server such as `gunicorn`: ```sh gunicorn --bind 0.0.0.0:8000 wsgi:app ``` ## TODO - [ ] Improve the tex2typ reconstruction strategy for `spacing`. - [ ] Fix memory leaks in normalized formulas - [ ] Add formula detection - [ ] Explore using LoRA to fine-tune the OCR model for TeX - [ ] Publish to PyPI - [ ] Document the complete dataset construction process - [ ] ~~Train using `seq2seqtrainer`~~ ## Contributing ### Data Contribution If you have a collection of Typst mathematical formula text (which can be included in Typst documents), you can create a dataset by running the following command in the Typst workspace root: ```bash python -m typress.dataset extract ``` Then, submit the generated `out.json` file to us via email at [<EMAIL>](mailto:<EMAIL>). By submitting your data to us, you agree to make your dataset publicly available. ### Code Contribution We welcome any code contributions, including bug fixes, feature additions, etc. If you're unsure where to start, you can refer to our Todo list. ## License This repository is published under an MIT License. See [LICENSE](https://github.com/ParaN3xus/typress/blob/main/LICENSE) file ## Credits This project makes use of the following open-source projects or datasets: - [TrOCR](https://github.com/microsoft/unilm/tree/master/trocr): Transformer-based Optical Character Recognition with Pre-trained Models. - [tramsformers](https://github.com/huggingface/transformers): State-of-the-art Machine Learning for Pytorch, TensorFlow, and JAX. - [evaluate](https://github.com/huggingface/evaluate): A library for easily evaluating machine learning models and datasets. - [eq_query_rec](https://github.com/sjfhsjfh/eq_query_rec): Query equations from Typst source file and reconstruct normalized equation from querying result. - [typst.ts](https://github.com/Myriad-Dreamin/typst.ts): Run Typst in JavaScriptWorld. - [fusion-image-to-latex-datasets](https://huggingface.co/datasets/hoang-quoc-trung/fusion-image-to-latex-datasets): The largest dataset to date from online sources. - [latex-formulas](https://huggingface.co/datasets/OleehyO/latex-formulas): TexTeller previous dataset. Thanks to the developers and contributors of these projects for their hard work and dedication. Thanks to [sjfhsjfh](https://github.com/sjfhsjfh), [Naptie](https://github.com/Naptie), [Mivik](https://github.com/Mivik/) for providing Typst mathematical formula data.
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Templates/notes.typ
typst
#let chapter_heading(doc) = { set heading(numbering: "1.1.") doc }
https://github.com/mitex-rs/mitex
https://raw.githubusercontent.com/mitex-rs/mitex/main/fixtures/underleaf/ieee/main.typ
typst
Apache License 2.0
#import "@preview/mitex:0.2.4": * #let res = mitex-convert(mode: "text", read("main.tex")) #eval(res, mode: "markup", scope: mitex-scope)
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/casoslov/vecierenBezKnaza.typ
typst
#import "../../style.typ": * #import "/CSL/texts.typ": * #import "../styleCasoslov.typ": * = Vsednévna večerňa <X> #show: rest => columns(2, rest) #nacaloBezKnaza #include "../zalmy/Z103.typ" #si #lettrine("Allilúia, allilúia, allilúia. Sláva tebí, Bóže.") #primText[(3x)] #ektenia(12) #note[Nasleduje predpísaná katizma:] #ektenia(3) #header[Hóspodi, vozzvách] Hóspodi, vozvách k tebí uslýši mja, \* uslýši mja Hóspodi. \* Hóspodi, vozvách k tebí uslýši mja, \* voňmí hlásu molénija mojehó, \* vnehdá vozváti mi k tebí, uslýši mja, Hóspodi. Da isprávitsja molítva mojá \* jáko kadílo préd tobóju: \* vozďijánije rukú mojéju, \* žértva večérňaja, uslýší mjá Hóspodi. #include "../zalmy/Z_PaneJaVolam.typ" #verse(( "Izvedí iz temnícy dúšu mojú, ispovídatisja ímeni tvojemú.", "Mené ždút právednicy, dóndeže vozdási mňi.", "Iz hlubiný vozvách k tebí Hóspodi, Hóspodi uslýši hlas moj.", "Da búdut úši tvojí vnémľušči hlásu molénija mojehó.", "Ašče bezzakónija nazriši Hóspodi, Hóspodi kto postojít, jáko u tebé očiščénije jesť.", "Imené rádi tvojehó poterpích ťa Hóspodi, poterpí dušá mojá vo slóvo tvojé, upová dušá mojá na Hóspoda.", "Ot stráži útrenija do nóšči, ot stráži útrénija da upovájet Isrájiľ na Hóspoda.", "Jáko u Hóspoda mílosť i mnóhoje u ného izbavlénije, i toj izbávit isrájiľa ot vsich bezzakónij jehó.", "Chvalíte Hóspoda vsi jazýcy, pochvalíte jehó vsi ľúdije.", "Jáko utverdísja mílosť jehó na nás, i ístina Hospódňa prebyvájet vo vík." )) #header[Svíte tíchij] #lettrine("Svíte tíchij, * svjatýja slávy, * bezsmértnaho Otcá nebésnaho, * svjatáho blažénnaho, * Iisúse Christé: * Prišédše sólnca na západ, * víďivše svít večérnij, * pojém Otcá i Sýna i svjatáho Dúcha Bóha. * Dostójin jesí * vo vsja vremená, * pít býti * hlásy prepodóbnými, * Sýne Bóžij, * živót dajáj vsemú míru, * jehóže rádi * vés mír slávit ťa.") #header[Prokimen] #prokimenyVecierne #header[Čténia] #note[Berieme čítania ak sú:] #header[Spodóbi, Hóspodi] #lettrine("Spodóbi, Hóspodi, vo véčer sej, * bez hrichá sochranitísja nám. - Blahoslovén jesí, Hóspodi, Bóže otéc nášich, * i chváľno i proslávlenno ímja tvojé vo víki, amíň. - Búdi, Hóspodi, mílosť tvojá na nas, * jákože upováchom na ťa. - Blahoslovén jesí, Hóspodi, * naučí nas opravdánijem tvojím. - Blahoslovén jesí, Vladýko, * vrazúmi nas opravdánijem tvojím. - Blahoslovén jesí, Svjatýj, * prosvití nás opravdániji tvojími. - Hóspodi, mílosť tvojá vo vik, * ďíl rukú tvojéju ne prezri. - Tebí podobájet chvalá, * tebí podobájet pínije. - Tebí sláva podobájet * Otcú i Sýnu i svjatómu Dúchu. - Nýňi i prísno, * i vo víki vikóv, amíň.") #ektenia(12) #header[Stichíry na stichovňi] #slohy(( "K tebí vozvedóch óči mojí, živúščemu na nebesí. Sé jáko óči ráb v rukú hospódij svoích, jáko óči rabýni v rukú hospoží svojejá, táko óči náši ko Hóspodu Bóhu nášemu, dóndeže uščédrit ný.", "Pomíluj nás Hóspodi, pomíluj nás, jáko po mnóhu ispólnichomsja uničižénija: najpáče napólnisja dušá náša ponošénija hobzújuščich i uničižénija hórdych." )) #header[Molitva Simeona] #lettrine("Nýňi otpuščáješi rabá tvojehó, Vladýko, * po hlahólu tvojemú s mírom. * Jáko víďista oči mojí spasénije tvojé, * jéže jesí uhotovál pred licém vsich ľudéj. * Svít vo otkrovénije jazýkov * i slávu ľudéj tvojích Ísraiľa") #trojsvatePoOtcenas #header[Tropar] #note[Berieme tropáre zakončené Bohorodičníkom:] #ektenia(40) #prepustenieBezKnaza
https://github.com/jamesrswift/springer-spaniel
https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/src/package/gentle-clues.typ
typst
The Unlicense
#import "@preview/gentle-clues:0.9.0": * #let gentle-clues = gentle-clues.with(border-radius: 0.5pt)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/tracking-spacing_05.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test word spacing relative to the font's space width. #set text(spacing: 50% + 1pt) This is tight.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cheq/0.1.0/README.md
markdown
Apache License 2.0
# Cheq Write markdown-like checklist easily. ## Usage Checklists are incredibly useful for keeping track of important items. We can use the cheq package to achieve checklist syntax similar to [GitHub Flavored Markdown](https://github.github.com/gfm/#task-list-items-extension-). ```typ #import "@preview/cheq:0.1.0": checklist #show: checklist = Solar System Exploration, 1950s – 1960s - [ ] Mercury - [x] Venus - [x] Earth (Orbit/Moon) - [x] Mars - [ ] Jupiter - [ ] Saturn - [ ] Uranus - [ ] Neptune - [ ] Comet Haley ``` ![Example](./examples/example.png) ## Custom Styles ```typ #import "@preview/cheq:0.1.0": checklist #show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em) = Solar System Exploration, 1950s – 1960s - [ ] Mercury - [x] Venus - [x] Earth (Orbit/Moon) - [x] Mars - [ ] Jupiter - [ ] Saturn - [ ] Uranus - [ ] Neptune - [ ] Comet Haley #show: checklist.with(unchecked: sym.ballot, checked: sym.ballot.x) = Solar System Exploration, 1950s – 1960s - [ ] Mercury - [x] Venus - [x] Earth (Orbit/Moon) - [x] Mars - [ ] Jupiter - [ ] Saturn - [ ] Uranus - [ ] Neptune - [ ] Comet Haley ``` ![Example](./examples/custom-styles.png) ## `checklist` function ```typ #let checklist( fill: white, stroke: rgb("#616161"), radius: .1em, default: ([•], [‣], [–]), unchecked: auto, checked: auto, body, ) = { .. } ``` **Arguments:** - `fill`: [`string`] &mdash; The fill color for the checklist marker. - `stroke`: [`string`] &mdash; The stroke color for the checklist marker. - `radius`: [`string`] &mdash; The radius of the checklist marker. - `default`: [`tuple`] &mdash; The default markers for [Bullet List](https://typst.app/docs/reference/model/list/#parameters-marker), default to be `([•], [‣], [–])`. - `unchecked`: [`string`] &mdash; The marker to represent unchecked item. If set to `auto`, it will use the `unchecked-sym()` function in the cheq package. - `checked`: [`string`] &mdash; The marker to represent checked item. If set to `auto`, it will use the `checked-sym()` function in the cheq package. - `body`: [`content`] &mdash; The main body from `#show: checklist` rule. ## `unchecked-sym` function ```typ #let unchecked-sym(fill: white, stroke: rgb("#616161"), radius: .1em) = { .. } ``` **Arguments:** - `fill`: [`string`] &mdash; The fill color for the unchecked symbol. - `stroke`: [`string`] &mdash; The stroke color for the unchecked symbol. - `radius`: [`string`] &mdash; The radius of the unchecked symbol. ## `checked-sym` function ```typ #let checked-sym(fill: white, stroke: rgb("#616161"), radius: .1em) = { .. } ``` **Arguments:** - `fill`: [`string`] &mdash; The fill color for the checked symbol. - `stroke`: [`string`] &mdash; The stroke color for the checked symbol. - `radius`: [`string`] &mdash; The radius of the checked symbol. ## License This project is licensed under the MIT License.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fh-joanneum-iit-thesis/1.2.2/template/chapters/4-background.typ
typst
Apache License 2.0
#import "global.typ": * = Background #lorem(45) #todo( [ In the background section you might give explanations which are necessary to read the remainder of the thesis. For example define and/or explain the terms used. Optionally, you might provide a glossary (index of terms used with/without explanations). *Hints for equations in Typst*: Mathematical formulars are (embedded in `$`) in Typst. For example: The notation used for #textbf([calculating]) of #textit([code performance]) might typically look like shown in @eq:performance, i.e. the first one for *slow* in @slow and the other one for *very slow* in @veryslow. #figure( kind: math.equation, align(left, [ #set math.equation(numbering: "(I)", supplement: [Eq.]) $ O(n) = n^2 $ <slow> $ O(n) = 2^n $ <veryslow> ]), caption: flex-caption([Equations calculste the performance.], [Performance.]), ) <eq:performance> #figure( kind: math.equation, align( left, [ In the text we refer multiple times to $phi.alt$. We define it to be calcultated as shown here: #set math.equation(numbering: "(I)", supplement: [Eq.]) $ d := 7 - sqrt(3) $ <diff> $ phi.alt := d / 3 $ <ratio> ], ), caption: flex-caption( [A custom definition of $phi.alt$ allows to shorten upcoming equations.], [Phi defined in two steps.], ), ) <eq:phidef> The @eq:phidef explains (for the single steps see @diff and @ratio) how the overall $phi.alt$ is calculated to be used in the upcoming formulars of this thesis. ], )
https://github.com/wzy1935/Typst-Blocks
https://raw.githubusercontent.com/wzy1935/Typst-Blocks/master/examples/tech_doc.typ
typst
#import "../blocks.typ": * #main_block([ = Introduction #warning_block([ *You are reading the documentation for Vue 3!* - Vue 2 support will end on Dec 31, 2023. Learn more about #link("https://v2.vuejs.org/lts/")[Vue 2 Extended LTS]. - Vue 2 documentation has been moved to #link("https://v2.vuejs.org/")[v2.vuejs.org]. - Upgrading from Vue 2? Check out the #link("https://v3-migration.vuejs.org/")[Migration Guide]. ]) == What is Vue? Vue (pronounced /vjuː/, like *view*) is a JavaScript framework for building user interfaces. It builds on top of standard HTML, CSS, and JavaScript and provides a declarative and component-based programming model that helps you efficiently develop user interfaces, be they simple or complex. Here is a minimal example: ```js import { createApp } from 'vue' createApp({ data() { return { count: 0 } } }).mount('#app') ``` ```html <div id="app"> <button @click="count++"> Count is: {{ count }} </button> </div> ``` The above example demonstrates the two core features of Vue: - Declarative Rendering: Vue extends standard HTML with a template syntax that allows us to declaratively describe HTML output based on JavaScript state. - Reactivity: Vue automatically tracks JavaScript state changes and efficiently updates the DOM when changes happen. You may already have questions - don't worry. We will cover every little detail in the rest of the documentation. For now, please read along so you can have a high-level understanding of what Vue offers. #info_block([ *Prerequisites* The rest of the documentation assumes basic familiarity with HTML, CSS, and JavaScript. If you are totally new to frontend development, it might not be the best idea to jump right into a framework as your first step - grasp the basics and then come back! You can check your knowledge level with #link("https://developer.mozilla.org/en-US/docs/Web/JavaScript/Language_overview")[this JavaScript overview]. Prior experience with other frameworks helps, but is not required. ]) == The Progressive Framework Vue is a framework and ecosystem that covers most of the common features needed in frontend development. But the web is extremely diverse - the things we build on the web may vary drastically in form and scale. With that in mind, Vue is designed to be flexible and incrementally adoptable. Depending on your use case, Vue can be used in different ways: - Enhancing static HTML without a build step - Embedding as Web Components on any page - Single-Page Application (SPA) - Fullstack / Server-Side Rendering (SSR) - Jamstack / Static Site Generation (SSG) - Targeting desktop, mobile, WebGL, and even the terminal If you find these concepts intimidating, don't worry! The tutorial and guide only require basic HTML and JavaScript knowledge, and you should be able to follow along without being an expert in any of these. If you are an experienced developer interested in how to best integrate Vue into your stack, or you are curious about what these terms mean, we discuss them in more detail in #link("https://vuejs.org/guide/extras/ways-of-using-vue.html")[Ways of Using Vue]. Despite the flexibility, the core knowledge about how Vue works is shared across all these use cases. Even if you are just a beginner now, the knowledge gained along the way will stay useful as you grow to tackle more ambitious goals in the future. If you are a veteran, you can pick the optimal way to leverage Vue based on the problems you are trying to solve, while retaining the same productivity. This is why we call Vue "The Progressive Framework": it's a framework that can grow with you and adapt to your needs. ])
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/deps.typ
typst
Apache License 2.0
#import "@preview/oxifmt:0.2.0"
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-circle_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test relative sizing. #set text(fill: white) #show: rect.with(width: 100pt, height: 50pt, inset: 0pt, fill: rgb("aaa")) #set align(center + horizon) #stack( dir: ltr, spacing: 1fr, 1fr, circle(radius: 10pt, fill: eastern, [A]), // D=20pt circle(height: 60%, fill: eastern, [B]), // D=30pt circle(width: 20% + 20pt, fill: eastern, [C]), // D=40pt 1fr, )
https://github.com/morel-olivier/template-typst
https://raw.githubusercontent.com/morel-olivier/template-typst/master/letter/main.typ
typst
/******************************************************************************* * This template is based on the template of <NAME> : typst-letter-template * available on GitHub : * https://github.com/pascal-huber/typst-letter-template/tree/master *******************************************************************************/ #import "lttr.typ": * #show: lttr_init.with( debug: false, format: "C5-WINDOW-RIGHT", title: "Ceci est le sujet de la lettre", opening: "Madame, Monsieur,", closing: "Meilleures salutations", signature: [<NAME> #image("mbernasconi.svg", width: 4cm)], date_place: ( date: "le 21 novembre 2023", place: "Pont-le-Vieux", ), receiver: ( "<NAME>", "Rue du four 4", "1234 perpet les oies", ), sender: ([ <NAME>\ Che<NAME>és 8\ 1234 Pont-le-Vieux ]), ) #show: lttr_preamble #lorem(100) #lorem(100) #lorem(100) #show: lttr_closing
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/013%20-%20Magic%202015/007_Comin'%20Through!.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Comin' Through!", set_name: "Magic 2015", story_date: datetime(day: 30, month: 07, year: 2014), author: "<NAME>", doc ) Fizz poked her head out of the trench long enough to see that she didn't want to do it any longer. Orc raiders fought in tight formation, and hundreds of her fellow goblins charged ahead of them as shock troops and minesweepers. Bombs exploded, arrows flew, and goblins fell by the dozens. Some of them were probably going to survive the battle. It happened, sometimes. And they were going to come back with an appetite. That's where Fizz came in. #figure(image("007_Comin' Through!/01.jpg", width: 100%), caption: [Bubbling Cauldron | Art by <NAME>champs], supplement: none, numbering: none) Fizz was not, by nature, a fighter. Back in the warren, while her thirty-five (or so) brothers and sisters fought among themselves for scraps of rat and the most flavorful rocks, Fizz had hidden in a corner, stewing armadillos in the shell or frying up some nice crisp toad skeletons. When the orc general Razgar had called the goblin clans to war, Fizz had reluctantly strapped a mixing bowl to her head, stuck a chef's knife in her belt, and joined the ranks. But it hadn't been long before her commanders had taken note of her unique talents, and she soon found herself leaving the 99th Goblin Infantry (the grand old Grag Ridge Expendables) for the relative safety of the field kitchens. On this particular day, she was stewing a thick, bubbling pot of her specialty, Stuff-I-Found-Lying-Around Soup. She fished a boot out of the stock with her ladle and bit into it. She frowned, tossed it back in, sprinkled in a dash of powdered goat, and stirred. She took another taste. It still needed something... "Iiiiiiinnnnnnncooooooommmmmmiiiiiiiiinnnnnnnggggggg!" #emph[Sploosh.] "Hot!" yelled the goblin messenger who had just landed in her soup. "Hot, hot, hot!" She grabbed him by the ear, hauled him out of the soup, deposited him next to the cauldron, and tasted. Perfect! "Field Chef Fizz?" asked the messenger. Fizz saluted with the ladle still in her hand, splattering the messenger with soup. "Message from the general," said the messenger, holding out a sodden piece of parchment. Fizz took it, wrung it out over the cauldron, unfolded it, and read. Her eyes went wide. "General Razgar wants lunch..." The messenger yawned. "...now..." He rubbed at his ear where she had grabbed it. "...in his tent..." The messenger licked soup off of his nose and nodded appreciatively. "...across the battlefield..." The messenger scratched his head. "...in the middle of a battle?!" The messenger shrugged. "Can't read," he said cheerfully. "That's why they made me a messenger! It's called security." Fizz, unfortunately, could read. The General's note was quite specific. Lunch, now, in his tent, all the way across the battlefield. And it had better be hot when it gets there. She peeked over the wall of the trench again, at the terrible, deadly chaos of battle. She'd never make it through that alive, never mind without spilling the soup. Fizz straightened. Never say never, or at least almost never, as her mother used to say. This was her chance. Today was her day. She was born for this. She saluted. "Tell the general I'm on my way." "Huh?" said the messenger. "I'm stayin' here. You tell him." He grabbed a bowl and filled it from her cauldron. "I'm on my lunch break." Fizz pulled a bandolier off the wall and filled it with shakers of salt, pepper, and two kinds of beetle carapace. Like she always said, spices were the spice of life. She tasted the soup one last time, hauled the cauldron off the coals, and lifted it with a grunt. She'd have to cross the battlefield, but she was going to go as far as she could in their own trenches. This was, after all, an important mission. Fizz dashed down the trench, soup in hand, trying not to spill a drop. Rocks and arrows rained down. Some fell in the soup. That was all right—they'd add flavor. She ran through the chaos, stepping over other goblins, running between the legs of orcs, and ignoring the shouts of surprise that followed her down the narrow trench. The way ahead was blocked by a squad of nervous, milling goblins. She slowed and stopped. "Um, excuse me," she said. "I'm on an urgent mission for the general!" Nobody moved. One of the goblins picked his nose at her. She tried to shoulder past. "Move!" she said. They didn't. Fizz took a deep breath. "HOT SOUP! COMIN' THROUGH!" #figure(image("007_Comin' Through!/02.jpg", width: 100%), caption: [Hot Soup | Art by <NAME>umbo], supplement: none, numbering: none) The goblins scrambled to get out of her way, and she ran onward... ...until she tripped over someone's foot. The soup cauldron left her hands and tumbled through the air. She dove and caught the hot cauldron, landing hard but managing not to spill more than a bowlful. She stood up, dusted herself off, and looked around. Behind her, the source of her near-disaster, was a goblin minelayer. #figure(image("007_Comin' Through!/03.jpg", width: 100%), caption: [Goblin Kaboomist | Art by <NAME>], supplement: none, numbering: none) The minelayer sat in the middle of the trench. He bit his tongue in concentration as he used a trowel—#emph[clang!] —to tamp down loose dirt. The mound of dirt barely covered a... Was that a #emph[bomb?] Yes—yes, it was. A fuse stuck out of the mound of dirt, burning down. #emph[Clang!] "What...what are you doing?" asked Fizz. She backed away. "Diggin'," said the minelayer. "Bombin'." "In our own trenches?" #emph[Clang!] A shrug. "Gotta do it somewhere." "So...how long until...?" "'Til what?" he said. The fuse was quite low now. "Never mind," said Fizz. "I...I can see you're very busy." #emph[Clang!] Fizz ran. The explosion was very loud. Her ears popped, and dirt showered down around her. Well, mostly dirt. Fizz rounded a corner and skidded to a halt behind a line of goblins carrying large, hot cauldrons. Was this the lunch detail? Had the general ordered a #emph[lot] of soup? "Ember haulers ready!" yelled an unseen sergeant. #figure(image("007_Comin' Through!/04.jpg", width: 100%), caption: [Ember Hauler | Art by <NAME>], supplement: none, numbering: none) #emph[Oh, no.] Fizz began to back away, but bumped into another goblin carrying a huge cauldron who'd lined up behind her. Fizz turned to apologize as coals spilled out and fell on the goblin's nose. She yelped and glared at Fizz. "Ember haulers...attaaaaaack!" Well, she needed to cross the battlefield anyway... The goblin behind her pushed against Fizz's back. Fizz shrugged, hefted her soup cauldron, and ran up a ramp and over the edge of the trench with the ember haulers. Bombs exploded. Goblins cowered. Orcs yelled. In the distance, humans in gleaming armor charged, waving shining swords and long, wicked spears. In the middle distance, the general's pennant hung limply above a large, grubby tent. She was getting close! Around her, the ember haulers spilled their cargoes with a hiss, and sometimes screamed as the hot coals showered down. For a few lucky ones—comparatively lucky, anyway—they succeeded in their mission, and it was the enemy screaming. Fizz hot-footed her way across a swath of embers and kept running. Goblins milled around her. Orcs barked orders. The thin, mewling sounds of human speech were barely audible, even though she was pretty sure the humans were yelling at the top of their lungs. Huffing and puffing, Fizz paused to catch her breath among a group of goblin irregulars who were cowering inside a large crater. "Izzat lunch?" asked one. "Not for you," Fizz said. She puffed out her chest. "I'll have you know this is the general's lunch." "Ohhh, the #emph[general] ," said another. "He's already sent us to die once. What's he gonna do if we steal his soup?" "He'll have you drawn and quartered and...and...and stewed!" "Least then I'd have some food," grumbled a third. The irregulars surrounded Fizz and her soup pot. "You will not steal the general's lunch," said Fizz. "I...I won't allow it. Think of...think of..." "Think of the lads and lasses back home!" yelled a booming voice. There, at the edge of the crater, stood a dashing figure, sword upraised. #figure(image("007_Comin' Through!/05.jpg", width: 100%), caption: [Goblin Rabblemaster | Art by <NAME>ov], supplement: none, numbering: none) "Think of all o' them sittin' in their warrens, warm and safe, with plenty to eat. Why, they're probably back there thinking to themselves, 'I'm sure glad I ain't fightin' in no war!'" He paused. Fizz held her breath. The irregulars leaned in expectantly. "Uh, wait," he said, scratching his head. "That kinda got away from me." The irregulars glanced at each other. "But the point...?" said Fizz. "Right! The point," he said. "The point is...see, what I meant was...well, we're all in this together, and if they don't hang us separately, it's probably because they hanged us all at once. Or...something. Anyway, as a great general once said..." He raised his sword high and pointed at the humans' trenches. "Everybody but me—CHARGE!" The irregulars cheered and ran toward the enemy battle line. Fizz was simply swept along. "No, wait, I need to—" She tried to charge back the way she'd came, but they were all around her. Behind them, the goblin who had inspired them cowered in the crater they had vacated. They ran in a howling mob, pulling Fizz along. Her soup sloshed dangerously. Then they were over the lip of the enemy trench. Fizz landed on a pile of groaning irregulars. She scrambled off, and they ran charging into the trench system. Fizz looked around. The trenches were straight and neatly excavated, with tall sides that didn't slope even a little. She hunted desperately for an exit, but soon heard boots approaching and the squeaky voices of humans. With no other options, she set down the cauldron and hid behind it. "—don't know why we even bother," one of them was saying. "The way they fight, they'd kill themselves off if we just left them alone." "You know that's not true," said another. This one had an even higher voice. A female? "They breed like rats and they fight like rabid dogs. With the orcs in charge, they could overrun the whole western reach." "Ought to go into the mountains and kill 'em all off," said the first voice, drawing still closer. "Drag 'em out of their warrens and—" Fizz seethed. The humans rounded the corner, and the first soldier cut himself off. "Hey, the lunch detail showed up for once!" #emph[Oh, no. No no no no no.] "Are you sure?" said the second soldier. "That stuff doesn't smell right." "I'm too hungry to care," said the first. The clatter of bowls. A sloshing, sucking sound. Fizz peeked out around the cauldron as the human lifted a spoon overflowing with Fizz's signature soup, blew on it, and stuck it in his mouth. His face turned red, then green, then purple. He keeled over. The second soldier backed away in horror. "Chemical attack!" she yelled. "Ward spells, now!" She ran down the trench. Fizz crawled out from behind the cauldron. The soldier had stopped twitching. "Drag #emph[you] out of your warren," mumbled Fizz. "Jerk." Standing on his breastplate, she was just barely able to lift the heavy cauldron out of the trench and scramble up after it. The battle seemed to be going their way. But she had to hurry. Still distant, further to her left than she'd been expecting, was the general's tent. She started running. She ran through a quiet section of the front, where the battle had moved on. She reached the top of a heap of dirt and saw an opportunity. There, sitting on the ground, was a half-deflated goblin balloon-toad. The toad wheezed contentedly. The gondola lay on its side, and two crew-goblins argued about whose fault it was. "Excuse me," said Fizz. Both goblins turned. "I'm on a very important mission for the general," said Fizz. "I need to get to his tent right away. Fly me there, and your reward will be...something, probably!" The goblins shrugged. "Beats waiting here for the humans to come back, I guess," said one of them. "Is that...soup?" said the other. "You bet it is," said Fizz. "Go!" "Well, you heard her!" said the first crew-goblin. "#emph[Inflate the toad!] " "I'm standin' right here," said the other. After much grousing, some frantic inflating, and only a little bit of frog drool in the soup, the balloon began to rise into the air. #figure(image("007_Comin' Through!/06.jpg", width: 100%), caption: [Goblin Balloon Brigade | Art by Lars Grant-West], supplement: none, numbering: none) "Get in!" said one of the goblins. The gondola rose just barely off the ground. "No time!" said Fizz. "I'll want to land in a hurry." She wrapped a dangling rope around one arm, looped it around the soup, and hung on. "That," the other goblin called from above her, "is the stupidest thing I have ever seen." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) General Razgar sat in his tent, trying to concentrate on the battle map through a growing and especially surly hunger. His stomach growled loud enough to hear over the sounds of the battle. "Where's my soup?" he bellowed. "I-I-I-I-I-I sent a messenger," said Yort, his goblin adjutant. He groveled. He was absolutely pathetic, and Razgar liked him that way. "Just one?" yelled Razgar. "I'm s-s-s-s-sorry, my lord!" said Yort. "I'll send more. I'll—I'll send dozens! But you said you wanted the best, and Fizz is—" He paused and cocked his hears. "What's that noise?" Goblins had sharper ears than orcs—one of their very few advantages, besides sheer rate of reproduction—so it took a moment before Razgar heard it too. "Comin' throoooouuuuuuuuuuuuuuugggghhhh!" Yort opened the side of the tent to reveal an absurd sight: a goblin civilian holding an oversized cauldron dangling from a goblin toad-balloon. The goblin skidded into the tent, tumbling head over heels and landing with a grunt in a pile of maps. The cauldron of soup thumped to the ground in front of the general, sloshing slightly. It was still piping hot. The goblin chef climbed out of the pile of maps and saluted. She came up to Razgar's mid-thigh. "Field Chef Fizz, reporting for duty as ordered!" she yelled. "At ease," said the general. "Well then, Field Chef. Let's see if you're as good as they say..." He hefted the entire cauldron, lifted it to his lips, and began to drink. It seared his throat and filled his belly and made his eyes water, just like a good soup ought to. The taste was indescribable. Boots, dirt, rats, a dash of goblin sweat, a splash of toad drool, and... He stopped drinking. "Is that beetle carapace?" "Yes, sir," said the chef. "The red kind and the shiny kind, sir." He drank the rest of the soup, set the cauldron down with a clang, and wiped his mouth on his sleeve. The goblin chef waited anxiously. "Good work...Field Chef, First Class." The newly promoted chef beamed with pride. The general had just made up the position of field chef, first class, but it seemed to make her happy. "Yes," he said. "That was very good." He gazed out at the battle still raging. They were winning, but there would be many hours of mop-up. "In fact," he said, "I think I'll have another."
https://github.com/0xPARC/0xparc-intro-book
https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/README.md
markdown
# Introduction to Programmable Cryptography This is an attempt at an introductory lecture notes on programmable cryptography. It is developed by [0xPARC](https://0xparc.org/). The source files are written in [Typst](https://typst.app). ## Downloading the book - If you want the latest **tagged** version (i.e. that has a release number), check the [Releases page](https://github.com/0xPARC/0xparc-intro-book/releases/). We tag the versions of the book as they reach certain milestones, e.g. just before we send them off to the printer. - If you want to download the compiled book as of the latest commit, go under the [Actions page](https://github.com/0xPARC/0xparc-intro-book/actions) and click the most recent commit. Scroll down until you see the section titled "Artifacts" and click the link labeled "PDF". ![Where to find artifacts for the latest compiled build.](artifacts.png) ## Spot a typo? Have a suggestion? Please open a [GitHub issue](https://github.com/0xPARC/0xparc-intro-book/issues)!
https://github.com/TOD-theses/paper-T-RACE
https://raw.githubusercontent.com/TOD-theses/paper-T-RACE/main/utils.typ
typst
#import "@preview/dashy-todo:0.0.1": todo #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #import "@preview/ctheorems:1.1.2": * #let theorem = thmbox("theorem", "Theorem") #let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em)) #let proof = thmproof("proof", "Proof") #let proposition = thmbox("proposition", "Proposition") // some shortcuts #let pre = "prestate" #let post = "poststate" #let colls = "collisions" #let changedKeys = "changed_keys" #let stateKey(type, ..args) = [(‘#type’, #args.pos().join(","))]
https://github.com/RanolP/resume
https://raw.githubusercontent.com/RanolP/resume/main/modules/github.typ
typst
#import "components.typ": chip, icon #let gh-repo(name-with-owner) = link("https://github.com/" + name-with-owner)[ #icon("devicon/github", bottom: -1em / 6) #text(weight: 700)[#name-with-owner] ] #let gh-pull-chip-open(content: "Open") = { chip(background: color.rgb("#238636"))[ #set text(size: 0.75em, weight: 500, fill: color.rgb("#ffffff")) #icon("octicon/git-pull-request-16?color=#ffffff") #content ] } #let gh-pull-chip-merged(content: "Merged") = { chip(background: color.rgb("#8250df"))[ #set text(size: 0.75em, weight: 500, fill: color.rgb("#ffffff")) #icon("octicon/git-merge-16?color=#ffffff") #content ] } #let gh-pull-req(url) = { [#metadata(url) <github-pull>] } #let gh-pull(url) = { [#metadata(url) <github-pull>] let pull-db = json("../assets/.automatic/github/pull.json") let pull = pull-db.at(url, default: none) if pull == none { let match = url.match(regex("https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/[0-9]+")).captures return ("nameWithOwner": match.at(0) + "/" + match.at(1), "url": url) } else { return (..pull, "url": url) } } #let gh-pull-rich(pull) = { if pull.at("state", default: none) == none { text(fill: color.rgb("#ff0000"))[\#NO_GITHUB_PULL_DATA\#] return } text(size: 0.8em)[ #if pull.state == "OPEN" { gh-pull-chip-open() } else if pull.state == "MERGED" { gh-pull-chip-merged() } else { pull.state } #link(pull.url)[ #text(weight: 600)[#pull.title] ] #h(1fr) #text(size: 0.8em, fill: color.rgb("#595959"))[ \##pull.number, #datetime(..pull.updatedAt).display() ] ] } #let gh-pull-short(pull, full: false) = { if pull.at("state", default: none) == none { text(fill: color.rgb("#ff0000"))[\#NO_GITHUB_PULL_DATA\#] return } let match = pull.url.match(regex("https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/[0-9]+")).captures let label = if full { match.at(0) + "/" } else { "" } + match.at(1) + " #" + str(pull.number) link(pull.url)[ #{ if pull.state == "OPEN" { gh-pull-chip-open(content: label) } else if pull.state == "MERGED" { gh-pull-chip-merged(content: label) } else { pull.state } } ] } #let gh-issue(url, show-repo: false) = { [#metadata(url) <github-issue>] let issue-db = json("../assets/.automatic/github/issue.json") if issue-db.at(url, default: none) != none { let issue = issue-db.at(url) if issue.state == "OPEN" { { chip(background: color.rgb("#1f883d"))[ #set text(size: 8pt, weight: 500, fill: color.rgb("#ffffff")) #icon("octicon/issue-opened-16?color=#ffffff") Open ] } } else if issue.state == "CLOSED" { { chip(background: color.rgb("#8250df"))[ #set text(size: 8pt, weight: 500, fill: color.rgb("#ffffff")) #icon("octicon/issue-closed-16?color=#ffffff") Closed ] } } else { issue.state } link(url)[ #if show-repo { issue.nameWithOwner } #text(weight: 600)[#issue.title] \ #text(size: 0.75em)[ \##issue.number at #datetime(..issue.updatedAt).display() ] ] } else { text(fill: color.rgb("#ff0000"))[\#NO_GITHUB_ISSUE_DATA\#] } }
https://github.com/maucejo/book_template
https://raw.githubusercontent.com/maucejo/book_template/main/template/chapters/ch2.typ
typst
MIT License
#import "../../src/book.typ": * #show: chapter.with(title: "Deuxième chapitre") == Objectifs #lorem(100) $ arrow(V)(M slash R_0) = lr((d arrow(O M))/(d t)|)_(R_0) + theta $ La Figure @b2 présente la carte du Cnam @Jon22. #subfigure( figure(image("../images/chapitre1/cnam_region.png"), caption: []), figure(image("../images/chapitre1/cnam_region.png"), caption: []), <b2>, columns: (1fr, 1fr), caption: [(a) Left image and (b) Right image], label: <fig:subfig2>, )
https://github.com/liuguangxi/suiji
https://raw.githubusercontent.com/liuguangxi/suiji/main/tests/test-choice-f.typ
typst
MIT License
#set document(date: none) #import "/src/lib.typ": * #let print-arr(arr) = { if type(arr) != array { [#raw(str(arr) + " ")] } else { [#raw(arr.map(it => str(it)).join(" "))] } } #{ let rng = gen-rng-f(42) let arr = () (rng, arr) = choice-f(rng, range(30)) raw(repr(arr)); parbreak() (rng, arr) = choice-f(rng, range(30), size: 1) raw(repr(arr)); parbreak() (rng, arr) = choice-f(rng, range(30), size: 0) raw(repr(arr)); parbreak() [replacement: *false*, permutation: *false* \ ] for i in range(10) { (rng, arr) = choice-f(rng, range(30), size: 15, replacement: false, permutation: false) print-arr(arr); [\ ] } parbreak() [replacement: *false*, permutation: *true* \ ] rng = gen-rng-f(42) for i in range(10) { (rng, arr) = choice-f(rng, range(30), size: 15, replacement: false, permutation: true) print-arr(arr); [\ ] } parbreak() [replacement: *true* \ ] rng = gen-rng-f(42) for i in range(10) { (rng, arr) = choice-f(rng, range(30), size: 15, replacement: true) print-arr(arr); [\ ] } parbreak() }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-05.typ
typst
Other
// Test lvalue out of bounds. #{ let array = (1, 2, 3) // Error: 3-14 array index out of bounds (index: 3, len: 3) and no default value was specified array.at(3) = 5 }
https://github.com/talal/pesha
https://raw.githubusercontent.com/talal/pesha/main/lib.typ
typst
MIT No Attribution
#let pesha( name: "", address: "", contacts: (), profile-picture: none, paper-size: "a4", footer-text: none, page-numbering-format: "1 of 1", body, ) = { // Set document metadata. set document( title: name, author: name, keywords: (name, "curriculum vitae", "cv", "resume"), ) // Configure text properties. set text(size: 10pt, hyphenate: false) // Text settings used across the template. let head-text = text.with(font: "Cantarell", weight: "medium") // Set page properties. set page( paper: paper-size, margin: ( x: 14%, top: if profile-picture == none {13%} else {8.6%}, bottom: 10% ), // Display page number in footer only if there is more than one page. footer: context { set align(center) show text: it => { head-text(size: 0.85em, tracking: 1.2pt, it) } let total = counter(page).final().first() if total > 1 { let i = counter(page).at(here()).first() upper[#footer-text #counter(page).display(page-numbering-format, both: true)] } else { upper[#footer-text] } } ) // Display title and contact info. block(width: 100%, below: 1.5em)[ #let header-info = { show text: upper head-text(size: 1.8em, tracking: 3.2pt, name) v(1.4em, weak: true) show text: it => { head-text(size: 0.86em, tracking: 1.4pt, it) } address if contacts.len() > 0 { v(1em, weak: true) grid(columns: contacts.len(), gutter: 1em, ..contacts ) } } #if profile-picture != none { grid( columns: (1fr, auto), box( clip: true, width: 3.3cm, height: 3.3cm, radius: 2.5cm, profile-picture, ), align(right + horizon, header-info) ) } else { align(center, header-info) } ] // Configure heading properties. show heading: it => { line(length: 100%, stroke: 0.5pt) pad( top: -0.85em, left: 0.25em, bottom: 0.6em, upper(head-text(weight: "black", size: 0.7em, tracking: 0.6pt, it)) ) } // Configure paragraph properties. set par(leading: 0.7em, justify: true, linebreaks: "optimized") body } // This function formats its `body` (content) into a block of experience section. #let experience( body, place: none, title: none, location: none, time: none, ) = { set list(body-indent: 0.85em) block(width: 100%, pad(left: 0.25em)[ #text(size: 1.4em, place) #h(1fr) #text(size: 1.3em, time) #v(1em, weak: true) #emph(title) #if location != none [ #h(1fr) #text(size: 0.9em, location) ] #v(1em, weak: true) #body ]) } // Workaround for the lack of an `std` scope. #let std-smallcaps = smallcaps #let std-upper = upper // Overwrite the default `smallcaps` and `upper` functions with increased spacing between // characters. We do this so that when someone uses these functions they will get spacing // which fits in better with the rest of the template. #let smallcaps(body) = std-smallcaps(text(tracking: 0.6pt, body)) #let upper(body) = std-upper(text(tracking: 0.6pt, body))
https://github.com/barrel111/readings
https://raw.githubusercontent.com/barrel111/readings/main/notes/mira.typ
typst
#import "@local/preamble:0.1.0": * #import "@preview/commute:0.2.0": node, arr, commutative-diagram #show: project.with( course: "Analysis", sem: "Summer", title: "Measure, Integration and Real Analysis", subtitle: "Axler", authors: ("<NAME>",), ) #set enum(indent: 15pt, numbering: "a.") = Riemann Integration == Review: Riemann Integral #definition("partition")[ Suppose $a, b in RR$ with $a < b$. A _partition_ of $[a, b]$ is a finite list of the form $x_0, x_1, dots, x_n$, where $ a = x_0 < x_1 < dots.c < x_n = b. $] We use a partition $x_1, x_1, dots, x_n$ of $[a, b]$ to think of $[a, b]$ as a union of closed subintervals, $ [a, b] = [x_0, x_1] union [x_1, x_2] union dots.c union [x_(n - 1), x_n]. $ #definition("notation for infimum and supremum of a function")[If $f$ is a real-valued function and $A$ is a subset of the domain of $f$, then $ inf_A f = inf {f(x) : x in A} #h(5pt) "and" #h(5pt) sup_A f = sup {f(x) : x in A}. $] #definition("lower and upper Riemann sums")[Suppose $f: [a, b] -> RR$ is a bounded function and $P$ is a partition $x_0, dots, x_n$ of $[a, b]$. The _lower Riemann sum_ $L(f, P, [a, b])$ and the _upper Riemann sum_ $U(f, P, [a, b])$ are defined by $ L(f, P, [a, b]) = sum_(j = 1)^n (x_j - x_(j - 1)) inf_([x_(j - 1), x_j]) f $ and $ U(f, P, [a, b]) = sum_(j = 1)^n (x_j - x_(j - 1)) sup_([x_(j - 1), x_j]) f. $] #lemma("inequalities with Riemann sums")[ Suppose $f: [a, b] -> RR$ is a bounded function and $P, P'$ are partitions of $[a, b]$ such that the list are defining $P$ is a sublist of the list defining $P'$. Then $ L(f, P, [a, b]) <= L(f, P', [a, b]) <= U(f, P', [a, b]) <= U(f, P, [a, b]). $] #lemma($"lower Riemann sums" <= "upper Riemann sums"$)[Suppose $f: [a, b] -> RR$ is a bounded function and $P, P'$ are partitions of $[a, b]$. Then $ L(f, P, [a, b]) <= U(f, P', [a, b]). $] #definition("lower and upper Riemann integrals")[Supose $f: [a, b] -> RR$ is a bounded function. The _lower Riemann integral_ $L(f, [a, b])$ and hte _upper Riemann integral_ $U(f, [a, b])$ of $f$ are defined by $ L(f, [a, b]) = sup_P L(f, P, [a, b]) $ and $ U(f, [a, b]) = inf_P U(f, P, [a, b]) $ where the supremum and infimum above are taken over all partitions $P$ of $[a, b]$.] #lemma($"lower Riemann integral" <= "upper Riemann integral"$)[ Suppose $f: [a, b] -> RR$ is a bounded function. Then $ L(f, [a, b]) <= U(f, [a, b]). $] #definition("Riemann integrable; Riemann integral")[+ A bounded function on a closed bounded interval is called _Riemann integrable_ if its lower Riemann integral equals its upper Riemann integral. + If $f: [a, b] -> RR$ is Riemann integrable, then the _Riemann integral_ $integral_a^b f$ is defined by $ integral_a^b f = L(f, [a, b]) = U(f, [a, b]). $] #prop("continuous functions are Riemann integrable")[Every continuous real-valued function on each closed bounded interval is Riemann integrable.] #lemma("bounds on Riemann integral")[Suppose $f: [a, b] -> RR$ is Riemann integrable. Then $ (b - a) inf_([a, b]) f <= integral_a^b f <= (b - a) sup_([a, b]) f. $] == Riemann Integral Is Not Good Enough There are three issues we discuss + Riemann integration does not handle functions with many discontinuities; + Riemann integration does not handle unbounded functions; + Riemann integration does not work well with limits. #example("a function that is not Riemann integrable")[ Define $f: [0, 1] -> RR$ by $ f(x) = cases(1 #h(15pt) &"if" x "is rational," \ 0 &"if" x "is irrational.") $ If $[a, b] subset.eq [0, 1]$ with $a < b$, then $ inf_([a, b]) f = 0 #h(10pt) "and" #h(10pt) sup_([a, b]) f= 1 $ because $[a, b]$ contains an irrational number and contains a rational number. Thus, $L(f, P, [0, 1]) = 0$ and $U(f, P, [0, 1]) = 1$ for any partition $P$ of $[0, 1]$. Since $L(f, [0, 1]) != U(f, [0, 1])$, we conclude that $f$ is not Riemann integrable. ] #example("Riemann integration does not work with unbounded functions")[ Define $f: [0, 1] -> RR$ by $ f(x) = cases(1/sqrt(x) #h(15pt) & "if" 0 < x <= 1"," \ 0 & "if" x = 0.) $ If $x_0, x_1, dots, x_n$ is a partition of $[0, 1]$, then $sup_[x_0, x_1] f = oo$. Then, $U(f, P, [0, 1]) = infinity$ for every partition $P$ of $[0, 1]$. However, we should consider the area under the graph of $f$ to be $2$ and not $oo$ as $ lim_(a arrow.b 0) integral_a^1 f = lim_(a arrow.b 0) (2 - 2 sqrt(a)) = 2. $ Calculus courses fix with this issue by just defining $integral_0^1 1/sqrt(x) "dx"$ to be $lim_(a arrow.b 0) integral_a^1 1/sqrt(x) "dx"$. ] #example("area seems to make sense, but Riemann integral is not defined")[Let $r_1, r_2, dots$ be a sequence that includes each rational number in $(0, 1)$ exactly once and includes no other numbers. For $k in ZZ^+$, define $f_k: [0, 1] -> RR$ by $ f_k (x) = cases(1/(sqrt(x - r_k)) #h(15pt) &"if" x > r_k "," \ 0 &"if" x <= r_k".") $ Then define $f: [0, 1] -> [0, oo]$ by $ f(x) = sum_(k = 1)^infinity (f_k(x))/2^k. $ Since every nonempty open subinterval of $[0, 1]$ contains a rational number, $f$ is unbounded on every such subinterval. Thus, the Riemann integral of $f$ is undefined on every subinterval of $[0, 1]$ with more than one element. However, the area under the graph of each $f_k$ is less than $2$. Then by the definition of $f$, the area under the graph of $f$ should be less than $2$.] #example("Riemann integration does not work well with pointwise limits")[ Let $r_1, r_2, dots$ be a sequence that includes each rational number in $[0, 1]$ exactly once and that includes no other numbers. For $k in ZZ^+$, define $f_k: [0, 1] -> RR$ by $ f_k (x) = cases(1 #h(15pt) &"if" x in {r_1, dots, r_k}"," \ 0 &"otherwise.") $ Each $f_k$ is Riemann integrable and $integral_0^1 f_k = 0$. Define $f: [0, 1] -> RR$ by $ f(x) = cases(1 #h(15pt) &"if" x "is rational," \ 0 #h(15pt) &"if" x "is rational.") $ Then $ lim_(k -> infinity) f_k (x) = f(x) "for each" x in [0, 1]. $ However, $f$ is not Riemann integrable even though $f$ is the pointwise limit of a sequence of integrable functions bounded by $1$. ] There is a condition under which Riemann integrals behave well with limits-- though, this positive result has the undesirable hypothesis of the limit function $f$ being Riemann integrable. #prop("interchanging Riemann integral and limit")[Suppose $a, b, M in RR$ with $a < b$. Suppose $f_1, f_2, dots$ is a sequence of Riemann integrable functions on $[a, b]$ such that $ |f_k (x)| <= M $ for all $k in ZZ^+$ and all $x in [a, b]$. Suppose $lim_(k -> infinity) f_k (x)$ exists for each $x in [a, b]$. Define $f: [a, b] -> RR$ by $ f(x) = lim_(k -> infinity) f_k (x). $ If $f$ is Riemann integrable on $[a, b]$, then $ integral_a^b f = lim_(k -> oo) integral_a^b f_k. $ ] = Measures == Outer Measure on $RR$ #definition("length of open interval")[The _length_ $ell(I)$ of an open interval $I$ is define by $ ell (I) = cases(b - a #h(15pt) &"if" I = (a, b) "for some" a\, b in RR "with" a < b, 0 &"if" I = nothing, oo &"if" I = (-oo, a) "or" I = (a, oo) "for some" a in RR, oo &"if" I = (-oo, oo)) $] #definition("outer measure")[The _outer measure_ $abs(A)$ of a set $A subset.eq RR$ is defined by $ abs(A) = inf { sum_(k = 1)^oo ell (I_k) bar I_1, I_2, dots "are open intervals such that" A subset.eq union.big_(k = 1)^infinity I_k }. $] #example("finite sets have outer meaure 0")[Let $A = {a_1, dots, a_n}$ be a finite subset of $RR$. Suppose $epsilon > 0$. Define the sequence of $I_1, I_2, dots$ of open intervals by $ I_k = cases((a_k - epsilon \, a_k + epsilon) #h(15pt) &"if" k <= n, nothing &"if" k > n.) $ Then $I_1, I_2, dots$ is a sequence of open interval whose union contains $A$. Then, $sum_(k = 1)^infinity ell(I_k) = 2 epsilon n$. Hence $abs(A) <= 2 epsilon n$. Since $epsilon$ is an arbitrary positive number, this implies that $abs(A) = 0$.] === Good Properties of Outer Measure #prop[Every countable subset of $RR$ has outer measure $0$.] #prop[Suppose $A$ and $B$ are subsets of $RR$ with $A subset.eq B$. Then $abs(A) <= abs(B)$. ] #definition("translation")[If $t in RR$ and $A subset.eq RR$, then the _translation_ $t + A$ is defined by $ t + A = {t + a bar a in A}. $] #prop("translation invariant")[Suppose $t in RR$ and $A subset.eq RR$. Then $abs(t + A) = abs(A)$.] #prop("countable subadditivity")[Suppose $A_1, A_2, dots$ is a sequence of subsets of $RR$. Then $ abs(union.big_(k = 1)^oo A_k) <= sum_(k = 1)^oo abs(A_k). $] === Outer Measure of Closed Bounded Interval #definition("open cover; finite subcover")[Suppose $A subset.eq RR$ + A collection $cal(C)$ of open subsets of $RR$ is called an _open cover_ of $A$ if $A$ is contained in the union of all the sets in $cal(C)$. + An open cover $cal(C)$ of $A$ is said to have a _finite subcover_ if $A$ is contained in the union of some finite list of sets in $cal(C)$.] #prop("Heine-Borel Theorem")[Every open cover of a closed bounded subset of $RR$ has a finite subcover.] #prop("outer measure of a closed interval)")[Suppose $a, b in RR$, with $a< b$. Then $abs([a, b]) = b - a$.] #prop("nontrivial intervals are uncountable")[Every interval in $RR$ that contains at least two distint elements is uncountable.] === Outer Measure is Not Additive #prop("non-additivity of outer measure")[There exist disjoint subsets $A$ and $B$ of $RR$ such that $abs(A union B) != abs(A) + abs(B)$.] == Measurable Spaces and Functions #prop( $"nonexistence of extension of length to all subsets of " RR$ )[There does not exist a function $mu$ with all the following properties. + $mu$ is a function from the set of subsets of $RR$ to $[0, oo]$. + $mu(I) = ell(I)$ for every open interval $I$ of $RR$. + $mu(union.big_(k = 1)^oo A_k) = sum_(k = 1)^oo mu(A_k)$ for every disjoint sequence $A_1, A_2, dots$ of subsets of $RR$. + $mu(t + A) = mu(A)$ for every $A subset.eq RR$ and every $t in RR$.] === $sigma$-Algebras #definition($sigma"-algebra"$)[Suppose $X$ is a set and $cal(S)$ is a set of subsets of $X$. THen $cal(S)$ is called a _$sigma$-algebra_ on $X$ if the following three conditions are satisfied: - $emptyset in cal(S)$; - if $E in cal(S)$, then $X \\ E in cal(S)$; - if $E_1, E_2, dots$ is a seuqence of elements of $cal(S)$, then $union.big_(k = 1)^oo E_k in cal(S)$.] #example[The following are some $sigma$-algebras on a set $X$. - ${emptyset, X}$ - $cal(P)(X)$ - The set of all subsets $E$ of $X$ such that $E$ is countable or $X \\ E$ is countable.] #prop($sigma"-algebras are closed under countable intersection"$)[Suppose $cal(S)$ is a $sigma$-algebra on a set $X$. Then + $X in cal(S)$; + if $D, E in cal(S)$, then $D union E in cal(S)$ and $D sect E in cal(S)$ and $D \\ E in cal(S)$; + if $E_1, E_2, dots$ is a sequence of elements of $cal(S)$, then $sect.big_(k = 1)^oo E_k in cal(S)$.] #definition("measurable space; measurable set")[- A _measurable space_ is an ordered pair $(X, cal(S))$, where $X$ is a set and $cal(S)$ is a $sigma$-algebra on $X$. - An element of $cal(S)$ is called an _$cal(S)$-measurable set_, or just a _measurable set_ if $cal(S)$ is clear from the context.] === Borel Subsets of $RR$ #prop($"smallest" sigma"-algebra containing a collection of subsets"$)[Suppose $X$ is a set and $cal(A)$ is a set of subsets of $X$. Then the intersection of all $sigma$-algebras on $X$ that contain $cal(A)$ is a $sigma$-algebra on $X$.] #example[ For a set $X$ with $cal(A) = {{x} bar x in X}$, the smallest $sigma$-algebra containing $cal(A)$ is the finite-cofinite $sigma$-algebra. ] #definition("Borel set")[The smallest $sigma$-algebra on $RR$ containing all open subsets of $RR$ is called the collection of _Borel subsets_ of $RR$. An element of this $sigma$-algebra is called a _Borel set_.] #example[- Every closed subset of $RR$ is a Borel set because every closed subset of $RR$ is the complement of an open subset of $RR$. - Every countable subset of $RR$ is a Borel subset because if $B = {x_1, x_2, dots}$, then $B = union.big_(k = 1)^oo {x_k}$, which is a Borel set because each ${x_k}$ is a closed set. - Every half-open interval $[a, b)$ (where $a, b in RR$) is a Borel set because $[a, b) = sect.big_(k = 1)^oo (a - 1/k, b)$. - If $f: RR -> RR$ is a function, then the set of points at which $f$ is continuous is the intersection of a sequence of open sets and thus is a Borel set.] #remark[ There is no finite procedure involving countable unions, countable intersection and complements for constructing the collection of Borel subsets.] === Inverse Images #definition($"inverse image;" f^(-1)(A)$)[If $f: X -> Y$ is a function nd $A subset.eq Y$, then the set $f^(-1)(A)$ is defined by $ f^(-1)(A) = {x in X bar f(x) in A}. $] #prop("algebra of inverse images")[Suppose $f: X -> Y$ is a function. Then + $f^(-1)(Y \\ A) = X \\ f^(-1)(A)$ for every $A subset.eq Y$; + $f^(-1)(union.big_(A in cal(A)) A) = union.big_(A in cal(A)) f^(-1)(A)$ for every set $cal(A)$ of subsets of $Y$; + $f^(-1)(sect.big_(A in cal(A))A) = sect.big_(A in cal(A)) f^(-1)(A)$ for every set $cal(A)$ of subsets of $Y$.] #prop("inverse image of a composition")[Suppose $f: X -> Y$ and $g: Y -> W$ are functions. Then $ (g compose f)^(-1)(A) = f^(-1)(g^(-1)(A)). $] . === Measurable Functions #definition("measurable function")[Suppose $(X, cal(S))$ is a measurable sapce. A function $f: X -> RR$ is called $cal(S)$-measurable if $ f^(-1)(B) in cal(S) $ for every Borel set $B subset.eq RR$] #definition($"characteristic function;"chi_E$)[Suppose $E$ is a subset of a set $X$. The _characteristic function of E_ is the function $chi_E: X -> RR$ defined by $ chi_E(x) = cases(1 #h(10pt)&"if" x in E\,, 0 &"if" x in.not E.) $] Note that, $ chi_E^(-1)(B) = cases(E &#h(20pt) "if" 0 in.not B "and" 1 in B\,, X \\ E &#h(20pt) "if" 0 in B "and" 1 in.not B\,, X &#h(20pt)"if" 0 in B "and" 1 in B\,, nothing &#h(20pt)"if" 0 in.not B "and" 1 in.not B.) $ Then, #lemma[$chi_E$ is an $cal(S)$-measurable function if and only if $E$ in $cal(S)$.] #prop("condition for measurable function")[Suppose $(X, cal(S))$ is a measurable space and $f: X -> RR$ is a function such that $ f^(-1)((a, infinity)) in cal(S) $ for all $a in RR$. Then $f$ is an $cal(S)$-measurable function.]<suff-cond-measurable> In general, we can say the following things. #lemma($"image of a" sigma"-algebra"$)[Suppose $(X, cal(S))$ is a measurable space and $f: X -> Y$ a function. Then, the following defines a $sigma$-algebra on $Y$ $ cal(F) = {A subset.eq Y bar f^(-1)(A) in cal(S) } $] So, the family from @suff-cond-measurable can be replaced by any family of sets such that the smallest $sigma$-algebra containing it also contains the Borel subsets of $RR$. #definition("Borel measurable function")[Suppose $X subset.eq RR$. A function $f: X -> RR$ is called _Borel measurable_ if $f^(-1)(B)$ is a Borel set for every Borel set $B subset.eq RR$.] #prop("every continuous function is Borel measurable")[Every continuous real-valued function defined on a Borel subset of $RR$ is a Borel measurable function.] #definition("increasing functions; strictly increasing")[Suppose $X subset.eq RR$ and $f: X -> RR$ is afunction - $f$ is called _increasing_ if $f(x) <= f(y)$ for all $x, y in X$ with $x < y$. - $f$ is called _strictly increasing_ if $f(x) < f(y)$ for all $x, y in X$ with $x < y$.] #prop("every increasing function is Borel measurable")[Every increasing function defined on a Borel subset of $RR$ is a Borel measurable function.] #prop("composition of measurable functions")[Suppose $(X, cal(S))$ is a measurable space and $f: X -> RR$ is an $cal(S)$-measurable function. Suppose $g$ is a real-valued measurable function defined on a subset of $RR$ that includes the range of $f$. Then $g compose f: X -> RR$ is an $cal(S)$-measurable function.] #prop("algebraic operations with measurable functions")[Suppose $(X, cal(C))$ is a measurable space and $f, g: X -> RR$ are $cal(S)$-measurable. Then + $f + g, f - g$ and $f g$ are $cal(S)$-measurable functions; + if $g(x) != 0$ for all $x in X$, then $f/g$ is an $cal(S)$-measurable function.] #prop($"limit of " cal(S)"-measurable functions"$)[Suppose $(X, cal(S))$ is a measurable space and $f_1, f_@, dots$ is a sequence of $cal(S)$-measurable functions from $X$ to $RR$. Suppose $lim_(k -> oo) f_k(x)$ exists for each $x in X$. Define $f: X -> RR$ by $ f(x) = lim_(k -> oo) f_k(x). $ Then $f$ is an $cal(S)$-measurable function.] #definition($"Borel subsets of " [-oo, oo]$)[A subset of $[-oo, oo]$ is called a _Borel set_ if its intersection with $RR$ is a Borel set.] #definition("measurable function")[Suppose $(X, cal(S))$ is a measurable space. A function $f: X -> [-oo, oo]$ is called _$cal(S)$-measurable_ if $ f^(-1)(B) in cal(S) $ for every Borel set $B subset.eq [-oo, oo]$.] #prop("condition for measurable function")[Suppose $(X, cal(S))$ is a measurable sapce and $f: X -> [-oo, oo]$ is a function such that $ f^(-1)((a, oo]) in cal(S)) $ for all $a in RR$. Then $f$ is an $cal(S)$-measurable function.] #prop($"infimum and supremum of a sequence of " cal(S)"-measurable functions"$)[Suppose $(X, cal(S))$ is a measurable space and $f_1, f_2, dots$ is a seuqence of $cal(S)$-measurable functions from $X$ to $[-oo, oo]$. Define $g, h: X -> [-oo, oo]$ by $ g(x) = inf{f_k(x) bar k in ZZ^+} #h(10pt) "and" #h(10pt) h(x) = sup{f_k(x) bar k in ZZ^+}. $ Then $g$ and $h$ are $cal(S)$-measurable functions.] == Measures and Their Properties #definition("measure")[Suppose $X$ is a set and $cal(S)$ is a $sigma$-algebra on $X$. A _measure_ on $(X, cal(S))$ is a function $mu: cal(S) -> [0, oo]$ such that $mu(emptyset) = 0$ and $ mu(union.big_(k = 1)^(oo)E_k) = sum_(k = 1)^oo mu(E_k) $ for every disjoint sequence $E_1, E_2, dots$ of sets in $cal(S)$.] #example[ - If $X$ is a set, then _counting measure_ is the measure $mu$ defined on the $sigma$-algebra of all subsets of $X$ by setting $mu(E) = n$ if $E$ is a finite set containing exactly $n$ elements and $mu(E) = oo$ if $E$ is not a finite set. - Suppose $X$ is a set, $cal(S)$ is a $sigma$-algebra on $X$, and $c in X$. Define the _Dirac_ measure $delta_c$ on $(X, cal(S))$ by $ delta_c (E) = cases(1 &#h(15pt) "if" c in E\,, 0 &#h(15pt) "if" c in.not E.) $ - Suppose $X$ is a set, $cal(S)$ is a $sigma$-algebra on $X$, and $omega: X -> [0,oo]$ is a function. Define a measure $mu$ on $(X, cal(S))$ by $ mu(E) = sum_(x in E) w(x) $ for $E in cal(S)$. THe sum is defined as the supremum of all finite subsums $sum_(x in D) w(x)$ as $D$ ranges over all finite subsets of $E$. - Suppose $X$ is a set and $cal(S)$ is the $sigma$-algebra on $X$ consisting of all subsets of $X$ that are either countable or have a countable complement in $X$. Define a measure on $mu$ on $(X, cal(S))$ by $ mu(E) = cases(0 &#h(15pt) "if" E "is countable,", 3 &#h(15pt) "if" E "is uncountable.") $ - Suppose $cal(S)$ is the $sigma$-algebra on $RR$ consisting of all subsets of $RR$. Then the function that takes a set $E subset.eq RR$ to $abs(E)$ (the outer measure of $E$) is not a measure because it is not finitely additive. - Suppose $cal(B)$ is the $sigma$-algebra on $RR$ consisting of all Borel subsets of $RR$. The outer measure is a measure on $(RR, cal(B))$ (proven below). ] #definition("measure space")[A _measure space_ is an ordered triple $(X, cal(S), mu)$, where $X$ is a set, $cal(S)$ is a $sigma$-algebra on $X$, and $mu$ is a measure on $(X, cal(S))$.] === Properties of Measures #prop("measure preserves order; measure of a set difference")[Suppose $(X, cal(S), mu)$ is a measure space and $D, E in cal(S)$ are such that $D subset.eq E$. Then + $mu(D) <= mu(E);$ + $mu(E \\ D) = mu(E) - mu(D)$ provided that $mu(D) < oo$.] #remark[The hypothesis $mu(D) < oo$ is required for part $(b)$ to avoid undefined expressions of the form $oo - oo$.] #prop("countable subadditivity")[Suppose $(X, cal(S), mu)$ is a measure space and $E_1, E_2, dots in cal(S)$. Then $ mu(union.big_(k = 1)^oo E_k) <= sum_(k = 1)^oo mu(E_k). $] #prop("measure of an increasing union")[Suppose $(X, cal(S), mu)$ is a measure space and $E_1 subset.eq E_2 subset.eq dots.c$ is an increasing sequence of sets in $cal(S)$. Then $ mu(union.big_(k = 1)^oo E_k) = lim_(k -> oo) mu(E_k) $] #prop("measure of a decreasing intersection")[Suppose $(X, cal(S), mu)$ is a measure space and $E_1 supset.eq E_2 supset.eq dots.c$ is a decreasing sequence of sets in $cal(S)$, with $mu(E_1) < oo$. Then $ mu(sect.big_(k = 1)^oo E_k) = lim_(k -> oo) mu(E_k). $] #remark[The hypothesis $mu(E_1) < oo$ is necessary.] #prop("measure of a union")[Suppose $(X, cal(S), mu)$ is a measure space $D, E in cal(S)$, with $mu(D sect E) < oo$. Then $ mu(D union E) = mu(D) + mu(E) - mu(D sect E). $] == Lebesgue Measure === Additivity of Outer Measure on Borel Sets === Lebesgue Measurable Sets === Cantor Set and Cantor Function == Convergence of Measurable Functions
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/stroke_07.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // 0pt strokes must function exactly like 'none' strokes and not draw anything #rect(width: 10pt, height: 10pt, stroke: none) #rect(width: 10pt, height: 10pt, stroke: 0pt) #rect(width: 10pt, height: 10pt, stroke: none, fill: blue) #rect(width: 10pt, height: 10pt, stroke: 0pt + red, fill: blue) #line(length: 30pt, stroke: 0pt) #line(length: 30pt, stroke: (paint: red, thickness: 0pt, dash: ("dot", 1pt))) #table(columns: 2, stroke: none)[A][B] #table(columns: 2, stroke: 0pt)[A][B] #path( fill: red, stroke: none, closed: true, ((0%, 0%), (4%, -4%)), ((50%, 50%), (4%, -4%)), ((0%, 50%), (4%, 4%)), ((50%, 0%), (4%, 4%)), ) #path( fill: red, stroke: 0pt, closed: true, ((0%, 0%), (4%, -4%)), ((50%, 50%), (4%, -4%)), ((0%, 50%), (4%, 4%)), ((50%, 0%), (4%, 4%)), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/exzellenz-tum-thesis/0.1.0/template.typ
typst
Apache License 2.0
#import "cover.typ": * #import "titlepage.typ": * #import "disclaimer.typ": * #import "acknowledgement.typ": * #import "abstract.typ": * #let exzellenz-tum-thesis( degree: "The degree", program: "The Program", school: "The School", supervisor: "Your Supervisor", advisors: ("The first advisor", "The second advisor"), author: "The Author", startDate: "The Startdate", titleEn: "English Title", titleDe: "German Title", abstractEn: [English Abstract], abstractDe: [German Abstract], acknowledgements: [The acknowledgements], submissionDate: "(Handover Date)", showTitleInHeader: true, draft: true, body, ) = { let draft_string = "" if draft{ draft_string = "DRAFT - " } set document(author: author, title: draft_string + titleEn) set page( numbering: "1", number-align: center, margin: (left: 25mm, right: 25mm, top: 30mm, bottom: 30mm), header: { set text(8pt) h(1fr) if draft [ DRAFT ] }, ) set page(numbering: none) cover( title: draft_string + titleEn, degree: degree, program: program, author: author, school: school ) titlepage( title: draft_string + titleEn, titleDe: titleDe, degree: degree, program: program, school: school, supervisor: supervisor, advisors: advisors, author: author, startDate: startDate, submissionDate: draft_string + submissionDate ) disclaimer( title: titleEn, degree: degree, author: author, submissionDate: submissionDate ) acknowledgement(acknowledgements) abstract(lang: "en")[#abstractEn] abstract(lang: "de")[#abstractDe] counter(page).update(1) set page( header: { set text(8pt) if showTitleInHeader [ #author - #titleEn ] h(1fr) if draft [ DRAFT ] }, ) body }
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/110.%20foundervisa.html.typ
typst
foundervisa.html The Founder Visa April 2009I usually avoid politics, but since we now seem to have an administration that's open to suggestions, I'm going to risk making one. The single biggest thing the government could do to increase the number of startups in this country is a policy that would cost nothing: establish a new class of visa for startup founders.The biggest constraint on the number of new startups that get created in the US is not tax policy or employment law or even Sarbanes-Oxley. It's that we won't let the people who want to start them into the country.Letting just 10,000 startup founders into the country each year could have a visible effect on the economy. If we assume 4 people per startup, which is probably an overestimate, that's 2500 new companies. Each year. They wouldn't all grow as big as Google, but out of 2500 some would come close.By definition these 10,000 founders wouldn't be taking jobs from Americans: it could be part of the terms of the visa that they couldn't work for existing companies, only new ones they'd founded. In fact they'd cause there to be more jobs for Americans, because the companies they started would hire more employees as they grew.The tricky part might seem to be how one defined a startup. But that could be solved quite easily: let the market decide. Startup investors work hard to find the best startups. The government could not do better than to piggyback on their expertise, and use investment by recognized startup investors as the test of whether a company was a real startup.How would the government decide who's a startup investor? The same way they decide what counts as a university for student visas. We'll establish our own accreditation procedure. We know who one another are.10,000 people is a drop in the bucket by immigration standards, but would represent a huge increase in the pool of startup founders. I think this would have such a visible effect on the economy that it would make the legislator who introduced the bill famous. The only way to know for sure would be to try it, and that would cost practically nothing. Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.Related: The United States of Entrepreneurs About Half of VC-Backed Company Founders are Immigrants csell_env = 'ue1'; var storeCheckoutDomain = 'order.store.turbify.net'; function toOSTN(node){ if(node.hasAttributes()){ for (const attr of node.attributes) { node.setAttribute(attr.name,attr.value.replace(/(us-dc1-order|us-dc2-order|order)\.(store|stores)\.([a-z0-9-]+)\.(net|com)/g, storeCheckoutDomain)); } } }; document.addEventListener('readystatechange', event => { if(typeof storeCheckoutDomain != 'undefined' && storeCheckoutDomain != "order.store.turbify.net"){ if (event.target.readyState === "interactive") { fromOSYN = document.getElementsByTagName('form'); for (let i = 0; i < fromOSYN.length; i++) { toOSTN(fromOSYN[i]); } } } }); // Begin Store Generated Code // Begin Store Generated Code csell_page_data = {}; csell_page_rec_data = []; ts='TOK_STORE_ID'; // Begin Store Generated Code function csell_GLOBAL_INIT_TAG() { var csell_token_map = {}; csell_token_map['TOK_SPACEID'] = '2022276099'; csell_token_map['TOK_URL'] = ''; csell_token_map['TOK_BEACON_TYPE'] = 'prod'; csell_token_map['TOK_IS_ORDERABLE'] = '2'; csell_token_map['TOK_RAND_KEY'] = 't'; csell_token_map['TOK_STORE_ID'] = 'paulgraham'; csell_token_map['TOK_ITEM_ID_LIST'] = 'foundervisa'; csell_token_map['TOK_ORDER_HOST'] = 'order.store.turbify.net'; c = csell_page_data; var x = (typeof storeCheckoutDomain == 'string')?storeCheckoutDomain:'order.store.turbify.net'; var t = csell_token_map; c['s'] = t['TOK_SPACEID']; c['url'] = t['TOK_URL']; c['si'] = t[ts]; c['ii'] = t['TOK_ITEM_ID_LIST']; c['bt'] = t['TOK_BEACON_TYPE']; c['rnd'] = t['TOK_RAND_KEY']; c['io'] = t['TOK_IS_ORDERABLE']; YStore.addItemUrl = 'http%s://'+x+'/'+t[ts]+'/ymix/MetaController.html?eventName.addEvent&cartDS.shoppingcart_ROW0_m_orderItemVector_ROW0_m_itemId=%s&cartDS.shoppingcart_ROW0_m_orderItemVector_ROW0_m_quantity=1&ysco_key_cs_item=1&sectionId=ysco.cart&ysco_key_store_id='+t[ts]; } // Begin Store Generated Code function csell_REC_VIEW_TAG() { var env = (typeof csell_env == 'string')?csell_env:'prod'; var p = csell_page_data; var a = '/sid='+p['si']+'/io='+p['io']+'/ii='+p['ii']+'/bt='+p['bt']+'-view'+'/en='+env; var r=Math.random(); YStore.CrossSellBeacon.renderBeaconWithRecData(p['url']+'/p/s='+p['s']+'/'+p['rnd']+'='+r+a); } // Begin Store Generated Code var csell_token_map = {}; csell_token_map['TOK_PAGE'] = 'p'; csell_token_map['TOK_CURR_SYM'] = '$'; csell_token_map['TOK_WS_URL'] = 'https://paulgraham./cs/recommend?itemids=foundervisa&location=p'; csell_token_map['TOK_SHOW_CS_RECS'] = 'false'; var t = csell_token_map; csell_GLOBAL_INIT_TAG(); YStore.page = t['TOK_PAGE']; YStore.currencySymbol = t['TOK_CURR_SYM']; YStore.crossSellUrl = t['TOK_WS_URL']; YStore.showCSRecs = t['TOK_SHOW_CS_RECS'];
https://github.com/sa-concept-refactoring/doc
https://raw.githubusercontent.com/sa-concept-refactoring/doc/main/progress-bar.typ
typst
#let printProgressBar(progress, fill: gray, label: "") = { let colorScale = (red, orange, yellow, green) let colorScalePosition = if progress < 0.25 {0} else if progress < 0.5 {1} else if progress < 0.75 {2} else {3} set text(white, size: 8pt, ) set align(center) rect( fill: fill, width: 100%, height: 12pt, inset: 0pt, radius: 4pt, [ #set align(left) #rect( fill: colorScale.at(colorScalePosition), width: 100% * calc.min(progress, 1), height: 12pt, radius: 4pt, inset: 5pt )[ #set align(horizon) #{label} ] ], ) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/gallery/waves.typ
typst
Apache License 2.0
#import "@preview/cetz:0.2.0": canvas, draw, vector #set page(width: auto, height: auto, margin: .5cm) #let transform-rotate-dir(dir, up) = { dir = vector.norm(dir) up = vector.norm(up) let (dx, dy, dz) = dir let (ux, uy, uz) = up let (rx, ry, rz) = vector.norm(vector.cross(dir, up)) ((rx, dx, ux, 0), (ry, dy, uy, 0), (rz, dz, uz, 0), (0, 0, 0, 1)) } #canvas({ import draw: * // Set up the transformation matrix set-transform(transform-rotate-dir((1, 1, -1.3), (0, 1, .3))) scale(x: 1.5, z: -1) grid((0,-2), (8,2), stroke: gray + .5pt) // Draw a sine wave on the xy plane let wave(amplitude: 1, fill: none, phases: 2, scale: 8, samples: 100) = { line(..(for x in range(0, samples + 1) { let x = x / samples let p = (2 * phases * calc.pi) * x ((x * scale, calc.sin(p) * amplitude),) }), fill: fill) let subdivs = 8 for phase in range(0, phases) { let x = phase / phases for div in range(1, subdivs + 1) { let p = 2 * calc.pi * (div / subdivs) let y = calc.sin(p) * amplitude let x = x * scale + div / subdivs * scale / phases line((x, 0), (x, y), stroke: rgb(0, 0, 0, 150) + .5pt) } } } group({ rotate(x: 90deg) wave(amplitude: 1.6, fill: rgb(0, 0, 255, 50)) }) wave(amplitude: 1, fill: rgb(255, 0, 0, 50)) })
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/docs/gallery/io-flowchart.typ
typst
MIT License
#import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #set page(width: auto, height: auto, margin: 5mm, fill: white) #set text(white, font: "Fira Sans") #let colors = (maroon, olive, eastern) #diagram( edge-stroke: 1pt, node-corner-radius: 5pt, edge-corner-radius: 8pt, mark-scale: 80%, node((0,0), [input], fill: colors.at(0)), node((2,+1), [memory unit (MU)], fill: colors.at(1)), node((2, 0), align(center)[arithmetic & logic \ unit (ALU)], fill: colors.at(1)), node((2,-1), [control unit (CU)], fill: colors.at(1)), node((4,0), [output], fill: colors.at(2), shape: fletcher.shapes.hexagon), edge((0,0), "r,u,r", "-}>"), edge((2,-1), "r,d,r", "-}>"), edge((2,-1), "r,dd,l", "--}>"), edge((2,1), "l", (1,-.5), marks: ((inherit: "}>", pos: 0.65, rev: false),)), for i in range(-1, 2) { edge((2,0), (2,1), "<{-}>", shift: i*5mm, bend: i*20deg) }, edge((2,-1), (2,0), "<{-}>"), )
https://github.com/jneug/typst-tools4typst
https://raw.githubusercontent.com/jneug/typst-tools4typst/main/assert.typ
typst
MIT License
#import "alias.typ" #import "is.typ" // ================================= // Asserts // ================================= #let lazy-message( user-message, ..args ) = { if user-message == none { return "" } let lazy = user-message if type(lazy) != "function" { lazy = (..) => str(lazy) } return lazy(..args) } /// Asserts that #arg[test] is #value(true). /// See #doc("foundations/assert"). /// /// - test (boolean): Assertion to test. /// - message (string,function): A message to show if the assertion fails. #let that(test, message:"Test returned false, should be true.") = assert( test, message:lazy-message(message, test) ) /// Asserts that #arg[test] is #value(false). /// /// - test (boolean): Assertion to test. /// - message (string, function): A message to show if the assertion fails. #let that-not(test, message:"Test returned true, should be false.") = assert( not test, message:lazy-message(message, test) ) /// Asserts that two values are equal. /// See #doc("foundations/assert", name:"assert.eq", anchor:"assert-eq"). /// /// - a (any): First value. /// - b (any): Second value. /// - message (string, function): A message to show if the assertion fails. #let eq(a, b, message:(a, b) => "Value "+repr(a)+" was not equal to "+repr(b)) = assert.eq( a, b, message:lazy-message(message, a, b) ) /// Asserts that two values are not equal. /// See #doc("foundations/assert", name:"assert.ne", anchor:"assert-ne"). /// /// - a (any): First value. /// - b (any): Second value. /// - message (string, function): A message to show if the assertion fails. #let ne(a, b, message:(a, b) => "Value "+repr(a)+" was equal to "+repr(b)) = assert.ne( a, b, message:lazy-message(message, a, b) ) /// Alias for @@ne() #let neq = assert.ne /// Asserts that not one of #arg[values] is #value(none). /// Positional and named arguments are tested if provided. /// For named key-value pairs the value is tested. /// /// // Tests /// #assert.not-none(1) /// #assert.not-none(..range(4)) /// /// - ..values (any): The values to test. /// - message (string, function): A message to show if the assertion fails. #let not-none( ..values, message:(..a) => "Values should not be none. Got " + repr(a) ) = { assert( values.pos().all((v) => v != none) and values.named().values().all((v) => v != none), message:lazy-message(message, ..values) ) } /// Assert that #arg[value] is any one of #arg[values]. /// /// Tests /// #assert.any(..range(4), 3) /// /// - ..values (any): A set of values to compare #arg[value] to. /// - value (any): Value to compare. /// - message (string, function): A message to show if the assertion fails. #let any( ..values, value, message:(..a) => "Value should be one of " + repr(a.pos().slice(1)) + ". Got " + repr(a.pos().first()) ) = assert( value in values.pos(), message:lazy-message(message, value, ..values) ) /// Assert that #arg[value] is not any one of #arg[values]. /// /// // Tests /// #assert.not-any(none, auto, 3) /// /// - ..values (any): A set of values to compare `value` to. /// - value (any): Value to compare. /// - message (string, function): A message to show if the assertion fails. #let not-any( ..values, value, message:(..a) => "Value should not be one of " + repr(a.pos().slice(1)) + ". Got " + repr(a.pos().first()) ) = assert( value not in values.pos(), message:lazy-message(message, value, ..values) ) /// Assert that #arg[value]s type is any one of #arg[types]. /// /// // Tests /// #assert.any-type("float", "integer", 3) /// #assert.any-type("float", "integer", 3.3) /// #assert.any-type("string", "boolean", true) /// #assert.any-type("string", "boolean", "foo") /// /// - ..types (string): A set of types to compare the type of `value` to. /// - value (any): Value to compare. /// - message (string, function): A message to show if the assertion fails. #let any-type( ..types, value, message:(..a) => "Value should have any type of " + repr(a.pos().slice(1)) + ". Got " + repr(a.pos().first()) + " (" + type(a.pos().first()) + ")" ) = assert( type(value) in types.pos(), message:lazy-message(message, value, ..types) ) /// Assert that #arg[value]s type is not any one of #arg[types]. /// /// // Tests /// #assert.not-any-type("float", "integer", "foo") /// #assert.not-any-type("string", "boolean", 1%) /// /// - ..types (string): A set of types to compare the type of `value` to. /// - value (any): Value to compare. /// - message (string, function): A message to show if the assertion fails. #let not-any-type( ..types, value, message:(..a) => "Value should not have any type of " + repr(a.pos().slice(1)) + ". Got " + repr(a.pos().first()) + " (" + type(a.pos().first()) + ")" ) = assert( type(value) not in types.pos(), message:lazy-message(message, value, ..types) ) /// Assert that the types of all #arg[values] are equal to #arg[t]. /// /// // Tests /// #assert.all-of-type("string", "a", "b") /// #assert.all-of-type("length", 1pt, 3em, 4mm) /// /// - t (string): The type to test against. /// - ..values (any): Values to test. /// - message (string, function): A message to show if the assertion fails. #let all-of-type( t, ..values, message:(..a) => "Values need to be of type " + repr(a.pos().first()) + ". Got " + repr(a.pos().slice(1)) + " / " + repr(a.pos().slice(1).map(type)) ) = assert( values.pos().all((v) => alias.type(v) == t), message:lazy-message(message, t, ..values) ) /// Assert that none of the #arg[values] are of type #arg[t]. /// /// // Tests /// #assert.none-of-type("integer", "a", "b", false, 1.2) /// #assert.none-of-type("string", 1pt, 3%, true) /// /// - t (string): The type to test against. /// - ..values (any): Values to test. /// - message (string, function): A message to show if the assertion fails. #let none-of-type( t, ..values, message:(..a) => "Values may not be of type " + repr(a.pos().first()) + ". Got " + repr(a.pos().slice(1)) + " / " + repr(a.pos().slice(1).map(type)) ) = assert( values.pos().all((v) => alias.type(v) != t), message:lazy-message(message, t, ..values) ) /// Assert that #arg[value] is not _empty_. /// /// Depends on `is.empty()`. See there for an explanation /// of _empty_. /// /// // Tests /// #assert.not-empty("string") /// #assert.not-empty((1,)) /// #assert.not-empty((a:1)) /// /// - value (any): The value to test. /// - message (string, function): A message to show if the assertion fails. #let not-empty( value, message:(v, ..a) => { "Value may not be empty. Got " + repr(v) } ) = { assert( is.not-empty(value), message:lazy-message(message, value) ) } /// Assert that #arg[args] has positional arguments. /// /// If #arg[n] is a value greater zero, exactly #arg[n] /// positional arguments are required. Otherwise, at least /// one argument is required. /// #sourcecode[```typ /// #let add(..args) = { /// assert.has-pos(args) /// return args.pos().fold(0, (s, v) => s+v) /// } /// ```] /// /// // Tests /// #let func(n:none, ..args) = { /// assert.has-pos(n:n, args) /// } /// #func(..range(4)) /// #func(n:4, ..range(4)) /// /// - n (integer, none): The mandatory number of positional arguments or #value(none). /// - args (arguments): The arguments to test. /// - message (string,function): A message to show if the assertion fails. #let has-pos( n:none, args, message:(n:none, ..a) => { if n == none { "At least one positional argument required." } else { "Exactly " + str(n) +" positional arguments required, got " + repr(a.pos()) } } ) = { if n == none { assert.ne(args.pos(), (), message:lazy-message(message, n:n, ..args)) } else { assert.eq(args.pos().len(), n, message:lazy-message(message, n:n, ..args)) } } /// Assert that #arg[args] has no positional arguments. /// #sourcecode[```typ /// #let new-dict(..args) = { /// assert.no-pos(args) /// return args.named() /// } /// ```] /// /// // Tests /// #let func(..args) = { /// assert.no-pos(args) /// } /// #func(a:1, b:2) /// /// - args (arguments): The arguments to test. /// - message (string,function): A message to show if the assertion fails. #let no-pos( args, message:(..a) => "Unexpected positional arguments: " + repr(a) ) = { assert.eq(args.pos(), (), message:lazy-message(message, ..args.pos())) } /// Assert that #arg[args] has named arguments. /// /// If #arg[n] is a value greater zero, exactly #arg[n] /// named arguments are required. Otherwise, at least one /// argument is required. /// /// // Tests /// #let func(names:none, ..args) = { /// assert.has-named(names:names, args) /// } /// #func(a:1, b:2) /// #func(a:1, b:2, names:("a", "b")) /// #func(a:1, b:2, c:3, names:("a", "b")) /// /// - names (array, none): An array with required keys or #value(none). /// - strict (boolean): If #value(true), only keys in #arg[names] are allowed. /// - args (arguments): The arguments to test. /// - message (string, function): A message to show if the assertion fails. #let has-named( names:none, strict: false, args, message:(..a) => { let names = a.named().at("names", default:()) if names == () { "Missing named arguments." } else { let named = a.named() let keys = named.keys() names = names.filter((k) => k != "names" and k not in keys) "Missing named arguments: " + names.join(", ") } } ) = { if names == none { assert.ne(args.named(), (:), message:lazy-message(message, names:(), ..args)) } else { if type(names) != "array" { names = (names,) } let keys = args.named().keys() assert(names.all((v) => v in keys), message:lazy-message(message, names:names, ..args)) } } /// Assert that #arg[args] has no named arguments. /// /// // Tests /// #let func(..args) = { /// assert.no-named(args) /// } /// #func(..range(4)) /// /// - args (arguments): The arguments to test. /// - message (string,function): A message to show if the assertion fails. #let no-named( args, message:(..a) => "Unexpected named arguments: " + repr(a.named()) ) = { assert.eq(args.named(), (:), message:lazy-message(message, ..args)) } /// Creates a new assertion from `test`. /// /// The new assertion will take a any number of `values` and pass them to `test`. /// `test` should return a `boolean`. /// #sourcecode[```typ /// #let assert-numeric = assert.new(is.num) /// /// #let diameter(radius) = { /// assert-numeric(radius) /// return 2*radius /// } /// ```] /// /// // Tests /// #let assert-numeric = assert.new(is.num) /// #let diameter(radius) = { /// assert-numeric(radius) /// return 2*radius /// } /// #diameter(4.3) /// #diameter(2) /// /// - test (function): A test function: #lambda("..any", ret:true) #let new( test, message:"" ) = (..v, message:message) => assert(test(..v), message:lazy-message(message, ..v))
https://github.com/N4tus/uf_algo
https://raw.githubusercontent.com/N4tus/uf_algo/main/style.typ
typst
MIT License
#import "style_base.typ": elem, sp, join, gs, ge, if_string, if_string_else, if_number, if_number_else, pipe #let keyword(k) = elem(k, "keyword") #let kw_function(f) = elem(f, "keyword", "function") #let kw_operator(o) = elem(o, "keyword", "operator") #let kw_control(c) = elem(c, "keyword", "control") #let loop(c) = elem(c, "keyword", "control", "loop") #let condition(c) = elem(c, "keyword", "control", "condition") #let imp(c) = elem(c, "keyword", "control", "import") #let ret(c) = elem(c, "keyword", "control", "return") #let exception(c) = elem(c, "keyword", "control", "exception") #let directive(d) = elem(d, "keyword", "directive") #let type(t) = elem(t, "keyword", "type") #let ty_class(t) = elem(t, "keyword", "type", "class") #let ty_struct(t) = elem(t, "keyword", "type", "struct") #let ty_union(t) = elem(t, "keyword", "type", "union") #let ty_enum(t) = elem(t, "keyword", "type", "enum") #let ty_interface(t) = elem(t, "keyword", "type", "interface") #let variable(v) = elem(v, "variable") #let var_builtin(b) = elem(b, "variable", "builtin") #let var_this(b) = elem(b, "variable", "builtin", "this") #let var_parameter(p) = elem(p, "variable", "parameter") #let var_self(p) = elem(p, "variable", "parameter", "self") #let var_class(p) = elem(p, "variable", "parameter", "class") #let var_function(f) = elem(f, "variable", "function") #let var_fn_def(f) = elem(f, "variable", "function", "definition") #let var_ctor(f) = elem(f, "variable", "function", "constructor") #let var_dtor(f) = elem(f, "variable", "function", "destructor") #let var_attribute(a) = elem(a, "variable", "attribute") #let comment(c) = elem(c, "comment") #let comment_sym(c) = elem(c, "comment", "sym") #let comment_line(c) = elem(c, "comment", "line") #let comment_block(c) = elem(c, "comment", "block") #let comment_doc(c) = elem(c, "comment", "doc") #let string(s) = elem(s, "string") #let str_quote(q) = elem(q, "string", "quote") #let str_regex(s) = elem(s, "string", "regex") #let punct(p) = elem(p, "punct") #let punct_delimiter(d) = elem(d, "punct", "delimiter") #let punct_bracket(b) = elem(b, "punct", "bracket") #let punct_special(s) = elem(s, "punct", "special") #let operator(o) = elem(o, "operator") #let op_unary(o) = elem(o, "operator", "unary") #let op_binary(o) = elem(o, "operator", "binary") #let number(n) = elem(n, "number") #let num_float(f) = elem(f, "number", "float") #let num_int(i) = elem(i, "number", "int") #let num_length(f) = elem(f, "number", "length") #let label(l) = elem(l, "label")
https://github.com/matthiasbeyer/ttt
https://raw.githubusercontent.com/matthiasbeyer/ttt/master/example.typ
typst
MIT License
#import "ttt.typ": * #set text(lang: "en") #show: ttt.with( author: "<NAME>", class: [Computer Science], subject: [Trees], date: datetime(year: 2024, month: 03, day: 19), bibliography: bibliography("refs.bib"), ) = Text == External links `ttt` adds a small maroon circle to external (outgoing) links #link("https://github.com/matthiasbeyer/ttt")[like so]. This acts as a hint for the reader so that they know that a specific text is a hyperlink. This is far better than #underline[underlining a hyperlink] or making it a #text(fill: blue)[different color]. If you want to disable this behavior then you can do so by setting the concerning option to `false`: ```typst #show: ttt.with( external-link-circle: false ) ``` == Blockquotes `ttt` also exports a `blockquote` function which can be used to create blockquotes. The function has one argument: `body` of the type content and can be used like so: ```typst #blockquote[ A wizard is never late, <NAME>. Nor is he early. He arrives precisely when he means to. ] ``` The above code will render the following: #blockquote[ A wizard is never late, <NAME>. Nor is he early. He arrives precisely when he means to. -- Gandalf ] == Small- and all caps `ttt` also exports functions for styling text in small caps and uppercase, namely: `smallcaps` and `upper` respectively. These functions will overwrite the standard #link("https://typst.app/docs/reference/text/smallcaps/")[`smallcaps`] and #link("https://typst.app/docs/reference/text/upper/")[`upper`] functions that Typst itself provides. This behavior is intentional as the functions that `ttt` exports fit in better with the rest of the template's styling. Here is how Typst's own #std-smallcaps[smallcaps] and #std-upper[upper] look compared to the `ttt`'s variants:\ #hide[Here is how Typst's own ] #smallcaps[smallcaps] and #upper[upper] They both look similar, the only difference being that `ttt` uses more spacing between individual characters. If you prefer Typst's default spacing then you can still use it by prefixing `std-` to the functions: ```typst #std-smallcaps()``` and ```typst #std-upper()```. == Tables In order to increase the focus on table content, we minimize the table's borders by using thin gray lines instead of thick black ones. Additionally, we use small taps for the header row. Take a look at the table below: #let unit(u) = math.display(math.upright(u)) #let si-table = table( columns: 3, table.header[Quantity][Symbol][Unit], [length], [$l$], [#unit("m")], [mass], [$m$], [#unit("kg")], [time], [$t$], [#unit("s")], [electric current], [$I$], [#unit("A")], [temperature], [$T$], [#unit("K")], [amount of substance], [$n$], [#unit("mol")], [luminous intensity], [$I_v$], [#unit("cd")], ) #figure(caption: [`ttt`'s styling], si-table) For comparison, this is how the same table would look with Typst's default styling: #[ #set table(inset: 5pt, stroke: 1pt + black) #show table.cell.where(y: 0): it => { v(0.5em) h(0.5em) + it.body.text + h(0.5em) v(0.5em) } #figure(caption: [Typst's default styling], si-table) ] = Code #let snip(cap) = figure(caption: cap)[ ```rust fn main() { let user = ("Adrian", 38); println!("User {} is {} years old", user.0, user.1); // tuples within tuples let employee = (("Adrian", 38), "die Mobiliar"); println!("User {} is {} years old and works for {}", employee.0.0, employee.0.1, employee.1); } ``` ] Here is `code` looks: #snip("Code snippet") = Some text Now lets have some lorem. == Subheading #lorem(400)
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/basic/modulize-multi-files-doc.typ
typst
Apache License 2.0
#import "mod.typ": * #show: book.page.with(title: "多文件文档") 尽管本书提倡你尽可能将所有文档内容放在单个文件中,本书给出构建一个多文件文档的合理方案。 - 工作区中包含多个主文件 - 每个主文件可以`include`多个子文件 ``` typ/packages ├── util.typ └── util2.typ typ/templates ├── book-template.typ └── note-template.typ documents/ └── my-book/ ├── main.typ ├── mod.typ ├── part1/ │ ├── mod.typ │ └── chap1.typ └── part2/ ├── mod.typ ├── chap2.typ └── chap3.typ ``` === 工作区内的模板与库 使用绝对路径方便引入工作区内的模板与库: ```typ #import "/typ/templates/ebook.typ": project as ebook ``` === 主文件和主库文件 `main.typ`文件中仅仅包含模板配置与`include`多个子文件。 ```typ // 在mod.typ文件中: // #import "/typ/templates/ebook.typ": project as ebook #import "mod.typ": * #show: ebook.with(title: "My Book") #include "part1/chap1.typ" #include "part2/chap2.typ" #include "part2/chap3.typ" ``` 对于每个子文件,你可以都`import`一个主库文件`mod.typ`,以减少冗余。例如在`documents/my-book/part1/chap1.typ`中: ```typ #import "mod.typ": * ``` === 重导出文件 示例文件结构中的`mod.typ`与编写库时的`lib.typ`很类似,都重新导出了大量函数。例如当你希望同时在`chap2.typ`和`chap3.typ`中使用相似的函数时,你可以在`mod.typ`中原地实现该函数或者从外部库中重导出对应函数: ```typ #import "@preview/example:0.1.0": add // 或者原地实现`add` #let add(x, y) = x + y ``` 这时你可以同时在`chap2.typ`和`chap3.typ`中直接使用该`add`函数。 === 依赖管理 你可以不在`main.typ`或者`chap{N}.typ`文件中直接引入外部库,而在`my-book/mod.typ`中引入外部库。由于级联的`mod.typ`,相关函数会传递给每个`main.typ`或者`chap{N}.typ`使用。
https://github.com/flaribbit/typst-sdu-master-thesis
https://raw.githubusercontent.com/flaribbit/typst-sdu-master-thesis/master/demo.typ
typst
#import "template.typ": * #show: project.with( 分类号: [XXXXX.X], 密级: [公开], 学号: [200000000], 标题: [基于Typst的毕业论文模板], title: [Graduation Thesis Template Based on Typst], 日期: [2024年3月26日], 作者姓名: [Typst], 培养单位: [Typst], 专业名称: [Typst], 指导教师: [Typst], 合作导师: [Typst], 摘要: [Typst 是一门面向出版与学术写作的可编程标记语言。它于 2023 年 4 月正式开源,从 0.1.0 版本到现在的 0.9.0 版本,已经成熟稳定许多。Typst 提供了更好的中文与 CJK 语言支持,能够满足复杂的排版需求。相较于传统的 LaTeX 和简单的 Markdown,Typst 在使用体验上更加简单,无需引入大量宏包,语法也更加简洁。它支持自动处理中英文之间的空格、中文标点压缩,以及英文 kerning、alternates 和 ligatures。Typst 还内置了脚注、参考文献、数学公式字体更换等功能。你可以通过 Typst CLI 命令行工具或在 VS Code 中使用 Typst 插件来编辑,而且 Typst 的包管理器能够按需自动下载所需资源,保持安装简洁。未来,Typst有望与Web更紧密结合,成为出版领域的一股新势力。], 关键词: ("Typst", "毕业论文" ,"模板"), abstract: [Typst is a programmable markup language designed for publishing and academic writing. It was officially open-sourced in April 2023 and has matured significantly from version 0.1.0 to the current 0.9.0 release. Typst provides enhanced support for Chinese and CJK languages, catering to complex typesetting requirements. Compared to traditional LaTeX and simple Markdown, Typst offers a more straightforward user experience, eliminating the need for extensive macro packages, and its syntax is concise. It automatically handles spacing between Chinese and English, compresses Chinese punctuation, and supports English kerning, alternates, and ligatures. Typst also includes built-in features like footnotes, bibliography management, and font customization for mathematical formulas. You can edit documents using the Typst CLI command-line tool or the Typst extension in Visual Studio Code. Its package manager ensures minimal installation complexity by automatically downloading necessary resources. In the future, Typst aims to integrate more closely with the web and become a powerful force in the publishing domain.], keywords: ("Typst", "Thesis", "Template"), ) = 标题 #add-toc-en(level: 1)[Title] == 标题 #add-toc-en(level: 2)[Title] 引用参考文献@Crichton2024。 #placeholder(40) #placeholder(40) #figure2(rect[Hello], caption: [这是一张图片], caption-en: [This is a figure])<fig1> #placeholder(60) == 标题 #add-toc-en(level: 2)[Title] #placeholder(30) === 标题 #add-toc-en(level: 3)[Title] #placeholder(80) #figure2(rect[Hello], caption: [这是一张图片], caption-en: [This is a figure])<fig2> #placeholder(60) $ f(x)=e^x sin(x) $<eq1> #placeholder(20) $ f(x)=e^x sin(x) $<eq2> = 标题 #add-toc-en(level: 1)[Title] #figure2(rect[Hello], caption: [这是一张图片], caption-en: [This is a figure])<fig3> #figure2(rect[Hello], caption: [这是一张图片], caption-en: [This is a figure])<fig4> #table2(rect[Hello], caption: [这是一张表格], caption-en: [This is a table])<tab1> @fig1 @fig2 @eq1 @eq2 @tab1 #pagebreak() #add-toc-en(level: 1, numbered: false)[Reference] #bibliography("ref.bib")
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/grid/rowspan.typ
typst
--- grid-rowspan --- #grid( columns: 4, fill: (x, y) => if calc.odd(x + y) { blue.lighten(50%) } else { blue.lighten(10%) }, inset: 5pt, align: center, grid.cell(rowspan: 2, fill: orange)[*Left*], [Right A], [Right A], [Right A], [Right B], grid.cell(colspan: 2, rowspan: 2, fill: orange.darken(10%))[B Wide], [Left A], [Left A], [Left B], [Left B], grid.cell(colspan: 2, rowspan: 3, fill: orange)[Wide and Long] ) #table( columns: 4, fill: (x, y) => if calc.odd(x + y) { blue.lighten(50%) } else { blue.lighten(10%) }, inset: 5pt, align: center, table.cell(rowspan: 2, fill: orange)[*Left*], [Right A], [Right A], [Right A], [Right B], table.cell(colspan: 2, rowspan: 2, fill: orange.darken(10%))[B Wide], [Left A], [Left A], [Left B], [Left B], table.cell(colspan: 2, rowspan: 3, fill: orange)[Wide and Long] ) --- grid-rowspan-gutter --- #grid( columns: 4, fill: (x, y) => if calc.odd(x + y) { blue.lighten(50%) } else { blue.lighten(10%) }, inset: 5pt, align: center, gutter: 3pt, grid.cell(rowspan: 2, fill: orange)[*Left*], [Right A], [Right A], [Right A], [Right B], grid.cell(colspan: 2, rowspan: 2, fill: orange.darken(10%))[B Wide], [Left A], [Left A], [Left B], [Left B], grid.cell(colspan: 2, rowspan: 3, fill: orange)[Wide and Long] ) #table( columns: 4, fill: (x, y) => if calc.odd(x + y) { blue.lighten(50%) } else { blue.lighten(10%) }, inset: 5pt, align: center, gutter: 3pt, table.cell(rowspan: 2, fill: orange)[*Left*], [Right A], [Right A], [Right A], [Right B], table.cell(colspan: 2, rowspan: 2, fill: orange.darken(10%))[B Wide], [Left A], [Left A], [Left B], [Left B], table.cell(colspan: 2, rowspan: 3, fill: orange)[Wide and Long] ) --- grid-rowspan-fixed-size --- // Fixed-size rows #set page(height: 10em) #grid( columns: 2, rows: 1.5em, fill: (x, y) => if calc.odd(x + y) { blue.lighten(50%) } else { blue.lighten(10%) }, grid.cell(rowspan: 3)[R1], [b], [c], [d], [e], [f], grid.cell(rowspan: 5)[R2], [h], [i], [j], [k], [l], [m], [n] ) --- grid-rowspan-cell-coordinates --- // Cell coordinate tests #set page(height: 10em) #show table.cell: it => [(#it.x, #it.y)] #table( columns: 3, fill: red, [a], [b], table.cell(rowspan: 2)[c], table.cell(colspan: 2)[d], table.cell(colspan: 3, rowspan: 10)[a], table.cell(colspan: 2)[b], ) #table( columns: 3, gutter: 3pt, fill: red, [a], [b], table.cell(rowspan: 2)[c], table.cell(colspan: 2)[d], table.cell(colspan: 3, rowspan: 9)[a], table.cell(colspan: 2)[b], ) --- grid-rowspan-over-auto-row --- // Auto row expansion #set page(height: 10em) #grid( columns: (1em, 1em), rows: (0.5em, 0.5em, auto), fill: orange, gutter: 3pt, grid.cell(rowspan: 4, [x x x x] + place(bottom)[*Bot*]), [a], [b], [c], [d] ) --- grid-rowspan-excessive --- // Excessive rowspan (no gutter) #set page(height: 10em) #table( columns: 4, fill: red, [a], [b], table.cell(rowspan: 2)[c], [d], table.cell(colspan: 2, stroke: (bottom: aqua + 2pt))[e], table.cell(stroke: (bottom: aqua))[f], table.cell(colspan: 2, rowspan: 10)[R1], table.cell(colspan: 2, rowspan: 10)[R2], [b], ) --- grid-rowspan-excessive-gutter --- // Excessive rowspan (with gutter) #set page(height: 10em) #table( columns: 4, gutter: 3pt, fill: red, [a], [b], table.cell(rowspan: 2)[c], [d], table.cell(colspan: 2, stroke: (bottom: aqua + 2pt))[e], table.cell(stroke: (bottom: aqua))[f], table.cell(colspan: 2, rowspan: 10)[R1], table.cell(colspan: 2, rowspan: 10)[R2], [b], ) --- grid-rowspan-over-fr-row-at-end --- // Fractional rows // They cause the auto row to expand more than needed. #set page(height: 10em) #grid( fill: red, gutter: 3pt, columns: 3, rows: (1em, auto, 1fr), [a], [b], grid.cell(rowspan: 3, block(height: 4em, width: 1em, fill: orange)), [c], [d], [e], [f] ) --- grid-rowspan-over-fr-row-at-start --- // Fractional rows #set page(height: 10em) #grid( fill: red, gutter: 3pt, columns: 3, rows: (1fr, auto, 1em), [a], [b], grid.cell(rowspan: 3, block(height: 4em, width: 1em, fill: orange)), [c], [d], [e], [f] ) --- grid-rowspan-cell-order --- // Cell order #let count = counter("count") #show grid.cell: it => { count.step() context count.display() } #grid( columns: (2em,) * 3, stroke: aqua, rows: 1.2em, fill: (x, y) => if calc.odd(x + y) { red } else { orange }, [a], grid.cell(rowspan: 2)[b], grid.cell(rowspan: 2)[c], [d], grid.cell(rowspan: 2)[f], [g], [h], [i], [j], [k], [l], [m], grid.cell(rowspan: 2)[n], [o], [p], [q], [r], [s], [t], [u] ) --- grid-rowspan-unbreakable-1 --- #table( columns: 3, rows: (auto, auto, auto, 2em), gutter: 3pt, table.cell(rowspan: 4)[a \ b\ c\ d\ e], [c], [d], [e], table.cell(breakable: false, rowspan: 2)[f], [g] ) --- grid-rowspan-unbreakable-2 --- // Test cell breakability #show grid.cell: it => { test(it.breakable, (it.x, it.y) != (0, 6) and (it.y in (2, 5, 6) or (it.x, it.y) in ((0, 1), (2, 3), (1, 7)))) it.breakable } #grid( columns: 3, rows: (6pt, 1fr, auto, 1%, 1em, auto, auto, 0.2in), row-gutter: (0pt, 0pt, 0pt, auto), [a], [b], [c], grid.cell(rowspan: 3)[d], [e], [f], [g], [h], [i], grid.cell(rowspan: 2)[j], [k], grid.cell(y: 5)[l], grid.cell(y: 6, breakable: false)[m], grid.cell(y: 6, breakable: true)[n], grid.cell(y: 7, breakable: false)[o], grid.cell(y: 7, breakable: true)[p], grid.cell(y: 7, breakable: auto)[q] ) --- grid-rowspan-in-all-columns-stroke --- #table( columns: 2, table.cell(stroke: (bottom: red))[a], [b], table.hline(stroke: green), table.cell(stroke: (top: yellow, left: green, right: aqua, bottom: blue), colspan: 1, rowspan: 2)[d], table.cell(colspan: 1, rowspan: 2)[e], [f], [g] ) --- grid-rowspan-in-all-columns-stroke-gutter --- #table( columns: 2, gutter: 3pt, table.cell(stroke: (bottom: red))[a], [b], table.hline(stroke: green), table.cell(stroke: (top: yellow, left: green, right: aqua, bottom: blue), colspan: 1, rowspan: 2)[d], table.cell(colspan: 1, rowspan: 2)[e], [f], [g] ) --- grid-rowspan-block-full-height --- // Block below shouldn't expand to the end of the page, but stay within its // rows' boundaries. #set page(height: 9em) #table( rows: (1em, 1em, 1fr, 1fr, auto), table.cell(rowspan: 2, block(width: 2em, height: 100%, fill: red)), table.cell(rowspan: 2, block(width: 2em, height: 100%, fill: red)), [a] ) --- grid-rowspan-block-overflow --- #set page(height: 7em) #table( columns: 3, [], [], table.cell(breakable: true, rowspan: 2, block(width: 2em, height: 100%, fill: red)), table.cell(breakable: false, block(width: 2em, height: 100%, fill: red)), table.cell(breakable: false, rowspan: 2, block(width: 2em, height: 100%, fill: red)), ) // Rowspan split tests --- grid-rowspan-split-1 --- #set page(height: 10em) #table( columns: 2, rows: (auto, auto, 3em), fill: red, [a], table.cell(rowspan: 3, block(width: 50%, height: 10em, fill: orange) + place(bottom)[*ZD*]), [e], [f] ) --- grid-rowspan-split-2 --- #set page(height: 10em) #table( columns: 2, rows: (auto, auto, 3em), row-gutter: 1em, fill: red, [a], table.cell(rowspan: 3, block(width: 50%, height: 10em, fill: orange) + place(bottom)[*ZD*]), [e], [f] ) --- grid-rowspan-split-3 --- #set page(height: 5em) #table( columns: 2, fill: red, inset: 0pt, table.cell(fill: orange, rowspan: 10, place(bottom)[*Z*] + [x\ ] * 10 + place(bottom)[*ZZ*]), ..([y],) * 10, [a], [b], ) --- grid-rowspan-split-4 --- #set page(height: 5em) #table( columns: 2, fill: red, inset: 0pt, gutter: 2pt, table.cell(fill: orange, rowspan: 10, place(bottom)[*Z*] + [x\ ] * 10 + place(bottom)[*ZZ*]), ..([y],) * 10, [a], [b], ) --- grid-rowspan-split-5 --- #set page(height: 5em) #table( columns: 2, fill: red, inset: 0pt, table.cell(fill: orange, rowspan: 10, breakable: false, place(bottom)[*Z*] + [x\ ] * 10 + place(bottom)[*ZZ*]), ..([y],) * 10, [a], [b], ) --- grid-rowspan-split-6 --- #set page(height: 5em) #table( columns: 2, fill: red, inset: 0pt, gutter: 2pt, table.cell(fill: orange, rowspan: 10, breakable: false, place(bottom)[*Z*] + [x\ ] * 10 + place(bottom)[*ZZ*]), ..([y],) * 10, [a], [b], ) --- grid-rowspan-split-7 --- #set page(height: 5em) #grid( columns: 2, stroke: red, inset: 5pt, grid.cell(rowspan: 5)[a\ b\ c\ d\ e] ) --- grid-rowspan-split-8 --- #set page(height: 5em) #table( columns: 2, gutter: 3pt, stroke: red, inset: 5pt, table.cell(rowspan: 5)[a\ b\ c\ d\ e] ) // Rowspan split without ending at the auto row --- grid-rowspan-split-9 --- #set page(height: 6em) #table( rows: (4em,) * 7 + (auto,) + (4em,) * 7, columns: 2, column-gutter: 1em, row-gutter: (1em, 2em) * 4, fill: (x, y) => if calc.odd(x + y) { orange.lighten(20%) } else { red }, table.cell(rowspan: 15, [a \ ] * 15), [] * 15 ) --- grid-rowspan-split-10 --- #set page(height: 6em) #table( rows: (4em,) * 7 + (auto,) + (4em,) * 7, columns: 2, column-gutter: 1em, row-gutter: (1em, 2em) * 4, fill: (x, y) => if calc.odd(x + y) { green } else { green.darken(40%) }, table.cell(rowspan: 15, block(fill: blue, width: 2em, height: 4em * 14 + 3em)), [] * 15 ) --- grid-rowspan-split-11 --- #set page(height: 6em) #table( rows: (3em,) * 15, columns: 2, column-gutter: 1em, row-gutter: (1em, 2em) * 4, fill: (x, y) => if calc.odd(x + y) { aqua } else { blue }, table.cell(breakable: true, rowspan: 15, [a \ ] * 15), [] * 15 ) // Some splitting corner cases --- grid-rowspan-split-12 --- // Inside the larger rowspan's range, there's an unbreakable rowspan and a // breakable rowspan. This should work normally. // The auto row will also expand ignoring the last fractional row. #set page(height: 10em) #table( gutter: 0.5em, columns: 2, rows: (2em,) * 10 + (auto, auto, 2em, 1fr), fill: (_, y) => if calc.even(y) { aqua } else { blue }, table.cell(rowspan: 14, block(width: 2em, height: 2em * 10 + 2em + 5em, fill: red)[]), ..([a],) * 5, table.cell(rowspan: 3)[a\ b], table.cell(rowspan: 5, [a\ b\ c\ d\ e\ f\ g\ h]), [z] ) --- grid-rowspan-split-13 --- // Inset moving to next region bug #set page(width: 10cm, height: 2.5cm, margin: 0.5cm) #set text(size: 11pt) #table( columns: (1fr, 1fr, 1fr), [A], [B], [C], [D], table.cell(rowspan: 2, lorem(4)), [E], [F], [G], ) --- grid-rowspan-split-14 --- // Second lorem must be sent to the next page, too big #set page(width: 10cm, height: 9cm, margin: 1cm) #set text(size: 11pt) #table( columns: (1fr, 1fr, 1fr), align: center, rows: (4cm, auto), [A], [B], [C], table.cell(rowspan: 4, breakable: false, lorem(10)), [D], table.cell(rowspan: 2, breakable: false, lorem(20)), [E], ) --- grid-rowspan-split-15 --- // Auto row must expand properly in both cases #set text(10pt) #show table.cell: it => if it.x == 0 { it } else { layout(size => size.height) } #table( columns: 2, rows: (1em, auto, 2em, 3em, 4em), gutter: 3pt, table.cell(rowspan: 5, block(fill: orange, height: 15em)[a]), [b], [c], [d], [e], [f] ) #table( columns: 2, rows: (1em, auto, 2em, 3em, 4em), gutter: 3pt, table.cell(rowspan: 5, breakable: false, block(fill: orange, height: 15em)[a]), [b], [c], [d], [e], [f] ) --- grid-rowspan-split-16 --- // Expanding on unbreakable auto row #set page(height: 7em, margin: (bottom: 2em)) #grid( columns: 2, rows: (1em, 1em, auto, 1em, 1em, 1em), fill: (x, y) => if x == 0 { aqua } else { blue }, stroke: black, gutter: 2pt, grid.cell(rowspan: 5, block(height: 10em)[a]), [a], [b], grid.cell(breakable: false, v(3em) + [c]), [d], [e], [f], [g] ) --- grid-rowspan-split-17 --- #show table.cell.where(x: 0): strong #show table.cell.where(y: 0): strong #set page(height: 13em) #let lets-repeat(thing, n) = ((thing + colbreak(),) * (calc.max(0, n - 1)) + (thing,)).join() #table( columns: 4, fill: (x, y) => if x == 0 or y == 0 { gray }, [], [Test 1], [Test 2], [Test 3], table.cell(rowspan: 15, align: horizon, lets-repeat((rotate(-90deg, reflow: true)[*All Tests*]), 3)), ..([123], [456], [789]) * 15 )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/tuhi-labscript-vuw/0.1.0/tuhi-labscript-vuw.typ
typst
Apache License 2.0
#let darkgrey = rgb(29, 27, 28) #let darkgreen = rgb(0,81,55) #let middlegreen = rgb(113, 135, 121) #let lightgreen = rgb(206,220,215) #let tuhi-labscript-vuw( experiment: text[murphy's l\ aws -- an investigation], script: "pre-lab script", coursetitle: "experimental physics ii", coursecode: "phys345", date: datetime(year: 2024,month: 7, day: 3), trimester: "2", illustration: none, body) = { // Set the document's basic properties. set document( author: coursecode, title: coursetitle, keywords: ("lab script"), date: date) set page(width: 210mm, height:297mm, margin:1.72cm, background: none, numbering: (num, total) => [#num / #total], footer: [ #set align(center) #set text(10pt, number-type: "old-style") #grid(columns: (1fr,1fr,1fr), { set text(tracking: 0.5pt) show text: it => smallcaps(lower(it)) align(left)[#date.display("[year] · ")#text[T#trimester]] }, [#counter(page).display((num, total) => [#set text(number-type: "lining") #num ⁄ #total], both: true)], [#h(1fr)#smallcaps[#coursecode.match(regex("([a-zA-Z]+)([0-9]+)")).captures.join(" ")]]) // adding hair space ],) set text(font: "Fira Sans", size: 12pt, weight: 400, fill: luma(50), number-type: "old-style", lang: "en", ) show raw: set text(font: "Fira Code", size: 11pt, weight: 500, tracking: -0.1pt) show math.equation: set text(font: "Fira Math", weight: 400) set par(justify: true) show heading.where(level: 1): it => {set text(font: "Fira Sans", fill: darkgrey, weight: 500, alternates: true, tracking: 0.5pt, number-type: "old-style") smallcaps(lower(it)) v(1em)} show heading.where(level: 2): it => {set text(font: "Fira Sans", fill: darkgreen, weight: 400, number-type: "old-style", tracking: 0.1pt) smallcaps(lower(it)) v(0.4em)} // opening page v(1.5cm) align(top + left)[ #set text(font: "Source Sans Pro", size: 48pt, weight: "extralight", fill: darkgreen) #set par(leading: 12pt) #smallcaps[#lower[#experiment]]#v(1cm,weak: true)#smallcaps[#text(size:22pt,weight: 100,fill:darkgreen)[›› ]#text(size:22pt,weight: 400, fill: darkgrey)[#script]] #v(1.5cm,weak: true) #illustration#v(2cm,weak: true) ] // Main body body }
https://github.com/exAClior/touying-simpl-hkustgz
https://raw.githubusercontent.com/exAClior/touying-simpl-hkustgz/master/template/main.typ
typst
MIT License
#import "@preview/touying:0.4.2": * #import "@preview/touying-hkustgz:0.1.0" as hkustgz-theme #let s = hkustgz-theme.register() // Global information configuration #let s = (s.methods.info)( self: s, title: [Touying for HKUSTGZ: Customize Your Slide Title Here], subtitle: [Customize Your Slide Subtitle Here], author: [Authors], date: datetime.today(), institution: [HKUST(GZ)], ) // Extract methods #let (init, slides) = utils.methods(s) #show: init // Extract slide functions #let (slide, empty-slide, title-slide, outline-slide, new-section-slide, ending-slide) = utils.slides(s) #show: slides.with() #outline-slide() = The section I == Slide I / i Slide content. == Slide I / ii Slide content. = The section II == Slide II / i Slide content. == Slide II / ii Slide content.
https://github.com/Maso03/Bachelor
https://raw.githubusercontent.com/Maso03/Bachelor/main/Bachelorarbeit/chapters/grundlagen.typ
typst
MIT License
= Grundlagen == Einführung in Künstliche Intelligenz (KI) Künstliche Intelligenz (KI) bezeichnet den Bereich der Informatik, der sich mit der Schaffung von Systemen befasst, die in der Lage sind, Aufgaben zu erledigen, die normalerweise menschliche Intelligenz erfordern @KI. Dazu gehören Fähigkeiten wie Lernen, Problemlösung, Mustererkennung und Sprachverarbeitung. Die KI kann in verschiedene Kategorien eingeteilt werden, darunter schwache KI, die auf spezifische Aufgaben spezialisiert ist, und starke KI, die über allgemeine menschliche Intelligenz hinausgeht @KI-Statista2. === Historische Entwicklung Die Entwicklung der Künstlichen Intelligenz (KI) begann Mitte des 20. Jahrhunderts mit Algorithmen, die nicht mehr auf festen Regeln basierten, sondern durch Wiederholungen selbstständig lernten, Probleme zu lösen. Diese Innovation ermöglichte es, Aufgaben anzugehen, deren Lösungswege nicht durch klare Regeln vorgegeben waren. Ein bedeutendes Beispiel hierfür sind neuronale Netze. Diese Modelle sind dem menschlichen Gehirn nachempfunden und bestehen aus Schichten und Parametern, die zahlreiche Verbindungen abbilden. Durch Training mit Daten können neuronale Netze anschließend auch auf unbekannten Daten zu gewünschten Schlussfolgerungen kommen @BMFW. Den Grundstein für die Künstliche Intelligenz legte der britische Mathematiker Alan Turing mit seiner Theorie der Turingmaschine im Jahr 1936. Turing stellte die Frage, ob Maschinen denken können, und formulierte das nach ihm benannte Turing-Test-Kriterium. Dieses besagt, dass eine Maschine dann als intelligent gilt, wenn sie in einem Gespräch nicht von einem Menschen unterschieden werden kann. In den folgenden Jahrzehnten wurden zahlreiche KI-Technologien entwickelt, die heute in vielen Anwendungen zum Einsatz kommen @KI-Statista2. Der erste Chatbot ELIZA, entwickelt von <NAME> in den 1960er Jahren, war ein Meilenstein in der Geschichte der KI. ELIZA konnte einfache Konversationen führen und den Eindruck erwecken, ein menschlicher Gesprächspartner zu sein. Im Jahre 1986 wurde mit "NETtalk", das erste neuronale Netzwerk zur Spracherkennung entwickelt. NETtalk konnte Buchstaben in gesprochene Wörter umwandeln und war ein Schritt in der Entwicklung von Spracherkennungssystemen. Die Schachmaschine Deep Blue von IBM schlug 1997 den amtierenden Schachweltmeister <NAME> und zeigte erstmals die Überlegenheit von KI-Systemen in komplexen Spielen. Mit der Entwicklung von Deep Learning-Technologien wie "Convolutional Neural Networks" (CNNs) und "Recurrent Neural Networks" (RNNs) in den 2010er Jahren wurden große Fortschritte in der Bild- und Spracherkennung erzielt. Diese Technologien sind heute in vielen Anwendungen wie Gesichtserkennung, Sprachassistenten und autonomen Fahrzeugen verbreitet. Heutzutage verwenden KI-Modelle den selben Aufbau, indem ein Neuronales Netzwerk mit vielen Schichten (Deep Learning) trainiert wird. Diese Modelle können komplexe Muster in Daten erkennen und für Vorhersagen und Klassifizierungen genutzt werden. === Maschinelles Lernen und Deep Learning KI-Systeme werden durch ein Künstliches Neuronales Netz (KNN) realisiert, das auf dem Prinzip des maschinellen Lernens basiert. Maschinelles Lernen ist ein Teilgebiet der KI, das sich mit der Entwicklung von Algorithmen befasst, die es Computern ermöglichen, aus Daten zu lernen und Vorhersagen zu treffen. Dabei werden die Algorithmen so trainiert, dass sie Muster in den Daten erkennen und diese Muster auf neue Daten anwenden können. Maschinelles Lernen kann in verschiedene Kategorien unterteilt werden, darunter überwachtes Lernen, unüberwachtes Lernen und verstärkendes Lernen. Ein Neuronales Netz besteht aus mehreren Schichten von künstlichen Neuronen, die miteinander verbunden sind und Informationen verarbeiten. Die Neuronen in einem Neuronalen Netzwerk sind durch Gewichte und Aktivierungsfunktionen miteinander verbunden. Durch das Training des Netzwerks werden die Gewichte so angepasst, dass das Netzwerk die gewünschten Ausgaben erzeugt. Deep Learning ist eine spezielle Form des maschinellen Lernens, bei der tiefe neuronale Netzwerke mit vielen Schichten verwendet werden. Diese Netzwerke sind in der Lage, komplexe Muster in den Daten zu erkennen und hochdimensionale Daten zu verarbeiten. Die erste Layer wird dabei als Input-Layer bezeichnet, die letzte als Output-Layer und alle dazwischen als Hidden-Layer. Die Anzahl der Hidden-Layer bestimmt die Tiefe des Netzwerks. Die Aktivierungsfunktionen in den Neuronen sorgen dafür, dass das Netzwerk nichtlinear arbeiten kann und komplexe Muster in den Daten erkennen kann. Die Gewichte in den Verbindungen zwischen den Neuronen werden durch das Training des Netzwerks so angepasst, dass das Netzwerk die gewünschten Ausgaben erzeugt. Deep Learning-Modelle können auf große Datenmengen trainiert werden und sind in der Lage, hochdimensionale Daten zu verarbeiten. === Funktionsweise von KI Nachdem die Grundlagen von KI und maschinellem Lernen erläutert wurden, soll nun die Funktionsweise von KI-Systemen genauer betrachtet werden. KI basiert auf Algorithmen und Modellen, die es Computern ermöglichen, Muster in Daten zu erkennen und daraus Schlussfolgerungen zu ziehen. Die Funktionsweise von KI-Systemen kann in drei Schritten beschrieben werden. Um die KI-Modelle zu trainieren und anzuwenden, sind folgende Schritte erforderlich: 1. *Datenerfassung und -vorbereitung:* KI-Modelle benötigen große Mengen an Daten, um zu lernen und Muster zu erkennen. Diese Daten werden gesammelt, bereinigt und in einem geeigneten Format für das Training des Modells vorbereitet. Als Beispiel können Bilder mit den entsprechenden Klassen (z. B. Katze oder Hund) versehen werden, um ein Modell zur Bilderkennung zu trainieren. 2. *Training des Modells:* Das KI-Modell wird mit den vorbereiteten Daten trainiert, um Muster und Zusammenhänge zu erkennen. Dies geschieht durch Anpassung der Modellparameter an die Daten, um die Genauigkeit der Vorhersagen zu verbessern. Beim Training eines neuronalen Netzwerks werden die Gewichte in den Verbindungen zwischen den Neuronen so angepasst, dass das Netzwerk die gewünschten Ausgaben erzeugt. 3. *Anwendung des Modells:* Nach dem Training kann das KI-Modell auf neue Daten angewendet werden, um Vorhersagen zu treffen oder Aufgaben zu erledigen. Je nach Anwendungsgebiet kann das Modell in Echtzeit oder im Batch-Modus betrieben werden. Beispielsweise kann ein KI-Modell zur Spracherkennung in Echtzeit gesprochene Wörter in Text umwandeln. Wenn ein falsches Ergebnis beim Output-Layer des neuronalen Netzwerks erzeugt wird, wird die KI entweder durch "Penalties" (Bestrafungen) oder durch Anpassung der Gewichte im Netzwerk trainiert. Dieser Prozess wird iterativ durchgeführt, bis das Modell die gewünschte Genauigkeit erreicht hat. === Künstliche Intelligenz in der Wirtschaft Künstliche Intelligenz (KI) hat sich in den letzten Jahren zu einem unverzichtbaren Werkzeug in vielen Branchen entwickelt und wird bereits in verschiedenen Bereichen wie Entwicklung, Produktion und Verwaltung eingesetzt. Laut <NAME> sind 69 % der deutschen Unternehmen der Meinung, dass KI die wichtigste Zukunftstechnologie darstellt @KI-Wirtschaft. === Anwendungsgebiete von KI *Bilderkennung und NLP:* Eine der bekanntesten Anwendungen von KI ist die Bilderkennung, die in vielen Bereichen von der Sicherheitsüberwachung bis zur medizinischen Bildanalyse genutzt wird. KI-gestützte Systeme können Bilddaten analysieren und Muster erkennen, die für menschliche Augen schwer zu identifizieren sind. Ein weiteres bedeutendes Anwendungsgebiet ist die Analyse von Texten und gesprochenem Wort, bekannt als Natural Language Processing (NLP). NLP-Technologien ermöglichen es Computern, menschliche Sprache zu verstehen, zu interpretieren und darauf zu reagieren. Dies wird in Chatbots, Sprachassistenten und Übersetzungsdiensten verwendet. *Medizinische Anwendungen:* In der Medizin wird KI genutzt, um Diagnosen zu verbessern und Behandlungen zu optimieren. Beispielsweise können KI-Modelle Tumorzellen auf digitalisierten Gewebeschnitten erkennen und klassifizieren. Ein Durchbruch in diesem Bereich ist AlphaFold2, das präzise Vorhersagen der Proteinstruktur ermöglicht und somit die Forschung und Entwicklung neuer Medikamente beschleunigt @AlphaFold. *Predictive Maintenance:* Ein weiteres wichtiges Anwendungsgebiet von KI ist die prädiktive Wartung (Predictive Maintenance). Hierbei werden KI-Modelle eingesetzt, um den Zustand von Maschinen zu überwachen und den Verschleiß von Bauteilen vorherzusagen. Dies ermöglicht es Unternehmen, Wartungsarbeiten effizienter zu planen und Ausfallzeiten zu minimieren. Durch die frühzeitige Erkennung von Problemen können kostspielige Reparaturen vermieden und die Lebensdauer der Maschinen verlängert werden. *Sprachgesteuerte Systeme:* Sprachgesteuerte Systeme finden in vielen Produktionsumfeldern Anwendung, wo sie die Bedienung von Maschinen und Anlagen erleichtern. Diese Systeme ermöglichen es den Mitarbeitern, durch einfache Sprachbefehle komplexe Aufgaben zu steuern, was die Effizienz und Sicherheit in der Produktion erhöht. Die Integration von KI in Geschäftsprozesse bietet erhebliche Vorteile in Bezug auf Effizienz, Genauigkeit und Kostenersparnis. Unternehmen können durch den Einsatz von KI-Technologien ihre Produktionsprozesse optimieren, innovative Produkte und Dienstleistungen entwickeln und letztlich ihre Wettbewerbsfähigkeit steigern. In dieser bachelorarbeit werden die Sprachgesteuerten Systeme und die Bilderkennung im Vordergrund stehen, um die Entwicklung eines 3D-Avatars zu realisieren. === Bedeutung und Wirtschaftliche Auswirkungen der Künstlichen Intelligenz Künstliche Intelligenz (KI) hat das Potenzial, tiefgreifende wirtschaftliche Veränderungen herbeizuführen und bietet enorme Chancen für Unternehmen und Volkswirtschaften. KI-basierte Lösungen könnten im produzierenden Gewerbe ein zusätzliches Wertschöpfungspotenzial von 30 Milliarden Euro ermöglichen. Es wird prognostiziert, dass das deutsche Bruttoinlandsprodukt durch den Einsatz von KI bis zum Jahr 2030 um 11,3 % steigen wird @KI-Statista2 @BMFW. Der Einsatz von KI-Technologien in der Wirtschaft hat in den letzten Jahren deutlich zugenommen. Unternehmen weltweit implementieren KI, um ihre Geschäftsprozesse zu optimieren, Effizienz zu steigern und Wettbewerbsvorteile zu sichern. Besonders häufig finden Robotic Process Automation (RPA), Natural Language Understanding und Computer Vision Anwendung. Diese Technologien sind besonders in der Finanz- und Automobilbranche sowie im Gesundheitssektor präsent @KI-Statista2. Private Investitionen in KI sind seit 2013 beträchtlich gestiegen, insbesondere in den USA, wo Unternehmen wie Apple führend sind. China hat sich das Ziel gesetzt, bis 2030 weltweit führend im Bereich KI zu sein und hat seine Investitionen entsprechend erhöht @KI-Statista2 @BMFW. Die wirtschaftlichen Auswirkungen von KI sind weitreichend und vielversprechend. Unternehmen und Volkswirtschaften, die in KI investieren und diese Technologien effektiv integrieren, können erhebliche Wettbewerbsvorteile erzielen. Während Deutschland und andere Länder daran arbeiten, die Potenziale von KI vollständig zu nutzen, bleibt die Balance zwischen technologischer Innovation und ethischen sowie rechtlichen Herausforderungen eine zentrale Aufgabe @KI-Statista2 @KI-Unternehmen2. === Herausforderungen Trotz des Potenzials von KI stehen Unternehmen vor mehreren Herausforderungen @BMFW: 1. *Fachwissen und Domänenwissen*: Reines Expertenwissen im Bereich KI ist für den erfolgreichen Einsatz in der Regel nicht ausreichend. Es muss mit Domänenwissen aus dem jeweiligen Anwendungsbereich kombiniert werden. Oft verfügen anwendende Unternehmen nicht über das notwendige maschinelle Lernwissen, während KI-Entwickelnde häufig das spezifische Domänenwissen fehlt. 2. *Datenqualität und Bias*: Die Qualität der Ergebnisse eines KI-Modells hängt stark von den Daten ab, die für das Training genutzt werden. Ein Ungleichgewicht in den Daten (Bias) kann zu unerwarteten und falschen Ergebnissen führen. Es ist wichtig, einen derartigen Bias frühzeitig zu identifizieren und zu beseitigen. 3. *Nachvollziehbarkeit und Erklärbarkeit*: KI-Modelle sind oft schwer nachvollziehbar. Selbst Experten können aufgrund der Komplexität nicht immer die Gründe für Entscheidungen nennen. Erklärungswerkzeuge können helfen, Modelle nachvollziehbarer zu gestalten und die Entscheidungsgrundlage zu plausibilisieren. 4. *Gesellschaftliche Akzeptanz*: Die Akzeptanz von KI-Algorithmen stellt eine gesellschaftliche Herausforderung dar. Viele Menschen sind skeptisch gegenüber KI, insbesondere weil die Modelle nicht immer nachvollziehbar sind. Es ist wichtig, dieser Besorgnis gezielt zu begegnen, um die Potenziale von KI in verschiedenen Wirtschaftsbereichen zu heben @KI-Statista. === Fazit Künstliche Intelligenz (KI) hat sich in den letzten Jahrzehnten von einer theoretischen Idee zu einer Schlüsseltechnologie entwickelt, die die momentane Wirtschaft und Gesellschaft prägt. Durch die ständige Verbesserung von KI-Modellen, beziehungsweise den Algorithmen und Neuronalen Netzen, setzen Unternehmen KI-Technologien in der Entwicklung, Produktion und Verwaltung ein, um die Effizienz und Produktivität zu steigern. Beispielsweise erleichtern sprachgesteuerte Systeme die Bedienung im Produktionsumfeld, und KI-Modelle wie AlphaFold2 revolutionieren die medizinische Forschung und Diagnose. Unternehmen stehen vor der Herausforderung, das Potenzial von KI vollständig zu nutzen, die Qualität der Daten zu gewährleisten und gleichzeitig ethische und rechtliche Aspekte zu berücksichtigen, um Akzeptanz in der Gesellschaft zu finden. Ein wichtiger Aspekt dieser Bachelorarbeit ist die Entwicklung eines interaktiven 3D-Avatars, der durch den Einsatz von Sprachsteuerung und Bilderkennung eine benutzerfreundliche Schnittstelle für Softwareeinführungen und Schulungen bietet. Dieser Avatar nutzt die Fähigkeiten von Generativer Intelligenz (GenAI), um personalisierte und dynamische Interaktionen zu ermöglichen, die über herkömmliche Mensch-Maschine-Schnittstellen hinausgehen. Solche interaktiven KI-Systeme können die Benutzererfahrung erheblich verbessern, indem sie komplexe Anleitungen intuitiv und verständlich vermitteln. Die Grundlagen der Künstlichen Intelligenz und des maschinellen Lernens bilden das Fundament für die Entwicklung des 3D-Avatars und werden in den folgenden Kapiteln weiter vertieft und angewendet.
https://github.com/Andres-AM/CV_typst
https://raw.githubusercontent.com/Andres-AM/CV_typst/main/README.md
markdown
Personal CV using typst based on modern CV
https://github.com/crd2333/Astro_typst_notebook
https://raw.githubusercontent.com/crd2333/Astro_typst_notebook/main/src/components/TypstTemplate/lib.typ
typst
#import "fonts.typ": * #import "utils.typ": * #import "math.typ": * #import "figures.typ": * #let project( title: "", lang: "zh", show_toc: true, toc_break: true, toc_depth: 4, body ) = { set document(title: title,) set page( paper: "a4", height: auto, margin: (x: 2cm, y: 1.5cm), ) // 导入 show 规则 show: setup-lovelace show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em) show: shorthand // 导入 math shorthand show: codly-init.with() // 行间公式、原始文本与文字之间的自动空格 show raw.where(block: false): it => h(0.25em, weak: true) + it + h(0.25em, weak: true) show math.equation.where(block: false): it => h(0.25em, weak: true) + it + h(0.25em, weak: true) // 矩阵用方括号显示 set math.mat(delim: "[") set math.vec(delim: "[") // 引用与链接字体蓝色显示 show ref: set text(colors.blue) show link: set text(colors.blue) // 设置字体与语言 set text(font: 字体.宋体, size: 字号.小四, lang: lang) set par(first-line-indent: 2em) set list(marker: ([●], [○], [■], [□], [►])) // 设置 bullet list 的 marker,相比默认更像 markdown,另外刻意调大了一点(适合老年人 set enum(numbering: numbly("{1}.", "{2:a}.", "{3:i}."), full: true) show emph: text.with(font: 字体.楷体) // 中文斜体显示为楷体 // 设置标题 show heading.where(level: 1): it => { set block(spacing: 1em) align(center, text(weight: "bold", font: 字体.黑体, size: 18pt, it)) } show heading.where(level: 2): set text(weight: "bold", font: 字体.黑体, size: 17pt) show heading.where(level: 3): set text(weight: "bold", font: 字体.黑体, size: 16pt) show heading.where(level: 4): set text(weight: "bold", font: 字体.黑体, size: 15pt) show heading.where(level: 5): set text(weight: "bold", font: 字体.黑体, size: 14pt) set heading(numbering: (..nums) => { // 设置标题编号 nums.pos().map(str).join(".") + " " }) // 代码相关设置 codly( languages: ( c: (name: "", icon: h(2pt)+c_svg, color: rgb("#A8B9CC")), C: (name: "", icon: h(2pt)+c_svg, color: rgb("#A8B9CC")), cpp: (name: "Cpp", icon: cpp_svg, color: rgb("#00599C")), Cpp: (name: "Cpp", icon: cpp_svg, color: rgb("#00599C")), py: (name: "Python", icon: python_svg, color: rgb(("#3D8FD1"))), python: (name: "Python", icon: python_svg, color: rgb(("#3D8FD1"))), rust: (name: "Rust", icon: rust_svg, color: rgb("#CE412B")), java: (name: "Java", icon: java_svg, color: rgb("#5382A1")), typ: (name: "Typst", icon: typst_svg, color: rgb("#FFD700")), sql: (name: "SQL", icon: sql_svg, color: rgb("#F0A103")), SQL: (name: "SQL", icon: sql_svg, color: rgb("#F0A103")), verilog: (name: "Verilog", icon: verilog_svg, color: rgb("#FF6666")), Verilog: (name: "Verilog", icon: verilog_svg, color: rgb("#FF6666")), ), zebra-color: luma(250), fill: luma(250), // stroke-width: 1pt, // display-name: false, // display-icon: false ) // 行内代码,灰色背景 show raw.where(block: false): box.with( fill: colors.gray, inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) show raw: set text(font: (字体.meslo-mono, 字体.思源宋体)) // 代码中文字体 show raw: it => { show regex("pin\d"): it => pin(eval(it.text.slice(3))) // pinit package for raw it } show: fix-indent() // 一个很 tricky 的包,需放在所有 show 规则的最后 if title != none { move(dy: -25pt, text(font: 字体.黑体, 2.5em, weight: 700, title)) } if show_toc {toc_note(toc_break: toc_break, depth: toc_depth)} // 目录 body v(10em) }
https://github.com/giZoes/justsit-thesis-typst-template
https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/utils/invisible-heading.typ
typst
MIT License
// 用于创建一个不可见的标题,用于给 outline 加上短标题 #let invisible-heading(..args) = { set text(size: 0pt, fill: white) heading(numbering: none, ..args) }
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/format.typ
typst
The Unlicense
#import "/packages.typ": tablex #import tablex: * #import "./colors.typ": * #let table(it) = { tablex( columns: it.columns, auto-lines: false, inset: 10pt, fill: (_, row) => { if calc.odd(row) { surface-3 } if calc.even(row) { surface-1 } }, hlinex(stroke: (cap: "round", thickness: 2pt)), ..for child in it.children { ([#child],) }, hlinex(stroke: (cap: "round", thickness: 2pt)), ) } #let heading(it) = { set block(below: 1em) let content = if it.level == 1 { set text(size: 15pt) box(fill: surface-3, outset: 0.5em, radius: 1.5pt, it.body) } else if it.level == 2 { set text(size: 14pt) it.body } else { set text(size: 11pt) it.body } block(content) } #let raw-not-block = box.with( fill: surface-2, inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) #let raw-block(it) = { set par(justify: false) // the line counter let i = 0 let box-radius = 1.5pt let detail-radius = 1.5pt if (it.lang != none) { grid( columns: (100%, 100%), column-gutter: (-100%), block( width: 100%, inset: 1em, { for line in it.text.split("\n") { box(width: 0pt, align(right, str(i + 1) + h(2em))) hide(line) linebreak() i = i + 1 } }, ), block( radius: box-radius, fill: surface-1, width: 100%, inset: 1em, { place( top + right, box(fill: surface-3, radius: detail-radius, outset: 3pt, it.lang), ) it }, ), ) } else { block(radius: box-radius, fill: surface-2, width: 100%, inset: 1em, it) } }
https://github.com/Myriad-Dreamin/shiroa
https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/github-pages/docs/format/book-meta.typ
typst
Apache License 2.0
#import "/github-pages/docs/book.typ": book-page #show: book-page.with(title: "Book Metadata") = Book Metadata #let type-hint(t, required: false) = { { set text(weight: 400, size: 16pt) if required { " (required) " } } { // show "<": set text(fill: blue) // show ">": set text(fill: blue) text(fill: red, raw(t)) } } === title #type-hint("string") Specify the title of the book. ```typ #book-meta( title: "../dist", ) ``` === authors #type-hint("array<string>") Specify the author(s) of the book. ```typ #book-meta( authors: ("Alice", "Bob"), ) ``` === summary #type-hint("content", required: true) Its formatting is very strict and must follow the structure outlined below to allow for easy parsing. Any element not specified below, be it formatting or textual, is likely to be ignored at best, or may cause an error when attempting to build the book. ```typ #book-meta( summary: [ #prefix-chapter("pre.typ")[Prefix Chapter] = User Guide - #chapter("1.typ", section: "1")[First Chapter] - #chapter("1.1.typ", section: "1.1")[First sub] - #chapter("2.typ", section: "1")[Second Chapter] #suffix-chapter("suf.typ")[Suffix Chapter] ], ) ``` + ***Prefix Chapter*** - Before the main numbered chapters, prefix chapters can be added that will not be numbered. This is useful for forewords, introductions, etc. There are, however, some constraints. Prefix chapters cannot be nested; they should all be on the root level. And you cannot add prefix chapters once you have added numbered chapters. ```typ #prefix-chapter("pre.typ")[Prefix Chapter] - #chapter("1.typ", section: "1")[First Chapter] ``` + ***Part Title*** - Headers can be used as a title for the following numbered chapters. This can be used to logically separate different sections of the book. The title is rendered as unclickable text. Titles are optional, and the numbered chapters can be broken into as many parts as desired. ```typ = My Part Title - #chapter("1.typ", section: "1")[First Chapter] ``` + ***Numbered Chapter*** - Numbered chapters outline the main content of the book and can be nested, resulting in a nice hierarchy (chapters, sub-chapters, etc.). ```typ = Title of Part - #chapter("first.typ", section: "1")[First Chapter] - #chapter("first-sub-chapter.typ", section: "1.1")[First sub-chapter] - #chapter("second.typ", section: "1")[Second Chapter] = Title of Another Part - #chapter("another/chapter.typ", section: "1")[Another Chapter] ``` Numbered chapters can be denoted either `-`. + ***Suffix Chapter*** - Like prefix chapters, suffix chapters are unnumbered, but they come after numbered chapters. ```typ = Last Part - #chapter("second.typ", section: "10")[Last Chapter] #suffix-chapter("suf.typ")[Title of Suffix Chapter] ``` + ***Draft chapters*** - Draft chapters are chapters without a file and thus content. The purpose of a draft chapter is to signal future chapters still to be written. Or when still laying out the structure of the book to avoid creating the files while you are still changing the structure of the book a lot. Draft chapters will be rendered in the HTML renderer as disabled links in the table of contents, as you can see for the next chapter in the table of contents on the left. Draft chapters are written like normal chapters but without writing the path to the file. ```typ #chapter(none, section: "5.2")[Draft Chapter] ``` + ***Separators*** - Separators can be added before, in between, and after any other element. They result in an HTML rendered line in the built table of contents. A separator is a line containing exclusively dashes and at least three of them: `---`. ```typ = My Part Title #prefix-chapter("pre.typ")[A Prefix Chapter] #divider() - #chapter("1.typ", section: "1")[First Chapter] ``` == Example Below is the summary content for the `book.typ` for this guide, with the resulting table of contents as rendered to the left. #{ let exp = read("../book.typ") let exp = exp.find(regex("// begin of summary[\s\S]*// end of summary")).split("\n") // remove first and last line (begin and end of summary) let exp = exp.slice(1, exp.len() - 2) // remove leading spaces let space = exp.at(0).position("#") let exp = exp.map(it => it.slice(space)) // filter out comments let exp = exp.filter(it => not it.starts-with(regex("\s*//"))) // render as typ raw block let exp = exp.join("\n") raw(exp, lang: "typ", block: true) } === description #type-hint("string") A description for the book, which is added as meta information in the html `<head>` of each page. ```typ #book-meta( description: "shiroa Documentation", ) ``` === repository #type-hint("string") The github repository for the book. ```typ #book-meta( repository: "https://github.com/Myriad-Dreamin/shiroa", ) ``` === language #type-hint("string") The main language of the book, which is used as a html language attribute `<html lang="en">` for example. ```typ #book-meta( language: "en", ) ```
https://github.com/qujihan/toydb-book
https://raw.githubusercontent.com/qujihan/toydb-book/main/src/chapter6/isolation.typ
typst
#import "../../typst-book-template/book.typ": * #let path-prefix = figure-root-path + "src/pics/" == 隔离级别 === 写倾斜(Write Skew)问题 <write-skew> === 参考 + https://justinjaffray.com/what-does-write-skew-look-like/
https://github.com/fywc/Resume_Template
https://raw.githubusercontent.com/fywc/Resume_Template/main/main.typ
typst
#import "template.typ": * #show heading: set text(black) // 项目具体描述的item设定 #set list(indent:12pt,body-indent:6pt) // 个人信息 #show: project.with( name: "Name", ) #info( phone:"(+86) xxxxxxxxxx", email:"<EMAIL>", github:"github.com/xxxx" ) == 教育背景 #line(length: 100%,stroke:0.7pt+black) #education( school:"XXXXXX", major:"专业", degree:"硕士", lab: "XXX实验室", mentor:"导师: XXX研究员", research:"研究方向: XXXX", date:"XXXX年 – XXXX年", )[] #education2( school:"XXXX", major:"XXXX专业", degree:"本科", date:"XXXX年 – XXXX年", grade:"GPA:xxx(4.0),年级前 xxx%", )[] == 个人能力 #line(length: 100%,stroke:0.7pt+black) #other()[ - 具体描述 - 具体描述 ] // 此句设置斜体,可以全局也可以在段落中间加 // #set text(style:"italic") == 工作经历 #line(length: 100%,stroke:0.7pt+black) #experience( name:"XXXX公司", type:"实习", // description:"职位介绍", date:"time", )[ - 具体描述 ] == 项目经历 #line(length: 100%,stroke:0.7pt+black) #experience( name:"XX项目", type:"实践项目", // description:"项目介绍", date:"time", )[ // 两种列表形式,自选 #list( [具体描述], [具体描述], ) ] #experience( name:"XX项目", type:"开源项目", // description:"项目介绍", date:"time", )[ #list( [具体描述], [具体描述], ) ] #experience( name:"XX项目", type:"课程项目", // description:"项目介绍", date:"time", )[ #list( [具体描述], [具体描述], ) ] == 专业技能 #line(length: 100%,stroke:0.7pt+black) #other()[ - Rust - git - English ] == 荣誉奖项 #line(length: 100%,stroke:0.7pt+black) #[ #prize( game:"XXXX荣誉", grade:"XXX奖", date:"time" )[] #prize( game:"XXXX荣誉", grade:"XXX奖", date:"time" )[] ] == 其他 #line(length: 100%,stroke:0.7pt+black) #other()[ Blog: https://xxx.blog ]
https://github.com/qujihan/typst-book-template
https://raw.githubusercontent.com/qujihan/typst-book-template/main/book.typ
typst
#import "template/parts/lib.typ": * #import "template/params.typ": * #import "template/utils.typ": * #let book(info: (), body) = { if not "title" in info { info.insert("title", "Unnamed Book") } if not "name" in info { info.insert("name", "Unnamed Author") } if not "outline-depth" in info { info.insert("outline-depth", 3) } set document( title: info.title, author: info.name, ) set page( paper: "a4", number-align: center + bottom, margin: auto, header: context { set align(center) let curr-page = here().page() let heading-1-anchors = query( selector(heading.where(level: 1)), ).map(it => it.location().page()) let heading-2-anchors = query( selector(heading.where(level: 2)), ).map(it => it.location().page()) let title1-infos = query(selector(heading.where(level: 1)).before(here())) let title2-infos = query(selector(heading.where(level: 2)).before(here())) let title1-body = "" let title2-body = "" if title1-infos.len() != 0 { title1-body = title1-infos.last().body } if title2-infos.len() != 0 { title2-body = title2-infos.last().body } if curr-page not in heading-1-anchors and curr-page not in heading-2-anchors { grid( columns: (1fr, 1fr), align: (left, right), text( size: 1em, fill: content-color, baseline: 0.5em, font: content-font, strong(title1-body), ), text( size: 1em, fill: content-color, baseline: 0.5em, font: content-font, strong(title2-body), ), ) line(length: 100%, stroke: 0.7pt + line-color) } if curr-page not in heading-1-anchors and curr-page in heading-2-anchors { grid( columns: (1fr), align: (center), text( size: 1em, fill: content-color, baseline: 0.5em, font: content-font, strong(title1-body), ) ) line(length: 100%, stroke: 0.7pt + line-color) } }, footer: context { set align(center) let curr-page = here().page() let heading-1-anchors = query( selector(heading.where(level: 1)), ).map(it => it.location().page()) grid( columns: (7fr, 1fr, 7fr), line(length: 100%, stroke: 0.7pt + line-color), text( font: chinese-font, fill: content-color, 0.8em, baseline: -3pt, strong(counter(page).display("1")), ), line(length: 100%, stroke: 0.7pt + line-color), ) }, ) set text( font: content-font, size: content-font-size, weight: 400, fill: content-color, ) show-cover(info.title, info.name) show-outline(info.outline-depth) set block(breakable: true) show footnote.entry: set text( font: content-font, size: 0.8em, fill: content-color, ) set footnote.entry( // separator: "", clearance: 0.8em, gap: 0.8em, indent: 0em, ) set par( first-line-indent: 2em, justify: true, leading: 0.8em, linebreaks: "optimized", spacing: 1.5em, ) show heading: set heading(numbering: "1.1.1 ") show heading.where(level: 1): it => { pagebreak(weak: false) let str = counter(heading).display("第1章") + " " + it.body text(size: 1.7em, str) } show heading.where(level: 2): it => { text(size: 1.5em, it) } show heading.where(level: 3): it => { text(size: 1.3em, it) } // reference: https://github.com/typst/typst/issues/311 // https://github.com/typst/typst/issues/311#issuecomment-2023038611 let virtual-line(radio) = ( context { let a = par(box()) a v(radio * measure(2 * a).width) } ) let indent-size = 1em show heading: it => { it virtual-line(-0.5) } set list(indent: indent-size) show list: it => { it virtual-line(-0.7) } set enum(indent: indent-size) show enum: it => { it virtual-line(-0.7) } show raw.where(block: true): it => { set text(size: 0.9em) set par(justify: false) it virtual-line(-0.7) } show raw.where(block: false): it => { set text(size: 1em, fill: code-line-color) h(0.2em) box( fill: luma(240), inset: (left: 0.2em, right: 0.2em, top: 0.3em, bottom: 0.3em), baseline: 0.2em, radius: 0.2em, )[ #h(0.2em) #it #h(0.2em) ] h(0.2em) } show raw: set block(breakable: true) show raw: it => { set text(font: (code-font, chinese-font)) it } show emph: it => { let left-right-space = 0.18em let top-size = 1em let bottom-size = -0.3em let radius-size = 0.35em let emph-context = context { box( baseline: -bottom-size, rect( width: left-right-space * 2, height: top-size - bottom-size, stroke: none, radius: (left: radius-size), fill: emph-color, ), ) it box( baseline: -bottom-size, rect( width: left-right-space * 2, height: top-size - bottom-size, stroke: none, radius: (right: radius-size), fill: emph-color, ), ) } highlight( fill: emph-color, top-edge: top-size, bottom-edge: bottom-size, // radius: 0.35em, // extent: left-right-space * 2, emph-context, ) } show figure: it => { set align(center) if it.kind == figure-kind-code { it.body it.supplement " " + it.counter.display(it.numbering) " " + it.caption.body let chapter-num = counter(heading.where(level: 1)).display() counter(figure-kind-code + str(chapter-num)).step() } else if it.kind == figure-kind-pic { it.body it.supplement " " + it.counter.display(it.numbering) " " + it.caption.body let chapter-num = counter(heading.where(level: 1)).display() counter(figure-kind-pic + str(chapter-num)).step() } else if it.kind == figure-kind-tbl { it.body it.supplement " " + it.counter.display(it.numbering) " " + it.caption.body let chapter-num = counter(heading.where(level: 1)).display() counter(figure-kind-tbl + str(chapter-num)).step() } else { it.body } } counter(page).update(1) show page: it => { counter(footnote).update(0) it } body }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/indenta/0.0.1/lib.typ
typst
Apache License 2.0
#let fix-indent(len: 2em, unsafe: false)={ return it=>{ let st=0 let _is_block(e,fn)=(fn==math.equation and e.block) or fn==figure or fn==block or fn==list.item or fn==enum.item let _is_inline(e,fn)=fn==text or (fn==math.equation and not e.block) or fn==box for e in it.children{ let fn=e.func() if st==0{ if fn==heading or _is_block(e,fn){st=1} }else if st==1{ if fn==parbreak{st=2} else{st=0} }else if st==2{ if _is_block(e,fn){st=1} else { if unsafe or _is_inline(e,fn){h(len)} st=0 } } e } }}
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/Presentations/Midpoint/presentation.typ
typst
#import "@preview/polylux:0.3.1": * #set page(paper: "presentation-16-9") #set text(size: 25pt) #polylux-slide[ #align(horizon + center)[ = Visual FP === _Design Decision_ ] ] #polylux-slide[ = Outline #v(1fr) - Goals #v(1fr) - Flo inspired #v(1fr) - Scratch inspired #v(1fr) - Mehta-drawing inspired #v(1fr) - Eros #v(1fr) ] #polylux-slide[ = Goals #v(1fr) In order: #v(1fr) 1. Educational tool for FP #v(1fr) 2. Graphical Development of Haskell code #v(1fr) 3. Tool for professional users #v(1fr) ] #include "flo-inspired.typ" #polylux-slide[ = Scratch inspired #align(center + horizon, image("static/scratch-inspired-01.png", width: 90%)) ] #polylux-slide[ = Scratch inspired #align(center + horizon, image("static/scratch-inspired-02.png", width: 100%)) ] #polylux-slide[ = Scratch inspired #align(center + horizon, image("static/scratch-inspired-03.png", width: 70%)) ] #polylux-slide[ = Scratch inspired #v(1fr) ```hs product [] = 1 product (x:xs) = x * product xs ``` #v(1fr) #image("static/scratch-inspired-04.png", width: 90%) #v(1fr) ] #polylux-slide[ = Scratch inspired #v(1fr) ```hs filter even (takeWhile (<= 10) (iterate (+ 1) 0)) ``` #v(1fr) #image("static/scratch-inspired-05.png", width: 90%) #v(1fr) ] #polylux-slide[ = Haskell Function-Notation inspired #align(center + horizon, image("static/mehta-drawing.png", width: 50%)) ] #polylux-slide[ = Haskell Function-Notation inspired #align(center + horizon, image("static/funcnotation_addition.png", width: 30%)) ] #polylux-slide[ = Haskell Function-Notation inspired #align(center + horizon, image("static/funcnotation_evenOneToTen.png", width: 85%)) ] #polylux-slide[ = Haskell Function-Notation inspired #align(center + horizon, image("static/funcnotation_collapsing.png", width: 65%)) ] #polylux-slide[ = Eros inspired #v(1fr) - _Deep Application_ hides implementation details #v(1fr) - _Tangled Values_ make it difficult to navigate #v(1fr) - Need for interactive-visualizers compatible with every value is difficult to scale to general-purpose programming #v(1fr) Like a 'no-code' tool, thought for people to avoid thinking about code rather than teaching them how to #v(1fr) ] #polylux-slide[ = Decision #v(1fr) - Design decision based on feedback of students & programmers #v(1fr) - Questions: - Were you able to understand the meaning of the boxes and arrows? - Do you find the concept nice to look at? - Could you imagine teaching functional programming using this vizualization? - Do you have any suggestions for improvement or general comments on the concept? #v(1fr) ]
https://github.com/alerque/polytype
https://raw.githubusercontent.com/alerque/polytype/master/content/integral-alignment.md
markdown
+++ title = "Alignment of Integrals" description = "Compare the baseline alignment of integrals." extra.typesetters = [ "typst", "sile", "xelatex" ] +++ Compare the baseline alignment of integrals. aka. What's up must come down.
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/requirements-analysis/playground.typ
typst
=== Ungrammar Online Demonstration Playground ==== List of Usecase - Try Code Editor - Change Theme - View Security - View Documentation ==== Usecase Diagram #figure( image("/diagrams/generated/usecase/uc-ungram-playground.svg", width: 80%), caption: [Usecase Diagram of Ungrammar Online Demonstration Playground] ) ==== Usecase Specifications #[ #set raw(lang: "gherkin", block: true) #figure( raw(read("/features/try-code-editor.feature")), caption: [Try Code Editor Usecase], ) #figure( raw(read("/features/change-theme.feature")), caption: [Change Theme Usecase], ) #figure( raw(read("/features/view-security.feature")), caption: [View Security Usecase], ) #figure( raw(read("/features/view-documentation.feature")), caption: [View Documentation Usecase], ) ]
https://github.com/pku-typst/PKU-typst-template
https://raw.githubusercontent.com/pku-typst/PKU-typst-template/main/utils/zihao.typ
typst
MIT License
#let 初号 = 42pt #let 小初 = 36pt #let 一号 = 26pt // #let 小一 = 24pt #let 二号 = 22pt #let 小二 = 18pt #let 三号 = 16pt #let 小三 = 15pt #let 四号 = 14pt #let 小四 = 12pt #let 五号 = 10.5pt #let 小五 = 9pt #let 六号 = 7.5pt #let 小六 = 6.5pt #let 七号 = 5.5pt #let 八号 = 5pt
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Symmetry%20Groups%20and%20Degeneracy.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "Symmetry Groups and Degeneracy", authors: ( "<NAME>", ), date: "10 Août, 2024", ) #set heading(numbering: "1.1.") == Symmetry Groups and Degeneracy in Advanced Quantum Mechanics <symmetry-groups-and-degeneracy-in-advanced-quantum-mechanics> === 1. Rotational Symmetry: <rotational-symmetry> - Rotational symmetry is a fundamental concept in quantum mechanics that arises from the isotropy of space, i.e., the laws of physics remain unchanged under rotations. - Rotational symmetry is closely related to angular momentum, which quantifies the rotational motion of a system. - Angular momentum operators, denoted by $J$, are defined by the commutation relations $[J_i , J_j] = i planck.reduce epsilon.alt_(i j k) J_k$, where $i$, $j$, and $k$ are the Cartesian components and $epsilon.alt_(i j k)$ is the Levi-Civita symbol. === 2. Angular Momentum: <angular-momentum> - Angular momentum is a conserved quantity in quantum mechanics and plays a crucial role in the description of particles and their interactions. - In quantum mechanics, angular momentum is quantized, meaning it can only take certain discrete values. - The total angular momentum operator, denoted by $J$, is the sum of the orbital angular momentum operator ($L$) and the spin angular momentum operator ($S$). === 3. Commutator: <commutator> - The commutator between two operators $A$ and $B$, denoted by $[A , B]$, is defined as $[A , B] = A B - B A$. - The commutator quantifies the non-commutativity of operators and determines the order in which they act. - In quantum mechanics, the commutator between two observables represents the uncertainty relation between them. === 4. Degeneracy: <degeneracy> - Degeneracy refers to the phenomenon where multiple states of a quantum system have the same energy. - Degeneracy arises due to the existence of symmetry in the system, leading to multiple states with indistinguishable energies. - Degenerate states form a subspace within the larger Hilbert space associated with the system. - Degeneracy can have profound implications for the behavior and properties of quantum systems. === 5. Symmetry Generators: <symmetry-generators> - Symmetry generators are operators that generate symmetry transformations on a quantum system. - For rotational symmetry, the symmetry generators are the components of angular momentum operators ($J_x , J_y , J_z$). - Symmetry generators act on quantum states to produce transformed states that belong to the same symmetry class. === 6. Symmetry Groups: <symmetry-groups> - Symmetry groups are mathematical structures that describe the collection of all symmetry transformations that leave a physical system invariant. - In quantum mechanics, symmetry groups play a fundamental role in determining the properties and behaviors of quantum systems. - The symmetry group associated with rotational symmetry is the special unitary group in three dimensions, denoted by $S U (2)$. - Symmetry groups provide a powerful framework for understanding the degeneracy and symmetry-related properties of quantum systems. === 7. Lie Algebra: <lie-algebra> - The Lie algebra of a symmetry group is a vector space that captures the algebraic properties of the group’s generators. - In the case of rotational symmetry, the Lie algebra associated with the special unitary group in three dimensions ($S U (2)$) is the algebra of Pauli spin matrices. - The Lie algebra provides a mathematical foundation for studying the symmetry transformations and their algebraic relations. === 8. Raising and Lowering Operators: <raising-and-lowering-operators> - Raising and lowering operators are operators that allow the generation of new states with different angular momentum quantum numbers from a given state. - In the context of angular momentum, raising operators ($J_(+)$) increase the angular momentum quantum number, while lowering operators ($J_(-)$) decrease it. - The action of raising and lowering operators on angular momentum eigenstates leads to the construction of multiplets and facilitates the understanding of degeneracy. #link("Maths.pdf")[Maths]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/document-01.typ
typst
Other
// This, too. // Ref: false #set document(author: ("A", "B"))
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/book/book-Android%20Compose.typ
typst
#import "@preview/ilm:1.1.2": * #set text( lang: "zh", font: "PingFang SC", // font: "JetBrains Mono", ) #show: ilm.with( title: [Android Compose], author: "dry", date: datetime(year: 2024, month: 07, day: 2), abstract: [ Android Compose的开发记录。 ], preface: [ #align(center + horizon)[ // 主要来源于#link("https://leetcode.cn/")[_力扣_] ] ], bibliography: bibliography("refs.bib"), figure-index: (enabled: true), table-index: (enabled: true), listing-index: (enabled: true) ) = 备忘录
https://github.com/AOx0/expo-nosql
https://raw.githubusercontent.com/AOx0/expo-nosql/main/themes/bipartite.typ
typst
MIT License
// This theme is inspired by https://slidesgo.com/theme/modern-annual-report #let bipartite-theme() = data => { let my-dark = rgb("#192e41") let my-bright = rgb("#fafafa") let my-accent = rgb("#fc9278") let title-slide(slide-info, bodies) = { if bodies.len() != 0 { panic("title slide of bipartite theme does not support any bodies") } block( width: 100%, height: 60%, outset: 0em, inset: 0em, breakable: false, stroke: none, spacing: 0em, fill: my-bright, align(center + horizon, text(size: 1.7em, fill: my-dark, data.title)) ) block( width: 100%, height: 40%, outset: 0em, inset: 0em, breakable: false, stroke: none, spacing: 0em, fill: my-dark, align(center + horizon, text(fill: my-bright)[ #text(size: 1.2em, data.subtitle) // #v(.0em) #text(size: .9em)[ #data.authors.join(", ") #h(1em) #sym.dot.c #h(1em) #data.date ] ]) ) place( center + horizon, dy: 10%, rect(width: 6em, height: .5em, radius: .25em, fill: my-accent) ) } let displayed-title(slide-info) = if "title" in slide-info { heading(level: 1, text(fill: my-bright, slide-info.title)) } else { [] } let west(slide-info, bodies) = { if bodies.len() != 1 { panic("default variant of bipartite theme only supports one body per slide") } let body = bodies.first() box( width: 30%, height: 100%, outset: 0em, inset: (x: 1em), baseline: 0em, stroke: none, fill: my-dark, align( left + horizon, displayed-title(slide-info) ) ) box( width: 70%, height: 100%, outset: 0em, inset: (x: 1em), baseline: 0em, stroke: none, fill: my-bright, align(left + horizon, text(fill: my-dark, body)) ) } let east(slide-info, bodies) = { if bodies.len() != 1 { panic("east variant of bipartite theme only supports one body per slide") } let body = bodies.first() box( width: 70%, height: 100%, outset: 0em, inset: (x: 1em), baseline: 0em, stroke: none, fill: my-bright, align(right + horizon, text(fill: my-dark, body)) ) box( width: 30%, height: 100%, outset: 0em, inset: (x: 1em), baseline: 0em, stroke: none, fill: my-dark, align( right + horizon, displayed-title(slide-info) ) ) } let center-split(slide-info, bodies) = { if bodies.len() != 2 { panic("center split variant of bipartite theme only supports two bodies per slide") } let body-left = bodies.first() let body-right = bodies.last() box( width: 50%, height: 100%, outset: 0em, inset: (x: 1em), baseline: 0em, stroke: none, fill: my-bright, align(right + horizon, text(fill: my-dark, body-left)) ) box( width: 50%, height: 100%, outset: 0em, inset: (x: 1em), baseline: 0em, stroke: none, fill: my-dark, align(left + horizon, text(fill: my-bright, body-right)) ) } ( "title slide": title-slide, "default": west, "east": east, "center split": center-split, ) }
https://github.com/MyPedagogicalRessources/BUT1-R1-01-Initiation-developpement
https://raw.githubusercontent.com/MyPedagogicalRessources/BUT1-R1-01-Initiation-developpement/main/TD/R1-01-Initiation_developpement-TD.typ
typst
#import "@preview/ilm:1.1.2": * #show: ilm.with( title: [R1-01 - Initiation au développement - TD], author: "<NAME>, <NAME>", date: datetime(year: 2024, month: 08, day: 19), abstract: [], preface: [], // bibliography: bibliography("refs.bib"), figure-index: (enabled: false), table-index: (enabled: false), listing-index: (enabled: false) ) #set heading(numbering: "1.1.") #import "TD1-Structures-controle.typ":* #td1(isCorrection: true) #import "TD2-Trace-dessins.typ":* #td2(isCorrection: true)
https://github.com/miyaji255/Typst-Utilities
https://raw.githubusercontent.com/miyaji255/Typst-Utilities/main/templates/電気電子工学実験A.typ
typst
MIT License
#let myname = "<NAME>" #let mynumber = "00A01234" #let mycourse = "~~コース" #let mymail = "<EMAIL>" #let mygroup = 1 #let members = ("阪大 太郎", "阪大 太郎") #let first_page = ( number, title, experiment_date, write_date: datetime.today(), members: members, ) => [ #set text(font: "Yu Mincho", size: 14pt) #set underline(offset: 0.25em, stroke: 0.5pt) #align( center, )[ #text(font: "Yu Gothic", size: 20pt)[*電子情報工学科*\ *電気電子工学専門実験A 報告*\ #h(1em) *第 #number 号*] #v(2em) #text(size: 16pt)[ 実 験 題 目\ #underline(title)\ ] #underline( )[#mycourse#box(width: 2em, stroke: (bottom: 0.5pt), outset: (bottom: 0.25em))第 #mygroup 班 #members.join("\n") ] #align(bottom)[ #{ "報  告  者" } #underline()[ #{ mynumber }番#{ " " }#myname #{ " " } (#mycourse)\ 電子メールアドレス:#mymail ] #v(4em) #write_date.display("[year]年[month]月[day]日")\ 大阪大学工学部電子情報工学科] ] #pagebreak() ] #let experiment_date = datetime(year: 2023, month: 01, day: 01) #first_page("A1", "ハイパワー衝撃回路の基礎実験", experiment_date)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/grid-2_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 60pt) #lorem(5) - #lorem(5)
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Maths_Prepa_MPSI_Chap1_Ex.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "Maths Prepa MPSI Chap1 Ex", authors: ( "<NAME>", ), date: "30 Octobre, 2023", ) #set heading(numbering: "1.1.") == Ex 2 <ex-2> #block[ #set enum(numbering: "1)", start: 1) + Prouvons par l’absurde $forall x in bb(R)$ et $x gt 2$ Supposons que $x gt.eq 3$ Si $x eq 2 comma 1$ On a $x gt 2 upright("et") x in bb(R)$ Or $2 comma 1 lt 3$ donc $x gt.eq.not 3$ Soit la propriété non vraie pour tout les $x$ appartenant à $bb(R)$ + $forall lr((x comma y)) in lr((bb(R)^ast.basic))^2 comma x lt y$ Posons la fonction $f$ avec $f lr((x)) eq 1 / x$ $f prime lr((x)) eq minus 1 / sqrt(x)$ $x gt 0 upright("ou") x lt 0$ Pour $x gt 0$ $f prime lr((x)) lt 0$ $x lt 0$ $f prime lr((x)) gt 0$ donc $f$ est croissante sur $bracket.r 0 semi plus oo bracket.l$ et décroissante sur $bracket.r minus oo semi 0 bracket.l$ Donc en composant par f(x) l’égalité devient Pour $x gt 0$ et $y gt 0$ $1 / x gt 1 / y$ et pour $x lt 0$ et $y lt 0$ $1 / x lt 1 / y$ ce qui est différent de la proposition De plus l’égalité est indéterminable dans les autres cas + Soit $x in bb(R)_plus$. On a : $x lt sqrt(x)$ \ $arrow.l.r.double x^2 lt x$ $arrow.l.r.double x lr((x minus 1)) lt 0$ ] On en déduit que : - Si $x in bracket.r 0 comma 1 bracket.l$, alors $x lr((x minus 1)) lt 0$ et donc $x lt sqrt(x)$. - Si $x gt.eq 1$, alors $x lr((x minus 1)) gt.eq 0$ et donc $x gt.eq sqrt(x)$. Donc l’énoncé "$exists x in bb(R)_plus upright(", ") x lt sqrt(x)$" est vrai, puisqu’il existe des réels strictement positifs inférieurs à 1 qui vérifient cette inégalité. #block[ #set enum(numbering: "1)", start: 6) + $forall x in bb(R) upright(",") quad x^2 plus x gt.eq 0 arrow.r.double x gt.eq 0$ ] Prenons un contre-exemple Posons $x eq minus 1 / 4$ alors $x^2 plus x eq lr((minus 1 / 4))^2 minus 1 / 4 eq minus 3 / 16 lt 0$ Donc la propriété n’est pas vraie pour tout x dans $bb(R)$
https://github.com/0x6b/typster
https://raw.githubusercontent.com/0x6b/typster/main/examples/sample.typ
typst
Apache License 2.0
// Shamelessly copied from https://zenn.dev/monaqa/articles/2023-04-19-typst-introduction // Thank you! #set document( title: "確率論の基礎", author: "typster", keywords: "確率論, 確率空間, 確率測度, 確率質量関数, 可測空間, 可測集合, 事象, Event, 確率, 定理, 定義, 例", date: auto ) // --------- ちょっとした設定 --------- // フォント周り #set text(font: "Noto Serif JP") #show emph: set text(font: "Noto Sans JP") #show strong: set text(font: "Noto Sans JP", fill: red) // 段落での両端揃えを有効化・行送りの長さを指定 #set par(justify: true, leading: 0.75em) // 箇条書きと別行立て数式の設定 #set list(indent: 0.5em) #set enum(numbering: "(1)") #set math.equation(numbering: "(1)") // theorem 用カウンタの定義 #let theorem-number = counter("theorem-number") // theorem 関数の定義。コマンドみたいに使える #let theorem(title: none, kind: "定理", body) = { let title-text = { if title == none { emph[#kind 2.#theorem-number.display()] } else { emph[#kind 2.#theorem-number.display() 【#title】] } } box(stroke: (left: 1pt), inset: (left: 5pt, top: 2pt, bottom: 5pt))[ #title-text #h(0.5em) #body ] theorem-number.step() } // 数式で用いるエイリアス($\mathcal{F}$ 的なやつ) #let cF = $cal(F)$ // 以降のテキストで現れる句読点を全角カンマピリオドに置換する。そんなこともできるの… #show "、": "," #show "。": "." // --------- ここから本文のマークアップ --------- #theorem(kind: "定義", title: [$sigma$-加法族])[ $Omega$ の部分集合族 $cF$ が以下の性質を満たすとき、 $Omega$ を $sigma$-加法族という。 + $Omega in cF$ + $A in cF ==> A^c in cF$ + $A_1, A_2, dots in cF$ に対して以下のことが成り立つ(_$sigma$-加法性、完全加法性、加算加法性_): $ union.big_(i=1)^infinity A_i in cF $ ] $A subset Omega$ に「確率」を定めたい。矛盾なく「確率」が定まる集合をあらかじめ決めておきたい。 それが $sigma$-加法族である。 $Omega$ と $cF$ の組 $(Omega, cF)$ を#strong[可測空間]という。 また、$cF$ の元を#strong[可測集合](または事象、Event)という。 #theorem(kind: "定義", title: [確率測度])[ $(Omega, cF)$ を可測空間とする。 $cF$ 上の関数 $P$ が次を満たすとき、これを#strong[確率測度]という。 - $0 <= P(A) <= 1 #h(0.5em) (forall A in cF)$ - $P(Omega) = 1$ - $A_1, A_2, dots in cF$ が $A_i sect A_j = nothing #h(0.25em) (forall i != j)$ のとき、 次が成り立つ($sigma$-加法性、完全加法性): $ P(union.big_(i=1)^infinity A_i) = sum_(i=1)^infinity P(A_i) $ ] $P$ が $(Omega, cF)$ の確率測度のとき、 $(Omega, cF, P)$ を#strong[確率空間]という。 #theorem(kind: "例", title: [一定時間に到着するメールの数])[ $Omega = {0, 1, 2, dots}$ で、 $ P(A) = sum_(omega in A) (lambda^omega)/(omega!) e^(-lambda) $ とすると、これも確率測度になっている($A$ は強度 $lambda$ の Poisson 過程に従うという)。 ] $Omega$ が加算無限の場合、 $cF = 2^Omega$ を考えておけば問題ない。 $0 <= h(omega) <= 1$, $sum_(omega in Omega) h(omega) = 1$ となるような $h$ を用いて $P(A) = sum_(omega in A) h(omega)$ とおけば、 $P$ は確率測度となる。 この $h(omega)$ のことを、確率質量関数という。
https://github.com/i-am-wololo/cours
https://raw.githubusercontent.com/i-am-wololo/cours/master/main/parties_i23/relations.typ
typst
#import "../templates.typ": * #title("Relations et applications")
https://github.com/han0126/MCM-test
https://raw.githubusercontent.com/han0126/MCM-test/main/2024亚太杯typst/chapter/chapter6.typ
typst
#import "../template/template.typ": * = 问题三的模型建立与求解 == 问题分析 题目要求在第一问的相关性基础上,建立洪水概率模型。而洪水发生与$20$个指标均有关系,模型过于庞大,故从中选取相关性较强的几组指标建立模型。则洪水概率可以直接由各项指标的值进行线性运算得出。紧接着,为进一步简化模型,仍是依据相关系数仅选取$5$项指标,对模型进行修改。同时,我们考虑到由于选取指标的个数差异会导致建立的洪水发生概率模型的精度产生不同,即分析选取$5$组指标建立的模型与原来选取的多组指标所建立的模型进行精度比较。从而可以得到选取相关性较强的指标对于模型的影响。 == 基于$"MLP"$神经网络模型建立 === 指标选取 根据第一问分析所得的相关系数大小来选取与洪水发生概率相关性相对强的指标$x_i$。在第二小问中仅选取出前$5$个相关性最强的指标。即在第一小问中选取:基础设施恶化、季风强度、地形排水、大坝质量、河流管理、淤积、人口得分、气候变化、滑坡$9$个指标;在第二小问中选取:基础设施恶化、季风强度、地形排水、大坝质量、河流管理$5$个指标。 === $"MLP"$神经网络 $"MLP"$神经网络即是对已有的数据进行处理,拟合出来一个比较好的模型,再通过添加一些其他的数据来对拟合出来的模型进行误差分析,修改原来拟合出的模型,使模型的误差降低。其工作原理分为两个部分: 1. 前向传播:输入数据通过网络的输入层,经过隐藏层中的加权求和和激活函数处理,最终得到输出层的结果。 2. 反向传播:$"MLP"$神经网络通常使用反向传播算法来优化网络参数,以最小化预测输出与实际输出之间的误差。反向传播通过计算损失函数的梯度,然后沿着梯度的反方向调整权重和偏置。 #img( image("../figures/4.jpg", width: 70%), caption: "MLP神经网络示意图" ) === $"MLP"$模型建立与评估 首先导入`train.csv`数据集,并将其划分为$80%$的训练集和的$20%$测试集,同时设置随机状态为$1$以保证结果的可重复性;接着通过计算数据的均值与标准差,将特征数据进行标准化,以保证模型训练过程中的数值稳定性;然后创建$"MLP"$模型,设置三层隐藏层分别为$200、100、50$,并将双曲正切函数$tanh$作为激活函数,并确定学习率初始化值、最大迭代次数、正则化参数、随机状态和开启早停策略以防止过拟合。基于上述灵敏度分析,最后得出评估模型精度为$99.97%$。
https://github.com/mkhoatd/Typst-CV-Resume
https://raw.githubusercontent.com/mkhoatd/Typst-CV-Resume/main/CV/example_single.typ
typst
MIT License
#import "typstcv_single.typ": * // TODO: add more bibstyle and try to use yaml and xml to replace json // // select the font type: "macfont" or "openfont" #let fonttype = "macfont" #show: mainbody => main( continue_header: "false", name: [<NAME>], //name:"" or name:[] // address: [#lorem(4)], lastupdated: "true", pagecount: "true", date:"2023.4.7", contacts: ( (text:"+84915960597",link:""), (text:"mkhoatd.me",link:"https://mkhoatd.me"), (text:"github.com/mkhoatd",link:"https://github.com/mkhoatd"), (text:"<EMAIL>",link:"mailto:<EMAIL>"), ), bibfile: [bib.json], mainbody ) //About #section("About") #descript[#lorem(50)] #sectionsep #section("Education") #education[#lorem(4)][#lorem(2)][xxxx-xxxx][UK][Core Modules: #lorem(10)]\ #education[#lorem(4)][#lorem(2)][xxxx-xxxx][UK][] #sectionsep #section("Skills") #descript("Programming Languages") #info[Python, C++, Java, JavaScript, HTML, CSS, SQL, LaTeX] #subsectionsep #descript("Frameworks") #info[React, Node.js, Express, Flask, Django, Bootstrap, jQuery] #subsectionsep #descript("Tools") #info[Git, GitHub, Docker, AWS, Heroku, MongoDB, MySQL, PostgreSQL, Redis, Linux] #sectionsep // Award #section("Awards") #awarddetail[2018][Scholarship][University] #awarddetail[2017][Grant][Organisation] #awarddetail[2016][Scholarship][University] #sectionsep //Experience #section("Experience") #jobtitle[#lorem(4)][#lorem(2)][xxxx-xxxx][UK] #jobdetail[ - #lorem(10) - #lorem(10) - #lorem(10) - #lorem(10)] #subsectionsep #jobtitle[#lorem(4)][#lorem(2)][xxxx-xxxx][UK] #jobdetail[#lorem(30)] #sectionsep // Projects #section("Projects") #project[#lorem(2)][Jan 2023][#lorem(40)] #subsectionsep #project[#lorem(2)][][ - #lorem(15) - #lorem(15) ] #subsectionsep #project[#lorem(2)][][#lorem(40)] #sectionsep // Publication #section("Publications") #chicago(json("bib.json")) // #apa(json("bib.json"))
https://github.com/djakish/render-typst
https://raw.githubusercontent.com/djakish/render-typst/main/README.md
markdown
Apache License 2.0
SVG/PDF render some typst text, only got it working with vite, and kind of with webpack. # Usage ```ts import init, { addFont, addSource, renderSvgMerged } from '@djakish/render-typst' import lin_font_r from '../assets/fonts/LinLibertine_R.ttf' // Load a font await addFont(lin_font_r) // Set input values setInputs({ "name": "world", }) // Set the main source file addSource(`#text([Hello #sys.inputs.name!],fill: red)`, "main.typ") // Get rendered SVG let doc = renderSvgMerged() ``` # Vite dependencies for wasm With vite you would need [vite-plugin-wasm](https://www.npmjs.com/package/vite-plugin-wasm) and [vite-plugin-top-level-await](https://www.npmjs.com/package/vite-plugin-top-level-await). # Setting up with webpack Next config that I got to work. ```js const nextConfig = { reactStrictMode: true, webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => { // For wasm config.externals.experiments = { asyncWebAssembly: true, importAsync: true, layers: true, } config.experiments = { asyncWebAssembly: true, layers: true, } config.module?.rules?.push({ test: /\.bin$/i, type: 'asset/resource', generator: { filename: 'assets/[hash][ext][query]', }, }); return config } } ``` Component that worked ```jsx <button onClick={async (e) => { const typst = (await import("@djakish/render-typst")); await typst.addFont("/LinLibertine_R.ttf") typst.addSource(`#text("Hello world!",fill: red)`, "main.typ"); let doc = typst.renderSvgMerged() let preview = document.querySelector<HTMLDivElement('#preview')!; preview.innerHTML = doc }}>Render</button> <div id='preview'></div> ``` # Building You need wasm-pack and rust, and dependencies for them. ```sh wasm-pack build --target bundler ```
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/tests/complex/output-complex-root/test.typ
typst
Apache License 2.0
#import "/src/lib.typ": * #set page(width: auto, height: auto, margin: 1cm) #complex(1, 2, output-complex-root: [i]) #complex(1, 2, output-complex-root: [j])
https://github.com/enseignantePC/2023-24
https://raw.githubusercontent.com/enseignantePC/2023-24/master/presentation.typ
typst
#import "chapter_template.typ": chapitre, doc #let doc = doc.with( show_doc: false, boxed: false, breakable: false, ) #show: it => chapitre( it, number: [zéro], title: [Introduction], objectifs: ( [Apprendre à se connaître], [Fondations pour travailler ensemble (le respect, l'écoute)], [Construire sa philosophie de l'école, attaquer le mythe de la neutralité], ), ) #set text(size: 13pt) #show heading.where(level: 1): it => text(size: 14pt)[*_#it.body;_*] #show heading.where(level: 2): it => text(size: 14pt)[*#it.body;*] #set par(justify: false, linebreaks: "optimized") #doc( title: [= À quoi ça sert l'école \ _(et est-ce que ça marche?)_], )[ - À quoi c'est supposé servir? Est-ce que ça marche?\ _ex: médecin de père en fils._ - À qui et quoi ça sert vraiment? (Se préparer au travail donc pas de temps pour se developer en tant que personne?) - Ceux qui n'ont pas aimé leur collège, levons la main. _*Merci de choisir une raison et de l'écrire sur le papier qui sera ramassé.*_ ] #doc( title: [= Ce que j'attends de vous? _(et ce que vous pouvez attendre de moi)_], )[ - Quand je parle, pas de bruit on m'écoute. Quand vous me parlez pareil. //typstfmt::off - Quand j'ai l'attention de la classe, on ne m'interrompt pas et je ne répond pas aux questions hors sujet. //typstfmt::on - Quand tout le monde est au travail, je réponds à toutes les questions. ] #doc( title: [= S'organiser], )[ + Toujours avoir sa blouse en TP (ou on rentre pas). 1 avertissement (sans manip) puis absence. + Venir avec un porte vue et des feuilles, de quoi écrire, une calculatrice. ] #doc( title: [= Pourquoi faire de la physique chimie/des études?], )[ Est-ce nécessaire/utile? - Pour envoyer des avions dans l'air? (pollution.) - Pour faire des centrales? (bombes atomiques) Comment éviter le cynisme. pourquoi les études? *Pour le pouvoir.* Je choisis ma vie et je suis heureuse alors vous pouvez le faire aussi (en tout cas je vous soutiens). Décider comment vivre, faire ce qu'on veut de son temps et de son argent. Je suis avec vous mais ni vous ni moi n'avons une énergie infinie (ex: burn out). ] #doc( title: [= Est-ce que c'est difficile?], )[ C'est long et parfois difficile. C'est rare de rencontrer des physicien.nes chimistes qui comprennent en profondeur tout ce qu'il font même adulte. Il faut s'accrocher en permanence et se laisser guider par le beau. ] #doc( title: [= C'est pour les garçons ou les filles? (mythe de la neutralité)], )[ Historiquement l'importance scientifique a été très inégalement répartie. Dans les sciences et dans la plupart des autres milieux, les hommes ont un avantage social injuste. Aujourd'hui, même si on voit beaucoup plus de femmes scientifiques, il ne faut pas relâcher sa vigilance car l'égalité n' a pas été atteinte. Des femmes sont décrédibilisées aujourd'hui dans leur travail scientifique pour leur genre. ] #doc( title: [= Quoi de beau en PC], )[ À la frontière entre les maths, l'informatique, la SVT etc, on essaie souvent d'apporter une explication de fond aux phénomènes. Ma réponse personnelle : Le fonctionnement des ordinateurs. L'histoire est pleine d'anecdote et d'erreurs que je trouve très belle (Méchain et la précision du mètre #footnote[Mesurer le Monde, l'incroyable histoire de l'invention du mètre, <NAME>], Neptune et Vulcain #footnote[La découverte de Neptune et le fiasco de Vulcain, <NAME>-Palencia]). ] #doc( title: [Donc la PC, c'est mieux que le reste?], )[ Non, tout est beau. Anecdote de Darwin et sa cousine. ] #doc( title: [Le but final c'est quoi?], )[ + Se découvrir, se respecter les uns les autres, travailler ensemble, Travailler sa curiosité. + Faire les choses pour soi vs choisir ses combats (attente déraisonnable). Conseil: dirigez vous vers ce qui vous intéresse et explorez le. Prenez le temps. ]
https://github.com/EGmux/ControlTheory-2023.2
https://raw.githubusercontent.com/EGmux/ControlTheory-2023.2/main/classNotes/comentarioResolucao.typ
typst
#set heading(numbering: "1.") = Poles and stability === Every single pole in left semi plane $->$ stable === Any pole in imaginary axis with 1 multiplicity $->$ partially stable === Any pole in right semi plane/ pole in imaginary axis/ higher multiplicity than 1 $->$ unstable = Good practices === Place every repeatable element in a line #line(length: 100%)
https://github.com/0x1B05/nju_os
https://raw.githubusercontent.com/0x1B05/nju_os/main/lecture_notes/content/01_操作系统概述.typ
typst
#import "../template.typ": * = 操作系统概述 == (Why): 为什么要学操作系统? === 为什么要学 "任何东西"? 为什么要学操作系统呢? 为什么要学微积分/离散数学/XXXX/...? === 学过微积分以后, 再看为什么要学微积分 微积分的几个重要主题 - 启蒙, 应用与挑战 (Newton 时代) - 机械论世界观 (模型驱动的系统分析) - 数学是理解世界的 "基本工具": 导数, 微积分基本定理, ... - 严格化与公理化 (Cauchy 时代) - 各种卡出的 bug (Weierstrass 函数, Peano 曲线...) - 大规模问题的数值计算 (von Neumann 时代) - 优化, 有限元, PID... - AI 是未来人类社会的 "基本工具" 三个主题应该根据学科特点各有侧重 我自己的感受: 学了很多, 但好像都没学懂 === 为什么要学 "任何东西"? 重走从无到有的发现历程: - 基本思想, 基本方法, 里程碑, 走过的弯路 - 最终目的: 应用/创新 (做题得分不是目的而是手段) - 如果只是记得几个结论, 那 ChatGPT 已经做得很好了 学习 "任何东西" 的现代方法: - 使用辅助工具加速探索 - 数值/符号计算: numpy, sympy, sage, Mathematica, ... - 可视化: matplotlib - All-in-one: Jupyter (2017 ACM Software System Award) - Life is short; you need Python - (正好我有一个微积分相关的案例):#link("..\demo\01_demo\Exploration_and_Discovery_of_Mathematical_Concepts.ipynb")[Exploration_and_Discovery_of_Mathematical_Concepts] === 为什么学习操作系统? 你体内的 "编程力量" 尚未完全觉醒 - 每天都在用的东西, 你还没搞明白 - 为什么能创建窗口?为什么 Ctrl-C 有时不能退出程序? - 为什么有的程序能把组里服务器的 128 个 CPU 用满? - 你每天都在用的东西, 你实现不出来 - 浏览器, 编译器, IDE, 游戏/外挂, 杀毒软件, 病毒... 《操作系统》带你补完 "编程" 的技术体系 - 悟性好: 学完课程就在系统方向 "毕业" - 具有编写一切 "能写出来" 程序的能力 (具备阅读论文的能力) - 悟性差: 内力大增 - 可能工作中的某一天想起上课提及的内容 == (What): 到底什么是操作系统? === 什么是操作系统? _Operating System: A body of software, in fact, that is responsible for making it easy to run programs (even allowing you to seemingly run many at the same time), allowing programs to share memory, enabling programs to interact with devices, and other fun stuff like that. (OSTEP)_ "programs" 就完了?那么多复杂的程序呢! "shared memory, interact with devices, ..."? "管理软/硬件资源, 为程序提供服务" 的程序? === 理解操作系统 "精准" 的教科书定义毫无意义 (但作者得被迫去写) - 定义是 "全部" 的一个极简表达 - 如果只想 "了解", 那可以读一下定义 - 如果想学习操作系统, 就必须理解 "全部" 操作系统 "全部" 的 overview: #tip("Tip")[ 这门课我们不需要太多关注定义,而是需要重点去关注*全部* ] - 操作系统如何从一开始变成现在这样的? - 三个重要的线索 - 硬件 (计算机) - 软件 (程序) - 操作系统 (管理硬件和软件的软件) === 复习: 理解计算机硬件 (电路) 前导知识: 数字逻辑电路/计算机系统基础 - 一个极简的公理系统 (导线, 时钟, 逻辑门, 触发器) - 建立在公理体系上的数字系统设计 (包括计算机) - 前导课程目标: 能根据需求实现数字系统 ==== Logisim Demo 数字电路模拟器 - 基本构件: wire, reg, NAND, NOT, AND, NOR - 每一个时钟周期 - 先计算 wire 的值 - 在周期结束时把值锁存至 reg 会编程, 你就拥有全世界! - 同样的方式可以模拟任何数字系统 (包括计算机系统) - 同时还体验了 UNIX 哲学 - Make each program do one thing well - Expect the output of every program to become the input to another === 复习: 理解计算机软件 (程序) 前导课程: C 程序设计/计算机系统基础 - 高级语言代码 -> 指令序列 -> 二进制文件 -> 处理器执行 - 前导课程目标: 能将需求实现; 掌握工具使用; 阅读汇编指令 === #link("..\demo\01_demo\rvemu\rvemu.c")[ RVEmu Demo ] 如果你的指令和设备实现得够完善, 就能直接启动 Linux === 理解操作系统 本课程讨论狭义的操作系统 - 操作系统: 硬件和软件的中间层 - 对单机 (多处理器) 作出抽象 - 支撑多个程序执行 - 学术界谈论的 "操作系统" 是更广义的 "System" - 例子: 对多台计算机抽象 (分布式系统) 理解操作系统 - 理解硬件 (计算机) 和软件 (程序) 的发展历史 - 夹在中间的就是操作系统 ==== ENIAC: 1946.2.14 ==== ENIAC: 1946.2.14 "图灵机" 的数字电路实现 执行完一条指令后, 可以根据结果跳转到任意一条指令 (用物理线路 "hard-wire") 重编程需要重新接线: Emulator and Programming the ENIAC ===== 1940s 的计算机硬件 电子计算机的实现 - 逻辑门: 真空电子管 - 存储器: 延迟线 (delay lines) - 输入/输出: 打孔纸带/指示灯 打印平方数, 素数表, 计算弹道... - 解释了《程序设计》教课书上经典习题的来源 (是时候改一改了) - 大家还在和真正的 "bugs" 战斗 没有操作系统。 能把程序放上去就很了不起了 - 程序直接用指令操作硬件 - 不需要画蛇添足的程序来管理它 ===== 1950s 的计算机硬件 更快更小的逻辑门 (晶体管), 更大的内存 (磁芯), 丰富的 I/O 设备 I/O 设备的速度已经严重低于处理器的速度, 中断机制出现 (1953) 更复杂的通用的数值计算 - 高级语言和 API 诞生 (Fortran, 1957): 一行代码, 一张卡片 - 80 行的规范沿用至今 (细节: 打印机会印刷本行代码) Fortran 已经 "足够好用" 自然科学, 工程机械, 军事...对计算机的需求暴涨 ```fortran C---- THIS PROGRAM READS INPUT FROM THE CARD READER, C---- 3 INTEGERS IN EACH CARD, CALCULATE AND OUTPUT C---- THE SUM OF THEM. 100 READ(5,10) I1, I2, I3 10 FORMAT(3I5) IF (I1.EQ.0 .AND. I2.EQ.0 .AND. I3.EQ.0) GOTO 200 ISUM = I1 + I2 + I3 WRITE(6,20) I1, I2, I3, ISUM 20 FORMAT(7HSUM OF , I5, 2H, , I5, 5H AND , I5, * 4H IS , I6) GOTO 100 200 STOP END ``` 库函数 + 管理程序排队运行的调度代码。 写程序 (戳纸带), 跑程序都是非常费事的 - 计算机非常贵 ($50,000−$1,000,000), 一个学校只有一台 - 算力成为一种服务: 多用户轮流共享计算机, operator 负责调度 操作系统的概念开始形成 - 操作 (operate) 任务 (jobs) 的系统 (system) - "批处理系统" = 程序的自动切换 (换卡) + 库函数 API - Disk Operating Systems (DOS) - 操作系统中开始出现 "设备", "文件", "任务" 等对象和 API ===== 1960s 的计算机硬件 集成电路, 总线出现 - 更快的处理器 - 更快, 更大的内存; 虚拟存储出现 - 可以同时载入多个程序而不用 "换卡" 了 - 更丰富的 I/O 设备; 完善的中断/异常机制 更多的高级语言和编译器出现 - COBOL (1960), APL (1962), BASIC (1965) - <NAME> 和 <NAME> 在 1975 年实现了 Altair 8800 上的 BASIC 解释器 计算机科学家们已经在今天难以想象的计算力下开发惊奇的程序 能载入多个程序到内存且调度它们的管理程序。 为防止程序之间形成干扰, 操作系统自然地将共享资源 (如设备) 以 API 形式管理起来 - 有了进程 (process) 的概念 - 进程在执行 I/O 时, 可以将 CPU 让给另一个进程 - 在多个地址空间隔离的程序之间切换 - 虚拟存储使一个程序出 bug 不会 crash 整个系统 操作系统中自然地增加进程管理 API - 既然可以在程序之间切换, 为什么不让它们定时切换呢? - Multics (MIT, 1965): 现代分时操作系统诞生 ===== 1970s+ 的计算机硬件 集成电路空前发展, 个人电脑兴起, "计算机" 已与今日无大异 - CISC 指令集; 中断, I/O, 异常, MMU, 网络 - 个人计算机 (PC 机), 超级计算机... PASCAL (1970), C (1972), ... - 今天能办到的, 那个时代已经都能办到了——上天入地, 图像声音视频, 人工智能... - 个人开发者 (Geek Network) 走上舞台 分时系统走向成熟, UNIX 诞生并走向完善, 奠定了现代操作系统的形态。 - 1973: 信号 API, 管道 (对象), grep (应用程序) - 1983: BSD socket (对象) - 1984: procfs (对象)... - UNIX 衍生出的大家族 - 1BSD (1977), GNU (1983), MacOS (1984), AIX (1986), Minix (1987), Windows (1985), Linux 0.01 (1991), Windows NT (1993), Debian (1996), Windows XP (2002), Ubuntu (2004), iOS (2007), Android (2008), Windows 10 (2015), ... ===== 今天的操作系统 通过 "虚拟化" 硬件资源为程序运行提供服务的软件。 空前复杂的系统之一 - 更复杂的处理器和内存 - 非对称多处理器 (ARM big.LITTLE; Intel P/E-cores) - Non-uniform Memory Access (NUMA) - 更多的硬件机制 Intel-VT/AMD-V, TrustZone/SGX, TSX, ... - 更多的设备和资源 - 网卡, SSD, GPU, FPGA... - 复杂的应用需求和应用环境 - 服务器, 个人电脑, 智能手机, 手表, 手环, IoT/微控制器... === 课程内容概述 操作系统: 软件硬件之间的桥梁 - 本课程中的软件: 多线程 Linux 应用程序 - 本课程中的硬件: 现代多处理器系统 (设计/应用视角,自顶而下) 操作系统为应用提供什么服务? - *操作系统 = 对象 + API* - 课程涉及: POSIX + 部分 Linux 特性 (实现/硬件视角,自底而上) 如何实现操作系统提供的服务? - *操作系统 = C 程序* - 完成初始化后就成为 interrupt/trap/fault handler - 课程涉及: xv6, 自制迷你操作系统 == (How): 怎么学操作系统? === 对 "教学" 的一些思考 #tip("Tip")[ _热情且聪明的学生...听说相对论, 量子力学...但是, 当他们学完两年以前那种课程 (斜面, 静电这样的内容) 后, 许多人就泄气了_ ——The Feynman Lectures on Physics ] #tip("Tip")[ _Education is not the filling of a pail, but the lighting of a fire_——<NAME> ] 我们读书的时代 (2009): 大家都说操作系统很难教 - 使用~~豆瓣评分高达 5.7/10~~ 的 "全国优秀教材" - 没有正经的实验 (16-bit code), 错误的工具链, 调试全靠猜 - 为了一点微不足道的分数内卷, 沾沾自喜, 失去 integrity - 长此以往, 脖子都要被卡断了 - 同时, 课堂教学是最容易被改善的 - 这门课告诉你可以变得更强, 真正的强 === 学习操作系统: 现代方法 读得懂的教科书和阅读材料:Operating Systems: Three Easy Pieces 问题驱动, 用代码说话 - Demo 小程序, 各类系统工具 (strace, gdb, ...) 的使用 - xv6-riscv, AbstractMachine - RTFM, STFW, RTFSC (F can be a colorful word) === Prerequisites 计算机专业学生必须具备的核心素质。 是一个合格的操作系统用户 1. 会 STFW/RTFM 自己动手解决问题 2. 不怕使用任何命令行工具 3. vim, tmux, grep, gcc, binutils, ... 不怕写代码 - 能管理一定规模 (数千行) 的代码 - 能在出 bug 时默念 "机器永远是对的, 我肯定能调出来的" - 然后开始用正确的工具/方法调试 #tip("Tip")[ 给 "学渣" 们的贴心提示: 不要尝试 "架空学习", 回头补基础 ] === 0. 学术诚信 (Academic Integrity) Academic integrity 不是底线, 而是 "自发的要求" 对 "不应该做的事情" 有清楚的认识 不将代码上传到互联网 主动不参考别人完成的实验代码 不使用他人测试用例 (depends) 有些行为可能使你得到分数, 但失去应有的训练 === 1. 成为 Power User 感到 Linux/PowerShell/... 很难用? - 没有建立信心, 没有理解基本逻辑:计算机科学自学指南 - 没有找对材料/没有多问 "能不能再做点什么":Baidu v.s. Google/Github/SO v.s. ChatGPT - 没有用对工具 (man v.s. tldr; 该用 IDE 就别 Vim):过了入门阶段, 都会好起来 === 2. 学会写代码 写代码 = 创造有趣的东西 - 命令行 + 浏览器就是全世界 #tip("Tip")[ 我们还有 `sympy`, `sage`, `z3`, `rich`, ... 呢 ] - 不需要讲语言特性, 设计模式, ...:编就对了; 你自然而然会需要它们的 === 最重要的: Get Your Hands Dirty #tip("Tip")[ 听课看书都不重要。独立完成编程作业即可理解操作系统。 ] 应用视角 (设计): Mini Labs x 6(使用 OS API 实现 "黑科技" 代码) 硬件视角 (实现): OS Labs x 5(自己动手实现一个真正的操作系统) 全部 Online Judge: - 代码不规范 -> `-Wall` `-Werror` 编译出错 - 代码不可移植 -> 编译/运行时出错: `int x = (int)&y;` - 硬编码路径/文件名 -> 运行时出错: `open("/home/a/b", ...)` == 编程实践 === Demo:数学概念的探索与发现 ```py = Life is short; you need Python. import z3 import numpy as np import sympy as sp import matplotlib.pyplot as plt x = sp.symbols('x') def plot(f, points=[], draw_label=True, draw_points=True): """Plot a sympy symbolic polynomial f.""" xmin = min([x_ for x_, _ in points], default=-1) - 0.1 xmax = max([x_ for x_, _ in points], default=1) + 0.1 xs = np.arange(xmin, xmax, (xmax - xmin) / 100) ys = [f.subs(x, x_) for x_ in xs] plt.grid(True) plt.plot(xs, ys) if draw_points: plt.scatter( [x_ for x_, y_ in points], [y_ for x_, y_ in points], ) if draw_label: for x_, y_ in points: plt.text(x_, y_, f'$({x_},{y_})$', va='bottom', ha='center') plt.title(f'$y = {sp.latex(f)}$') ``` #tip("Tip")[ - `z3`是一个求解任何一个逻辑方程组的工具(推箱子, 数独...) - `sympy`符号计算的库. ] 用`sympy`做插值拟合. ```py def interpolate(n=0, xs=[], ys=[]): """Return a polynomial that passes through all given points.""" n = max(n, len(xs), len(ys)) if len(xs) == 0: xs = [sp.symbols(f'x{i}') for i in range(n)] if len(ys) == 0: ys = [sp.symbols(f'y{i}') for i in range(n)] vs = [sp.symbols(f'a{i}') for i in range(n)] power = list(range(n)) cons = [ sum( v * (x_ * k) for v, k in zip(vs, power) ) - y for x_, y in zip(xs, ys) ] sol = list(sp.linsolve(cons, vs))[0] f = (sum( v * (x * k) for v, k in zip(sol, power) )) return f = ----------------------------------- xs = [-1, 0, 1, 2, 3] ys = [-1, 2, 1, 4, 5] f = interpolate(xs=xs, ys=ys) plot(f, list(zip(xs, ys)), True) = ----------------------------------- n = 10 xs = np.arange(-1, 1, 1 / n) ys = np.sin(xs * n) f = interpolate(xs=xs, ys=ys) plot(f, list(zip(xs, ys)), draw_points=True, draw_label=False) f = ----------------------------------- sp.simplify(interpolate(3)) ``` ==== 列表推导式 ```py [expression for item in iterable if condition] ``` 列表推导式按照以下步骤操作: - 从可迭代对象中逐个取出元素。 - 将每个元素应用于表达式,生成一个新的元素。 - 根据条件表达式过滤元素,只保留满足条件的元素。 - 将符合条件的元素组成一个新的列表。 ```py squares = [x*2 for x in range(10)] = 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = [x for x in numbers if x % 2 == 0] = 输出: [2, 4, 6, 8, 10] string = "Hello World" upper_letters = [char for char in string if char.isupper()] = 输出: ['H', 'W'] ``` ==== 格式化字符串 使用 f-strings(格式化字符串字面值): 在 Python 3.6+ 版本中引入了 f-strings,它允许在字符串前加上 f 前缀,并使用 {} 占位符来嵌入表达式。示例: ```py name = 'Charlie' age = 35 print(f'My name is {name} and I am {age} years old.') ``` === logisim demo ```c #define PRINT(X) printf(#X " = %d; ", X) ``` 其中 `#` 操作符是字符串化操作符,它将宏参数 `X` 转换为一个字符串。当宏被调用时,`#X` 将会被替换为参数 `X` 的字符串表示。 ```c int num = 10; PRINT(num); // printf("num" " = %d; ", num); ``` ```py import fileinput DISPLAY = ''' AAAAAAAAA FF BB FF BB FF BB FF BB GGGGGGGG EE CC EE CC EE CC EE CC DDDDDDDDD ''' = STFW: ANSI Escape Code CLEAR = '\033[2J\033[1;1f' BLOCK = { 0: '\033[37m░\033[0m', 1: '\033[31m█\033[0m', } for line in fileinput.input(): = Load "A=0; B=1; ..." to current context exec(line) = Render the seven-segment display pic = DISPLAY for seg in set(DISPLAY): if seg.isalpha(): val = globals()[seg] = 0 or 1 pic = pic.replace(seg, BLOCK[val]) = Clear screen and display print(CLEAR + pic) ``` #tip("Tip")[ - `CLEAR` 是一个 ANSI 转义码,用于清除控制台屏幕,并将光标移动到屏幕左上角;`BLOCK` 是一个字典,它将数字 0 和 1 映射到不同的颜色块,其中数字 0 对应着浅色的块,数字 1 对应着深色的块。 - `fileinput.input()` 循环遍历输入的行。在每次循环中,代码使用 `exec()` 函数执行当前行的代码,将其中定义的变量加载到当前上下文中。这样,可以通过在输入中设置变量的值来控制七段显示器的显示。 - 通过 `globals()` 函数获取全局变量中与该字母对应的变量(例如 `A`、`B`、`C`、`D`、`E`、`F`、`G`),并根据变量的值选择对应的颜色块进行替换。 ] === RVEmu demo #code(caption: [RVEmu demo])[ ```c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> typedef uint32_t u32; typedef struct { u32 op : 7, rd : 5, f3 : 3, rs1 : 5, rs2 : 5, f7 : 7; } inst_t; typedef struct { u32 on, x[32]; } CPUState; static inline u32 sext(u32 val, u32 n) { // Sign extend n-bit integer val to 32-bit u32 mask = ~((1 << n) - 1); u32 set = (val >> (n - 1)) & 1; u32 ret = set ? (val | mask) : val; return ret; } // Uncore: // inst_fetch - read an instruction from stdin // ebreak - hyper call: putchar/putd/exit static inline bool inst_fetch(inst_t *in) { union { inst_t i; u32 u; } u; int r = scanf("%x", &u.u); *in = u.i; return r > 0; } static inline void ebreak(CPUState *cpu) { switch (cpu->x[10]) { case 1: { putchar(cpu->x[11]); break; } case 2: { printf("%d", cpu->x[11]); break; } case 3: { cpu->on = false; break; } default: assert(0); } } int main(int argc, char *argv[]) { CPUState cpu = {.on = 1, .x = {0}}; // The RESET state for (int i = 0; argv[i + 1] && i < 8; i++) { cpu.x[10 + i] = atoi(argv[i + 1]); // Set a0-a7 to arguments } inst_t in; while (cpu.on && inst_fetch(&in)) { // For each fetched instruction, execute it following the RV32I spec u32 op = in.op, f3 = in.f3, f7 = in.f7; u32 imm = sext((f7 << 5) | in.rs2, 12), shamt = in.rs2; u32 rd = in.rd, rs1_u = cpu.x[in.rs1], rs2_u = cpu.x[in.rs2], res = 0; #define __ else if // Bad syntactic sugar! if (op == 0b0110011 && f3 == 0b000 && f7 == 0b0000000) res = rs1_u + rs2_u; __(op == 0b0110011 && f3 == 0b000 && f7 == 0b0100000) res = rs1_u - rs2_u; __(op == 0b0010011 && f3 == 0b000) res = rs1_u + imm; __(op == 0b0010011 && f3 == 0b001 && f7 == 0b0000000) res = rs1_u << shamt; __(op == 0b0010011 && f3 == 0b101 && f7 == 0b0000000) res = rs1_u >> shamt; __(op == 0b1110011 && f3 == 0b000 && rd == 0 && imm == 1) ebreak(&cpu); else assert(0); if (rd) cpu.x[rd] = res; } } ``` ]
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/knowledge/rings.typ
typst
#import "../cfg.typ": cfg #show: cfg = Rings $(K, +, *)$ is a ring $:=$ + $(K, +)$ is an abelian group. + $K$ is closed under $*$. + $a(b + c) = a b + a c$. + $(b + c)a = b a + c a$. $|K| > 1 -> 0 != 1$. *Binomial theorem:* $(a + b)^n = sum_(i = 0)^n binom(n, i) a^i b^(n - i)$ in a commutative ring. A ring is integral $:=$ it's commutative, associative, has a unit, more than one element and doesn't have zero divisors. $(a, b) tilde (a', b') := a b' = a' b$. A field of fractions of an integral ring $K := op("quot") K :=$ a field of those pairs where the second element of each pair is nonzero.
https://github.com/i-am-wololo/cours
https://raw.githubusercontent.com/i-am-wololo/cours/master/main/i21/pilesfiles.typ
typst
= Piles et Files = Piles Les piles (ou stack) sont des structures de donnees
https://github.com/YXalix/resume
https://raw.githubusercontent.com/YXalix/resume/main/resume.typ
typst
#import "template.typ": * // 设置图标, 来源: https://fontawesome.com/icons/ // 如果要修改图标颜色, 请手动修改 svg 文件中的 fill="rgb(38, 38, 125)" 属性 #let faAward = icon("fa-award.svg") #let faBuildingColumns = icon("fa-building-columns.svg") #let faCode = icon("fa-code.svg") #let faEnvelope = icon("fa-envelope.svg") #let faGithub = icon("fa-github.svg") #let faGraduationCap = icon("fa-graduation-cap.svg") #let faLinux = icon("fa-linux.svg") #let faPhone = icon("fa-phone.svg") #let faWindows = icon("fa-windows.svg") #let faWrench = icon("fa-wrench.svg") #let faresearch = icon("research.png") #let idCard = icon("mentoring.png") #let fawechat = icon("wechat.png") #let fainfo = icon("info.png") #let fahome = icon("home.svg") // 主题颜色 #let themeColor = rgb(0, 0, 0) // 设置简历选项与头部 #show: resume.with( // 字体基准大小 size: 10.5pt, // 标题颜色 themeColor: themeColor, // 控制纸张的边距 top: 0.4cm, bottom: 2cm, left: 1cm, right: 1cm, // 如果不需要头像,则将下面的参数注释或删除 photograph: "正式照.JPEG", photographWidth: 10em, gutterWidth: 3.5em, )[ #align(left + bottom, text(20pt)[ *周海鹏* ]) #person( color: themeColor, infoitem( icon: faGraduationCap, content: "预备党员", ), infoitem( icon: fahome, content: "浙江 · 杭州", ), infoitem( icon: faBuildingColumns, content: "南京航空航天大学", ), infoitem( icon: faPhone, content: "18851893975" ), infoitem( icon: faEnvelope, content: "<EMAIL>", ), infoitem( icon: faGithub, content: "github.com/YXalix", ), ) ] // #align(left, text(12pt)[ // *_技术栈_*: // Linux, // Rust, C/C++, Python, // UE4/5, Flutter, Git // ]) == #faGraduationCap 教育背景 #education( date[ *2022.09-2025.04* ], [ *南京航空航天大学 | 计算机科学与技术专业 | 硕士* ], [ #set align(left) 本校保研至原专业, 主要研究方向为动态联盟博弈, 考虑在无线传输的物理层安全场景下, 引入第三方智能反射服务提供方后, 研究合法用户、窃听者、第三方智能反射面之间的动态联盟关系。目前已有一篇CCF-C论文, 一篇TWC期刊在投; ] ) #education( date[ *2018.09-2022.06* ], [ *南京航空航天大学 | 计算机科学与技术专业 | 本科* ], [ #set align(left) 主修平均绩点4/5, 保研排名前10%, 具有良好的计算机基础知识; 有基于Futter的全栈开发经验; ] ) == #faWrench 专业技能 - 熟悉Rust开发, 熟悉所有权, trait机制等; - 熟悉C++11, Python开发, 熟练使用STL, 了解C++11特性; - 熟悉操作系统的基本原理, 包括进程管理, 内存管理, 内核锁, 文件系统, IPC机制等; - 熟悉UXIX/Linux环境, 熟悉常用命令, 了解strace等工具的使用; - 了解Git, Cmake, Makefile, GDB等常用工具的使用; == #idCard 实习经历 #internship( date[*2024.06-至今*], [* 华为 | 2012欧拉庞加莱实验室 | 操作系统开发 *], [ 实习期间在欧拉内存虚拟化部门, 完成EulerOS kenerl memory alloc/free tracer modules编写, 以及对应ARM下的AT脚本编写;实现内存NUMA的pre-offline特性支持; 技术栈 C, Python; ] ) #v(-0.1em) #internship( date[*2021.07-2021.09*], [* 腾讯 | IEG魔方工作室 | 游戏客户端开发 *], [ 实习期间独立设计实现一款以深度环境交互为题的PC端游戏, 游戏机制为3D场景2D化, 通过横版移动以及视角切换抵达目的地. 游戏采用UE4开发, 并应用了GAN来程序化生成随机地图, 共制作约500张场景数据训练, 完成UE4的torch模型加载;技术栈 UE4 C++, Python; ] ) == #faCode 项目经历 #item( date[ *2024.01-2024.06* ], [], [ *CICV | 内核开发* ], [ 项目实习期间, 作为队长带领团队完成了基于Starry的FastDDS移植工作, 我主要负责FastDDS交叉编译至RISC-V架构, Starry网络模块BUG定位与解决, Starry在ARM架构下的FastDDS移植(不同架构下页表不同导致的BUG), 累计贡献4个相关PR; 个人实习期间, 负责重新设计实现Starry的Futex功能模块, 并形成了一个相对独立的内核模块; ] ) #item( date[ *2023.12-2024.01* ], [], [ *minicc编译器开发* ], [ 基于 Rust 语言实现的 C 语言子集编译器,支持将 C 语言子集编译为 RISC-V 汇编语言, 实现 C 语言子集的基本功能, 先使用Rust实现链表来存储AST, 后续重构代码采用enum来存储AST, 增加中间代码生成IR; ] ) #item( date[ *2023.10-2023.12* ], [], [ * 清华大学 Open-Source OS Training Comp 2023* ], [ 针对开源操作系统rCore, 通过增加系统调用以及死锁检测的方式来理解内核的实际运行, 包括任务调度, 内存分配等; 并为rCoreOS增加虚拟文件系统层, 添加支持 FAT32 文件系统的独立内核模块. 获得优秀 (前1%); ] ) // #item( // date[ *2021.09 - 2021.12* ], // [ *基于Flutter的APP开发* ], // [ *课程项目* ], // ) // #tech[ Flutter, Dart, python+flask ] // 使用flutter进行前端开发, 实现一个跨平台的校园活动角APP, 项目难点在于当时fluter比较新并且Dart语言需要新学, 在使用该框架的时候也没有资料, 只能啃官方文档。 // == #faAward 荣誉 // #item( // [ *优秀学生干部* ], // [ ], // date[ 2022 年 09 月 – 2023 年 11 月 ] // ) // #item( // [ *优秀学生奖学金* ], // [ ], // date[ 2018 年 11 月 – 2021 年 11 月 ] // ) // #item( // [ *三好学生* ], // [ ], // date[ 2018 年 11 月 – 2021 年 11 月 ] // ) // == #faresearch 研究经历 // #researchitem( // [*面向物理层安全感知智能反射通信的重复联盟博弈研究*], // date[2022 年 12 月 - 至今] // ) // 主要是物理层安全方面的博弈, 考虑存在第三方智能反射服务提供方的情况下, 研究合法用户、窃听者、智能反射面的动态联盟关系。 // 《A Three-Party Repeated Coalition Formation Game for PLS in Wireless Communications with IRSs》WCNC24接收 == #faresearch 个人总结 热爱技术, 自主学习能力强, 喜欢钻研底层原理 // #v(-4em)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/frac-01.typ
typst
Other
// Test parenthesis removal. $ (|x| + |y|)/2 < [1+2]/3 $
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/text/em.typ
typst
// Test font-relative sizing. --- text-size-em-nesting --- #set text(size: 5pt) A // 5pt #[ #set text(size: 2em) B // 10pt #[ #set text(size: 1.5em + 1pt) C // 16pt #text(size: 2em)[D] // 32pt E // 16pt ] F // 10pt ] G // 5pt --- text-size-em --- // Test using ems in arbitrary places. #set text(size: 5pt) #set text(size: 2em) #set square(fill: red) #let size = { let size = 0.25em + 1pt for _ in range(3) { size *= 2 } size - 3pt } #stack(dir: ltr, spacing: 1fr, square(size: size), square(size: 25pt))
https://github.com/chaosarium/typst-templates
https://raw.githubusercontent.com/chaosarium/typst-templates/main/examples/slides-simple.typ
typst
#import "../slides-simple/lib.typ": * #show: slides.with( title: [Some Random Presentation], subtitle: [Making slides in Typst], date: [21 October 2024], authors: [list of authors], ratio: 16/9, layout: "medium", title-color: rgb("#4a1c8a"), footer: true, slides_counter: true, toc: true, // code-styling: true, font_size: 11pt, font: "Libertine" ) = Style Testing == Text #lorem(20)#footnote[hello this is footnote] Something *bold* and _italic_ and `raw text`. `raw` are good - List - With nesting - And more nesting - And more? / Term: #[ aristenairsntiarnstei \ ieanrst \ iaenrst ] #lorem(100) / Definition: aristenairsnt == More text ```sml fun fact 0 = 1 | fact n = n * fact (n - 1) ``` Some code definitely worked... Some math shoudl also work then $ E = m c ^2 $ == Table #table( columns: 4, [], [Exam 1], [Exam 2], [Exam 3], [John], [], [a], [], [Mary], [], [a], [a], [Robert], [b], [a], [b], ) = Something == Now this is a very long title and I don't know what the template will do if it wants to handle it hahahahaha == Hi Something = Something hello == Hi Something = bibliography == Citations should work? Hmmm @goldbergComprehensive. == Bib #bibliography("pubs.bib")
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fireside/1.0.0/.demo/demo_long.typ
typst
Apache License 2.0
#import "@preview/fireside:1.0.0": * #set page(numbering: "1") #show: fireside.with( title: [Anakin \ Skywalker], from-details: [ Appt. x, \ <NAME>, \ Tatooine \ <EMAIL> \ +999 xxxx xxx ], to-details: [ <NAME>ine \ 500 Republica, \ Ambassadorial Sector, Senate District, \ Galactic City, \ Coruscant ], ) Dear Emperor, You will _never_ guess what happened to me last week-end! #lorem(200) #lorem(220) #lorem(180) Hence the scratch on my helmet. <NAME>
https://github.com/EGmux/TheoryOfComputation
https://raw.githubusercontent.com/EGmux/TheoryOfComputation/master/unit2/decidibilidade.typ
typst
#set heading(numbering: "1.")
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/foundations/dict.typ
typst
// Test dictionaries. --- dict-basic-syntax --- // Empty #(:) // Two pairs and string key. #let dict = (normal: 1, "spacy key": 2) #dict #test(dict.normal, 1) #test(dict.at("spacy key"), 2) --- dict-fields --- // Test field on dictionary. #let dict = (nothing: "ness", hello: "world") #test(dict.nothing, "ness") #{ let world = dict .hello test(world, "world") } --- dict-missing-field --- // Error: 6-13 dictionary does not contain key "invalid" #(:).invalid --- dict-bad-key --- // Error: 3-7 expected string, found boolean // Error: 16-18 expected string, found integer #(true: false, 42: 3) --- dict-duplicate-key --- // Error: 24-29 duplicate key: first #(first: 1, second: 2, first: 3) --- dict-duplicate-key-stringy --- // Error: 17-20 duplicate key: a #(a: 1, "b": 2, "a": 3) --- dict-bad-expression --- // Simple expression after already being identified as a dictionary. // Error: 9-10 expected named or keyed pair, found identifier #(a: 1, b) --- dict-leading-colon --- // Identified as dictionary due to initial colon. // The boolean key is allowed for now since it will only cause an error at the evaluation stage. // Error: 4-5 expected named or keyed pair, found integer // Error: 17 expected expression #(:1 b:"", true:) --- spread-into-dict --- #{ let x = (a: 1) let y = (b: 2) let z = (a: 3) test((:..x, ..y, ..z), (a: 3, b: 2)) test((..(a: 1), b: 2), (a: 1, b: 2)) } --- spread-array-into-dict --- // Error: 3-11 cannot spread array into dictionary #(..(1, 2), a: 1) --- dict-at-lvalue --- // Test lvalue and rvalue access. #{ let dict = (a: 1, "b b": 1) dict.at("b b") += 1 dict.state = (ok: true, err: false) test(dict, (a: 1, "b b": 2, state: (ok: true, err: false))) test(dict.state.ok, true) dict.at("state").ok = false test(dict.state.ok, false) test(dict.state.err, false) } --- dict-at-missing-key --- // Test rvalue missing key. #{ let dict = (a: 1, b: 2) // Error: 11-23 dictionary does not contain key "c" and no default value was specified let x = dict.at("c") } --- dict-at-default --- // Test default value. #test((a: 1, b: 2).at("b", default: 3), 2) #test((a: 1, b: 2).at("c", default: 3), 3) --- dict-insert --- // Test insert. #{ let dict = (a: 1, b: 2) dict.insert("b", 3) test(dict, (a: 1, b: 3)) dict.insert("c", 5) test(dict, (a: 1, b: 3, c: 5)) } --- dict-remove-with-default --- // Test remove with default value. #{ let dict = (a: 1, b: 2) test(dict.remove("b", default: 3), 2) } #{ let dict = (a: 1, b: 2) test(dict.remove("c", default: 3), 3) } --- dict-missing-lvalue --- // Missing lvalue is not automatically none-initialized. #{ let dict = (:) // Error: 3-9 dictionary does not contain key "b" // Hint: 3-9 use `insert` to add or update values dict.b += 1 } --- dict-basic-methods --- // Test dictionary methods. #let dict = (a: 3, c: 2, b: 1) #test("c" in dict, true) #test(dict.len(), 3) #test(dict.values(), (3, 2, 1)) #test(dict.pairs().map(p => p.first() + str(p.last())).join(), "a3c2b1") #dict.remove("c") #test("c" in dict, false) #test(dict, (a: 3, b: 1)) --- dict-from-module --- // Test dictionary constructor #test(type(dictionary(sys).at("version")), version) #test(dictionary(sys).at("no-crash", default: none), none) --- dict-remove-order --- // Test that removal keeps order. #let dict = (a: 1, b: 2, c: 3, d: 4) #dict.remove("b") #test(dict.keys(), ("a", "c", "d")) --- dict-temporary-lvalue --- // Error: 3-15 cannot mutate a temporary value #((key: "val").other = "some") --- dict-function-item-not-a-method --- #{ let dict = ( call-me: () => 1, ) // Error: 8-15 type dictionary has no method `call-me` // Hint: 8-15 to call the function stored in the dictionary, surround the field access with parentheses, e.g. `(dict.call-me)(..)` dict.call-me() } --- dict-item-missing-method --- #{ let dict = ( nonfunc: 1 ) // Error: 8-15 type dictionary has no method `nonfunc` // Hint: 8-15 did you mean to access the field `nonfunc`? dict.nonfunc() } --- dict-dynamic-duplicate-key --- #let a = "hello" #let b = "world" #let c = "value" #let d = "conflict" #test(((a): b), ("hello": "world")) #test(((a): 1, (a): 2), ("hello": 2)) #test((hello: 1, (a): 2), ("hello": 2)) #test((a + b: c, (a + b): d, (a): "value2", a: "value3"), ("helloworld": "conflict", "hello": "value2", "a": "value3")) --- issue-1338-dictionary-underscore --- #let foo = "foo" #let bar = "bar" // Error: 8-9 expected expression, found underscore // Error: 16-17 expected expression, found underscore #(foo: _, bar: _) --- issue-1342-dictionary-bare-expressions --- // Error: 5-8 expected named or keyed pair, found identifier // Error: 10-13 expected named or keyed pair, found identifier #(: foo, bar) --- issue-3154-dict-at-not-contained --- #{ let dict = (a: 1) // Error: 3-15 dictionary does not contain key "b" and no default value was specified dict.at("b") } --- issue-3154-dict-at-missing-default --- #{ let dict = (a: 1) test(dict.at("b", default: 0), 0) } --- issue-3154-dict-at-missing-mutable --- #{ let dict = (a: 1) // Error: 3-15 dictionary does not contain key "b" // Hint: 3-15 use `insert` to add or update values dict.at("b") = 9 } --- issue-3154-dict-at-missing-mutable-default --- #{ let dict = (a: 1) // Error: 3-27 dictionary does not contain key "b" // Hint: 3-27 use `insert` to add or update values dict.at("b", default: 0) = 9 } --- issue-3154-dict-syntax-missing --- #{ let dict = (a: 1) // Error: 8-9 dictionary does not contain key "b" dict.b } --- issue-3154-dict-syntax-missing-mutable --- #{ let dict = (a: 1) dict.b = 9 test(dict, (a: 1, b: 9)) } --- issue-3154-dict-syntax-missing-add-assign --- #{ let dict = (a: 1) // Error: 3-9 dictionary does not contain key "b" // Hint: 3-9 use `insert` to add or update values dict.b += 9 } --- issue-3232-dict-unexpected-keys-sides --- // Confusing "expected relative length or dictionary, found dictionary" // Error: 16-58 unexpected keys "unexpected" and "unexpected-too" #block(outset: (unexpected: 0.5em, unexpected-too: 0.2em), [Hi]) --- issue-3232-dict-unexpected-keys-corners --- // Error: 14-56 unexpected keys "unexpected" and "unexpected-too" #box(radius: (unexpected: 0.5em, unexpected-too: 0.5em), [Hi]) --- issue-3232-dict-unexpected-key-sides --- // Error: 16-49 unexpected key "unexpected", valid keys are "left", "top", "right", "bottom", "x", "y", and "rest" #block(outset: (unexpected: 0.2em, right: 0.5em), [Hi]) // The 1st key is unexpected --- issue-3232-dict-unexpected-key-corners --- // Error: 14-50 unexpected key "unexpected", valid keys are "top-left", "top-right", "bottom-right", "bottom-left", "left", "top", "right", "bottom", and "rest" #box(radius: (top-left: 0.5em, unexpected: 0.5em), [Hi]) // The 2nd key is unexpected --- issue-3232-dict-empty --- #block(outset: (:), [Hi]) // Ok #box(radius: (:), [Hi]) // Ok
https://github.com/xdoardo/co-thesis
https://raw.githubusercontent.com/xdoardo/co-thesis/master/thesis/ris.typ
typst
#import "@local/summary:1.0.0": * #import "./includes.typ": * #set cite(style: "numerical") #show bibliography: set text(13pt) #show: summary.with( title: "Program Transformations in the Delay Monad", subtitle: "A Case Study for Coinduction via Copatterns and Sized Types", author: "<NAME>", figure: align(bottom, image("./figures/Minerva.png", width: 28%)), university: [University of Milan], department: [Department of Computer Science and Technology], degree: "Master of Science", msg: include "./msg.typ", supervisor: [Prof. <NAME>], year: [Academic Year 2022-2023], number: [num. 973597], ) = Summary Our objective is to define an _operational semantics_ for an _imperative language_ targeting an adequate _monad_ to model the desired _effects_, all in a _dependently typed_ _proof assistant_. This work, in a nutshell, is a case study to analyse how all these techniques work when put together. _Program transformations_ are the final end of our work. A program transformation is an operation that changes in some way an input program in some source language in another program in a target language. Examples of program transformations are the static analysis of the source code such as _constant folding_, _dead code elimination_, _register allocation_, _liveness analysis_ and many more @allen-catalogue. The kind of transformations just cited are _source to source_, that is, the transformation is a function from the input language and outputs a program in the same language. Another important program transformation are _compilers_ for which, in general, we often take the correctness for granted: in this case the transformation outputs, generally, a result in a different language, for example assembly code for an input in the C language. Having a formal statement that proves that the transformations operated on a program do not change the semantics of the source language is obviously a much desired feature, and many efforts in the literature have been in this direction. One of the most notable ones is CompCert @compcert, which has the objective of providing a formalized backend for (almost all of) the ISO C standard by providing a compiler where the majority of transformations (all, if we do not consider lexical analysis and printing to ASM as transformations) are either programmed in Caml or programmed and proved in Coq @coq. Our work draws inspiration from seminal works like @leroy-coinductive-bigstep and @danielsson-operational-semantics: both use _coinduction_ to define the semantics of the language, but do not make use of the same techniques we explore, namely sized types (which are not present in @danielsson-operational-semantics) and the use of the `Delay` monad proposed by Capretta @capretta-delay, which does not appear in @leroy-coinductive-bigstep. These two techniques together allow the definition of a functional interpreter which is then used throughout the work. The objective, then, is to implement program transformations: we chose two transformations as formally described by Nipkow in @concrete-semantics; once implemented, we show that the transformation either helps proving a theorem on the execution of the program (namely, that if the analysis validates the program its execution will not fail) or it is then proved that it does not change the result of the execution. #pagebreak() #bibliography("./db.bib")
https://github.com/sast-summer-training-2024/sast2024-neural-network
https://raw.githubusercontent.com/sast-summer-training-2024/sast2024-neural-network/master/slide.typ
typst
#import "@preview/touying:0.4.2": * #let s = themes.metropolis.register(aspect-ratio: "16-9", footer: [#counter(page).display() of #locate((loc) => {counter(page).final(loc).first()})]) #let s = (s.methods.info)( self: s, title: "(人工)神经网络", subtitle: "Artificial Neural Networks", date: "2024-8-4", institution: "SAST summer training", author: "王思图" ) #let (init, slides, touying-outline, alert, speaker-note) = utils.methods(s) #show: init #show strong: alert #let (slide, empty-slide, title-slide, new-section-slide, focus-slide) = utils.slides(s) #show: slides #new-section-slide("What is ANN?") #slide(title: "The positioning of ANN in the field of AI")[ #rect("人工智能"+rect("机器学习"+rect(" 统计机器学习"+rect("人工神经网络"))))][人工智能:智能主体(intelligent agent)的研究与设计。智能主体指一个可以观察周遭环境并作出行动以达致目标的系统][ 机器学习:对能通过经验自动改进的计算机算法的研究 统计机器学习:计算机系统通过运用数据及统计方法提高系统性能的机器学习 ][ 人工神经网络:一种模仿生物神经网络的结构和功能的数学模型,用于对函数进行估计或近似。能在外界信息的基础上改变内部结构,是一种自适应系统. ] #slide(title: "Definition of ANN")[ #block( fill: luma(230), inset: 8pt, radius: 4pt)[神经网络是由#alert[包含或不包含参数的简单处理单元]相互连接构成的#alert[大规模结构]。它能够#alert[将数据经过由连接和参数决定的流程]进行计算,将输入映射到输出。] ] #slide(title: "What can it do? What is its advantage?")[ = 能干什么? - 从数据中获取并保存信息(数据驱动任务) - 拥有结构化的、相对大量的结构化输入-输出对数据,有明确、可计算的性能评估指标 省流:常见的有分类、预测、生成任务 = 能干好什么? - 可以形成拥有大规模参数的结构:信息提取和保存能力强,泛化性能好 - 可扩展性:结构化的输入和输出,便于扩展和复用 - 非线性:从输入特征空间到输出特征空间的映射是非线性的 省流:可以做成很大规模,适合建模极为复杂且有大量结构化数据的问题 ] #new-section-slide("What is Machine Learning?") #slide(title: "Machine Learning Tasks")[ = Definition #block( fill: luma(230), inset: 8pt, radius: 4pt, "机器学习任务是由"+alert("模型M、经验E、任务T、性能量度P") + "组成的。 模型的学习是指"+alert("模型M通过得到经验E,在性能量度P意义下相对得到经验E并运行学习算法前在任务T上有所改进。 ") ) = Hint 在神经网络意义下,模型M即为神经网络本身,经验E为数据,性能量度P为损失函数,任务T为希望使用神经网络解决的机器学习问题。] #slide(title: "Machine Learning Tasks")[ = Example == 某个用于图像分类的神经网络模型的学习任务 - 任务T:正确分类输入的图像 - 模型M:这个神经网络 - 经验E:114514张标注了类别的图像数据 - 性能量度P:在某组给定的114张图片上的分类正确率 = teminology 在神经网络学习任务中,我们称使用数据作为经验E,对神经网络使用学习算法进行优化的过程为#alert[训练] ] #slide(title: "Formal Discription of Machine Learning Tasks")[ = 如何形式化地建模一个任务 考虑数据的生成过程。从统计学角度,我们认为数据是某一分布的某种采样。 = 统计机器学习的三个基础假设 1. 真实分布假设:认为数据符合某个#alert[确定的真实分布] 2. 独立同分布假设:认为数据是从真实分布中#alert[独立同分布采样]的 3. 低维流形假设:自然的#alert[原始数据是低维的流形]嵌入于原始数据所在的高维空间(因为我们无法通过有限空间和时间估计无穷维样本空间上的概率分布) ] #slide(title: "Data and Experience")[ = Definition #block( fill: luma(230), inset: 8pt, radius: 4pt, "对于某个样本空间已知而概率未知的概率空间"+$(Omega, cal(F), PP)$+",任务T定义为通过独立同分布的采样结果"+${X_i} ~ PP(x) " " i.i.d$+" 估计分布"+$PP$+"。我们称采样结果"+${X_i}$+"为"+alert()[数据] ) = Hint 在该定义下,经验E即为数据。经验E是指通过观察和分析得到的规律、模式和信息。我们注意到数据中确实包含了这些信息。 ] #slide(title: "Performance Metrics and Loss Functions")[ = Why we need Loss Functions 请为以下翻译结果打分:#block( fill: luma(230),)[参考译文:故事从洋务运动说起,蒸汽机和内燃机进入中国。这些技术来自西方,归洋鬼子管的。殖民地的人民受洋鬼子的奴役,机械需要地下产的煤和石油来驱动运转,大英帝国的维多利亚女王来管着他们。你以为我跟你闹着玩呢。]#block( fill: luma(230),)[待测译文:你有这么高速运转的机械进入中国,记住我给出的原理,小的时候,就是研发人,就研发这个东西的原理是阴间政权管,你知道为为什么有生灵给他运转先位,还有还有专门饲养这个,为什么地下产这种东西,他管着他是五世同堂旗下子孙,我你以为我跟你闹着玩呢。] ] #slide(title: "Performance Metrics and Loss Functions")[ 我们需要一个能够不需要人类参与的性能度量算法,以便神经网络自行迭代而无需人类的干预从而显著提升效率。 由于人类经验的复杂性,我们通常只能够近似地评估模型的性能。在神经网络学习任务中,性能量度P被称为损失函数 = Definition #block( fill: luma(230), )[对于给定的模型M,和给定的经验E,损失函数定义为函数$cal(L):(M,E) -> RR$,#alert()[损失函数值越大,代表人类认为模型M在任务T上的表现与经验E的表现差距越大]] = Example 在图像分类任务中,$cal(L)(M,E)$可以为在某一组标注好类别图像数据上,模型在预测这组图像类别时的错误率。 ] #slide(title: "Performance Metrics and Test Set")[ = Why we need Test Set 在神经网络的评估中,一个重要的指标是其泛化能力,即对于在经验E没有涉及的、同时位于任务T的样本空间范围内的点的估计效果。 通常我们会从训练数据中单独分出一小部分,在训练时不作为样本对模型进行训练,并评估模型在这些样本上的性能。 我们称 #alert[在训练时作为样本对模型进行训练的数据集合为数据集,分出来的那一小部分为测试集]。 通常,为了得知模型在训练过程中的性能变化趋势,我们还会从测试集中分出一小部分作为#alert[验证集],在训练中途多次在验证集上测试模型的性能表现。 ] #new-section-slide("Construction of ANN") #slide(title:"Construction of ANN")[ 我们在第一节强调了神经网络构成的两个部分:带参数或不带参数的简单结构,以及它们的连接。在本节中将以感知机为例详细说明这两部分。 ] #slide(title:"Perceptron")[ 线性感知机算法(PLA)1957年由<NAME>提出。感知机是二分类的线性分类模型,其输入为实例的特征向量,输出为实例的类别,取值为+1和-1。 #block( fill: luma(230), inset: 8pt, radius: 4pt, )[perceptron: $ f(arrow(x)) = s i g n(arrow(w)^T arrow(x) + b) $ where $w,x in RR^n,b in RR$] 显然,这是一个含参数$w$的,且能够将输入根据参数$w$唯一映射到输出的简单结构。 感知机是神经网络中最常使用、最简单的含参结构。虽然感知机只能进行简单的线性可分分类问题,但通过连接大量感知机,以及更换符号函数为其他非线性函数,我们可以构造出复杂的结构。 ] #slide(title: "Multilayer Perceptron - MLP")[ 多层感知机是通过感知机的拼接组成的结构。它是最简单也是最重要的神经网络结构。这个结构在几乎所有的现代深度神经网络中都存在。 #block( fill: luma(230), inset: 8pt, radius: 4pt, )[multiple layer perceptron: $ f(arrow(x)) = f_N circle.tiny dots.c circle.tiny f_0 $ $ f_i(arrow(x)) = sigma_i (W arrow(x) + arrow(b)) $ ,where $W in RR^(n_i times n_(i+1)),b in RR^n_(i+1),i in {0,dots ,N}$] ][#image("imgs/mlp.png") 其中的$h_i、o_i$代表一个将符号函数替换为非线性激活函数的感知机。 ] #new-section-slide("The learning Algorithm of ANN") #slide(title:"The Training Process of ANN")[ 我们已经探讨了机器学习任务,并定义了神经网络中的性能量度——损失函数。另外,我们也已经获得了一个典型的神经网络模型。于是,我们自然需要讨论如何通过使用经验E,即数据,使得神经网络在损失函数意义下获得性能提升。这个优化过程称为神经网络的#alert[训练]。 ] #slide(title:"Maximize Performance and Minimize the Loss Function")[ 注意到损失函数的定义,我们假定了模型性能越差,损失函数越大。也就是说,#alert()[我们只需要反过来通过调整M,在经验E上最小化损失函数,就能达到提高模型M在任务T上表现的目的。]于是,神经网络的优化任务可以如下形式化定义: #block( fill: luma(230), inset: 8pt, radius: 4pt, )[$ theta^* = arg min_theta cal(L)(M_theta,E) $] 其中$theta$是模型中#alert()[所有的可调整参数]。通过损失函数,我们成功将主观的性能评估和改进问题,转化为了计算和优化损失函数的问题,进而可以通过数值方法解决。可以认为,通过设计损失函数,我们将主观性转移至了损失函数中。 ] #new-section-slide("Gradient-based Optimization Method") #slide()[ 在数值计算领域,最常用、效果最好的数值优化算法绝大部分是基于梯度的算法。由于神经网络的简单基本结构的可导性以及参数空间的连续性,我们可以方便地使用梯度法作为优化方法。 ] #slide(title:"Gradient Descent Algorithm")[ 基于梯度的优化方法中最易理解的是梯度下降算法: = Definition #block( fill: luma(230), inset: 8pt, radius: 4pt, )[令$ theta_(n+1) = theta_(n) - eta (partial cal(L)(M_theta_n,E))/(partial theta_n) $ 则对于一类性质较好的$cal(L)$和$M_theta$,我们有 $ lim_(eta arrow 0,n arrow infinity) theta_n = theta^* $ ] 我们知道梯度的反向是该点邻域中函数值下降最快的方向,因此当函数不太差时,沿梯度的反向进行参数的更新都有机会达到函数的最小值。 ] #slide(title:"Gradient Descent Algorithm")[ = 梯度下降算法的缺点 1. 该方法对于函数的性质有要求,否则对于参数的初值较为敏感,容易陷入局部极小值。(考虑有两个谷的函数) 2. 该方法需要在全部样本上计算出梯度,并求平均。这极大的降低了梯度下降的效率。 ] #slide(title:"Stochastic Gradient Descent (SDE)")[ 随机梯度下降算法是目前几乎所有神经网络的学习算法。 目前已知的绝大多数算法都是基于这个方法的优化或微调。或者说,#alert()[今天我们所讲的神经网络就是指能够使用随机梯度下降算法进行训练的神经网络]。 = Definition #block( fill: luma(230), inset: 8pt, radius: 4pt, )[令$ theta_(n+1) = theta_(n) - eta (partial cal(L)(M_theta_n,{X_i} subset E))/(partial theta_n) $ 则对于大多数$cal(L)$和$M_theta$,我们有 $lim_(eta arrow 0,n arrow infinity) theta_n = theta^*$ ] 随机梯度下降法使得神经网络能够通过每次选取部分数据计算梯度,即可根据#alert()[学习率$eta$]更新网络参数 ] #slide(title:"How to Compute Gradient")[ 理论上,给定任何不含有不可微结构的确定的网络结构,我们都可以写出梯度的解析表达。然而当网络规模增大时,这显然是不可实现的。因此我们需要寻找数值方法计算参数的梯度。 ] #slide(title:"How to Compute Gradient")[ = 数值微分法 #block( fill: luma(230), inset: 8pt, radius: 4pt, )[$ hat(theta_(n+1,i))' = (cal(L)(M_(hat(theta_(n,i)) + epsilon),{X_i}) - cal(L(M_(hat(theta_(n,i)) - epsilon),{X_i})))/(2 epsilon) $] 该方法的时间复杂度是$cal(O)(N) times cal(O)("forward")$,$N$是参数规模。 通常来说,$cal(O)("forward")$ 与参数量成近似线性关系,因此总的复杂度为$cal(O)(N^2)$。 这个复杂度在参数量很大(现代深度神经网络的参数量通常在千万到百亿级别)时是不可接受的。 我们注意到,在进行网络中靠近输出部分的参数的梯度计算时,两次正向传播中有#alert[大量的重复计算]。我们是否能够找到一种能够复用计算结果的方法来降低重复计算的开销? ] #slide(title:"Backward Propagation")[ = 反向传播 反向传播法是现有的神经网络计算梯度的最优方法。现代深度神经网络训练框架#alert[全部]使用反向传播进行梯度计算。 ] #slide(title:"Backward Propagation")[ = Theorem 链式法则 #block( fill: luma(230), inset: 8pt, radius: 4pt, )[令 $f: RR^a -> RR^b ,g: RR^b -> RR^c ,c in RR^a$,则有 $ partial(g^((i))(arrow(f)(arrow(x))))/(partial x^((j))) = sum_(t = 1)^b (partial g^((i))(f^((1))(arrow(x)),dots,f^((b))(arrow(x))))/(partial f^((t))(arrow(x))) dot (partial f^((t))(arrow(x)))/(partial x^((j))) $ ] 可以发现,对于任何完全由复合函数构成的函数,我们都可以将其分为两部分进行计算,这两部分都仅与构成复合函数的部分自身相关。 回顾神经网络的定义,我们发现神经网络#alert[确实由这样可导的简单部分相互连接(即复合)构成的]。这表明我们对于神经网络的任意分割,都可以分别计算它们各自的参数的梯度,再将其按照网络结构的连接关系进行组合得到整个网络的参数的梯度。 ] #slide(title:"Backward Propagation")[ = 计算图 计算图是一种有向无环图,其中节点表示计算操作,边表示数据流。计算图提供了一种清晰的方式来表示复杂的计算过程,并允许方便的使用使用链式法则来计算梯度 计算图由两部分组成: 节点上的运算(通常用圈表示),以及复合关系(通常用箭头表示)。 一个神经网络唯一对应了一个计算图。 ][ 一个典型的计算图: #image("imgs/graph.svg") 计算图最重要的一点是实现了#alert[局部计算]: 对于每个节点,我们只需要保存正向过程的输入,并且获得下一级节点的梯度,就可以函数关于本节点的梯度。 ] #slide(title:"Backward Propagation")[ = Algorithm 反向传播算法 #block( fill: luma(230), inset: 8pt, radius: 4pt, )[ 1. 前向传播:计算所有激活值和加权输入 - 计算每一层的输出,同时保存输入输出信息 2. 计算损失函数的偏导数 - 计算输出层的误差 - 将误差作为损失函数层的微元系数,并计算对于每个输入的微元系数 3. 反向传播误差 - 对于每个已经计算出微元系数的节点的拓扑排序位于更前方的节点,读取传播过来的系数 - 使用该系数与本节点保存的信息,计算本节点的微元系数 - 将系数继续向前面的层传播 ] ] #slide(title:"Backward Propagation")[ #image("imgs/graph.svg")] #slide(title:"Backward Propagation")[ = 高效性 时间复杂度$cal(O)("forward")$,大部分情况下与参数量呈线性关系 = 实现的简便性 局部计算除了通过信息的复用显著降低了梯度求解的时间复杂度以外,也方便了使用现代编程语言实现神经网络。我们可以简单的将每个计算节点实例化为一个对象,这些相互不耦合的对象可以通过数据的传递完成一个完整神经网络的功能。 = 演示 一个简单“神经网络”的实现和训练 ] #new-section-slide("Generalization of Neural Networks") #slide(title: "Metrics that Determine the Effectiveness of ANN")[ 在训练过程中,我们通过假设损失函数能够完全反映模型性能来对模型进行改进。然而在实际情况中并不如此。首先,损失函数#alert[并不一定能完全反映模型性能],例如在生成模型中很难找到一个合适的完全反映生成质量的损失函数。其次,在神经网络学习任务中,我们通过最小化训练集上的误差(通常被称为训练误差)来训练模型。而#alert[机器学习问题和优化问题的本质不同在于,我们也希望泛化误差(也被称为测试误差)很低]。 泛化能力是指模型在新数据上的表现能力,即模型在训练集之外的数据上仍能保持良好性能的能力。一个理想的机器学习模型不仅在训练集上表现优异,还能在测试集上取得低误差。通过前面的统计学习的数据生成过程假设中的独立同分布假设,我们可以得知训练误差的期望和测试误差的期望在理论上是相同的。然而期望相同不代表表现一致,神经网络在训练集上的实际表现并不一定与测试集上相同。 ] #slide(title:"Underfitting and Overfitting")[ 模型的泛化能力面临两个主要挑战:欠拟合和过拟合。 #alert[欠拟合(Underfitting)是指模型在训练集上的表现不佳],即模型无法捕捉到训练数据中的主要模式或结构。这通常是由于模型过于简单,无法有效学习数据中的复杂关系所致。 #alert[过拟合(Overfitting)是指模型在训练集上表现优异],但在测试集上的表现较差。这通常是因为在训练过程中过于“记住”训练数据中的噪声和细节,而忽略了数据的整体结构。过拟合通常发生在模型过于复杂或训练数据不足的情况下。 ][#image("imgs/fitting.svg", width: 60%) #image("imgs/fitting2.png", height: 50%)] #slide(title: "Network structure and hypothesis space")[ 首先我们需要明确神经网络的结构影响了哪些因素。考虑输入n维,输出m维的神经网络。从神经网络的数学描述中可以看出,对于任意结构,任意给定参数的神经网络,其都是从$RR^n$到$RR^m$的函数空间的元素。于是,对于拥有k个可变参数的神经网络,其能表达的函数为${F_theta|theta in RR^k}$。这是上述函数空间的一个子集。我们发现,#alert[不同结构的神经网络实际上是上述函数空间的不同子集]。该空间称为神经网络的#alert[假设空间]。 通过调整神经网络的结构,我们可以调整神经网络的假设空间,进而调整其表达能力。 ] #slide(title:"MLP’s Representation Ability")[ 为了理解神经网络结构设计的目的,我们首先引入表述MLP表达能力的一个定理: = Theorem #block(fill: luma(230), inset: 8pt, radius: 4pt,)[ $ forall f in cal(L)(RR^n), forall epsilon>0, exists F_theta in M L P, forall x in RR^n, s.t. |F_theta (x)-f(x)|<epsilon $ ] 这表明参数量足够大的MLP可以以任意精度逼近任何可测函数。这是否意味着我们对于任何学习任务都可以直接选取一个足够大的MLP在训练集上进行训练呢? ] #slide(title:"MLP’s Representation Ability")[ #alert[机器学习任务是这样的,模型只需要表达能力足够强就可以了,而我们让模型进行学习需要考虑的就很多了,梯度下降能不能找到最优解,在训练集上训练后是否会过拟合,都需要深思熟虑。] 例如,严格来说,如果我们能够完全拟合训练集分布,那么我们会得到一个多点离散分布。这是离散化采样带来的必然结果。但这个估计显然是不合理的,例如我们如果在图像生成任务上完全拟合训练集,那么使用训练后的模型生成图片就变成了从训练集中随机挑选一张图片。 ] #slide(title:"MLP’s Representation Ability")[ = Review = 机器学习问题和优化问题的根本区别在于,除了希望训练误差很低,我们也希望泛化误差很低。] #slide(title:"Occam’s Razor Principle")[ = 奥卡姆剃刀原则 从理论上来说,仅通过离散化采样,我们永远无法完整得知真实分布。我们需要从所有符合条件的可能的分布中选取一个。#alert[奥卡姆剃刀原则(Occam’s Razor)]在逻辑学中是一条重要的指导原则。该原则陈述为如果关于同一个问题有许多种理论,每一种都能作出同样准确的预言,那么应该#alert[挑选其中最简单的]。尽管越复杂的方法通常能做出越好的预言,我们更倾向于引入外部因素更少的方法。例如给定数据集{(0,0), (1,1), (2,2)},我们最好使用$y=a x$作为模型对数据集进行拟合,而非$y = sum_(k=1)^infinity a_k x^k$. = Thinking 奥卡姆剃刀原则的另一种表述为:“在作出断言时,使用的假设越少越好”。这对应的是我们需要增大假设空间还是减小假设空间? ] #slide(title: "Problem Structure and Network Structure")[ 根据奥卡姆剃刀原则,我们应该使得模型的假设空间#alert[在包含符合先验信息的所有可能假设的情况下尽可能小]。这表明我们需要对神经网络的结构进行合理的设计,排除掉不符合先验信息的假设,进而提高神经网络的泛化能力。 然而,先验信息通常很难有显式的表达,并且对于各类不同任务,先验信息也大相径庭。事实上,深度神经网络的相当一部分研究都是通过研究甚至猜测先验信息的结构,进而设计出符合特定问题的网络结构,或调整问题结构使得问题符合神经网络的假设空间。#alert[神经网络的结构设计一定依赖于对于特定问题结构或者数据的信息结构的研究]。 ] #new-section-slide("Immutability and the Design of Network structures") #slide()[ = 不变性 不变性是一种常见的问题结构。通过不变性,我们可以将解决全局问题缩小为解决结构相似的局部问题,再通过局部问题的解得到全局问题的解。下面阐述一些常见问题中的不变性,以及其对应的神经网络结构。 ] #slide(title:"Translation Invariance and CNN")[ 平移不变性是指系统在受到平移操作时,其性质保持不变。这种不变性在图像处理、语音识别等领域中非常常见。例如,当我们处理图像时,无论#alert[图像]中的物体在什么位置,我们都希望模型能够识别出相同的物体。或者,当我们处理#alert[语音]时,无论某个音节出现在音频的哪一时刻,我们都希望识别出相同的音节。 为了解决平移不变性问题,#alert[卷积神经网络(Convolutional Neural Network, CNN)]被广泛应用。CNN通过使用一组特定的的卷积核在输入上进行卷积操作,使得网络能够提取平移不变的特征。 ] #slide(title:"CNN")[ 卷积操作是CNN的核心,通过在输入上应用卷积核来提取局部特征。每个卷积核扫描整个输入,生成一个特征张量。这些特征张量能够捕捉不同层次的特征,如边缘、纹理、形状等。卷积操作可以表示为如下形式: #block(fill: luma(230), inset: 8pt, radius: 4pt,)[ $ h_(i dots j) = sum_m dots sum_n x_(i+m, dots, j+n) w_(m dots n) $ 其中h为输出的特征,x是输入,w是卷积核。 ]][ 一个二维卷积的过程可以可视化为下图: #image("imgs/convolution.png") ] #slide(title:"CNN")[ 卷积所得结果中,每个特征图像素点取值依赖于输入图像中的某个区域,该区域被称为#alert[感受野]。在卷积神经网络中,感受野是特征图上的点对应输入图像上的区域。感受野内每个元素数值的变动,都会影响输出点的数值变化。当仅增加卷积网络深度时,感受野将会增大(请自行推导),输出特征图中的一个像素点将会包含更多的图像语义信息。 ][ 卷积计算不局限于前面的简单过程,实际应用时,处理的问题要复杂的多。例如:对于彩色图片有RGB三个通道,需要处理多输入通道的场景,相应的输出特征图往往也会具有多个通道。在神经网络的计算中常常是把一个批次的样本放在一起计算,所以卷积算子需要具有批量处理多输入和多输出通道数据的功能。可以注意到,我们可以使用“一片”输入和“一片”卷积核获得“一片”特征图。显然,我们可以通过输入和卷积核的排列组合达到多通道输入输出的目的。 ] #slide(title:"Feature Space Invariance and Embedding")[ 回顾先前提到的低维流形假设:自然的原始数据是低维的流形嵌入于原始数据所在的高维空间。一个显然的问题是,我们能否使用低维描述表示这个流形?考虑可维流形的性质,我们只需要学习一个从高维欧空间到低维欧空间的可微映射来表示该流形。我们称该问题为#alert[嵌入(embedding)]问题。 嵌入过程要求保持特征空间的不变性,即在低维空间中保留原始数据的特征结构和相似性: #block(fill: luma(230), inset: 8pt, radius: 4pt,)[ 设 $f: cal(X) -> RR^d$ 是从高维空间到低维空间的嵌入映射,那么对于任意两个数据点$x_i, x_j in cal(X)$ ,它们在低维空间中的距离或相似性 $|f(x_i) - f(x_j)|$ 应该与它们在高维空间中的距离或相似性$|x_i - x_j|$ 保持一致或近似一致。] ] #slide(title:"Feature Space Invariance and Embedding")[特征空间中的点#alert[通常包含足够的信息,我们甚至能够仅通过特征空间还原原始数据]。这意味着即使经过降维处理,特征空间中的表示仍然应保留原始数据的关键特征和模式。同时,特征空间的维度通常远小于原始数据空间的维度。通过降低维度,我们能够#alert[去除数据中的冗余信息,提取出对数据描述最重要的特征]。这种低维表示有助于减少计算复杂度和存储需求。] #slide(title: "Autoencoder")[ = 自回归编码器(Autoencoder, AE) 自回归编码器实际上是一种生成模型。它由两个主要部分组成:编码器(Encoder)和解码器(Decoder)。编码器将高维输入数据映射到低维特征空间,而解码器则从低维特征空间中重构出原始数据。 #block(fill: luma(230), inset: 8pt, radius: 4pt,)[ 编码器:$z = f(x)$ ,解码器:$hat(x) = g(z)$, 其中$x in cal(X), z in RR^d$ ] 特征空间不变性要求编码器将原始数据映射到特征空间中时,能够保留数据的关键特征和结构。自回归编码器通过保证能够仅通过特征空间中的编码向量还原原始数据来保证特征空间不变性。 自回归编码器通过#alert[最小化重构误差]来确保特征空间中的点能够有效地还原原始数据。重构误差通常通过均方误差来衡量: $ cal(L)(x, hat(x)) = |x - hat(x)|^2 $ 通过最小化重构误差,我们能够让编码器在学习到从原空间到低维流形的映射的同时使解码器学习到从低维流形到原空间的映射。编码器和解码器通常具有对称的结构,以确保特征空间中点的表示和原始数据之间的映射关系保持一致。 ] #slide(title:"Embedding")[ “嵌入”在现代神经网络设计中具有极为重要的地位。实际上,嵌入就是数据在特征空间中的表示。这使得嵌入具有结构和表示上的极为优良的性质。例如,词向量的“可加性”正是来源于特征空间的不变性。 #image("imgs/wordvec.jpeg")] #slide(title:"Transition Probability Invariance and RNN")[ 序列处理问题广泛存在于许多领域,包括自然语言处理、时间序列预测、语音识别等。这些问题通常涉及从输入序列中提取信息(序列识别)或生成新的序列(序列生成)。 在序列处理问题中,转移概率不变性是一个重要的概念。#alert[它指的是在序列的不同时间步之间,状态转移的概率保持不变]。换句话说,模型在每个时间步的状态转移规则是一致的,不依赖于时间步的具体位置。这一性质确保了模型能够一致地处理整个序列中的数据,无论序列的长度或位置如何。我们可以形式化地表述这一点: #block(fill: luma(230), inset: 8pt, radius: 4pt,)[ 设$h_t in RR^d$表示时间步$t$的隐藏状态($h$是特征空间中的向量),$x_t$表示时间步$t$的输入数据,那么隐藏状态的更新规则可以表示为: $ h_t = f(h_(t-1), x_t, t) $ 其中$f$是状态转移函数。]这意味着,对于所有的$t$,状态转移函数$f$的形式和参数都不变。 ] #slide(title: "RNN")[ 递归神经网络(Recurrent Neural Network, RNN)是一类适合处理序列数据的神经网络模型。RNN的设计基于特征空间不变性和转移概率不变性,能够有效捕捉序列数据的动态特征和时间依赖性。 RNN由一系列递归单元组成,每个单元在每个时间步接收当前输入和前一个时间步的隐藏状态,并输出新的隐藏状态。这种结构可以如下形式化表示: #block(fill: luma(230), inset: 8pt, radius: 4pt,)[ $h_t = sigma(W_h h_(t-1) + W_x x_t + W_t t + b_h)$ $y_t = sigma(W_y h_t + b_y)$] ][RNN通常可以用时序图来表示: #figure(image("imgs/rnn.png", width: 70%))] #slide(title: "Feature Space Invariance in RNN")[ 在RNN中,特征空间不变性通过两处设计来实现。首先是#text(fill: purple.darken(10%))[共享权重]:RNN在每个时间步使用相同的权重,确保所有时间步的输入和隐藏状态都在相同的特征空间中处理。其二是#text(fill: purple.darken(10%))[隐藏状态的连续性]:隐藏状态在时间序列中连续传递,确保每个时间步的特征表示与前后时间步的特征表示之间的关系保持一致。 ] #new-section-slide("Summary") #slide()[ 神经网络算法是典型的统计机器学习算法:从数据中获取信息,进而实现特定任务。通过使用基于梯度的优化算法,我们在数据上训练神经网络,使其在任务上具有更好的表现。通过一些对于数据和真实分布性质的假定,我们期望神经网络能够拥有超越经典优化问题的特点——泛化性。同时,通过研究问题、数据与信息的结构,我们设计和改进神经网络的结构,进而提高神经网络的训练和泛化性能。希望大家能够体会到机器学习的核心:数据与信息,任务与模型,进而理解并适当使用神经网络这一强大的工具。 ] #slide()[ = 请自行思考以下关键词的含义,以及它们之间的关系: #columns(3)[ - 任务 - 经验 - 性能量度 - 模型 - 结构 - 数据 - 特征 - 优化 - 学习 - 泛化 - 估计 - 统计学习的三个假设 - 问题结构 - 不变性 - 样本空间 - 特征空间 - 嵌入(Embedding) - 数据生成过程 - 计算图 - 局部计算 - 梯度法 - 损失函数 - 转移概率 - 可优化参数 - 表达能力 - 过拟合 - 欠拟合 ] ]
https://github.com/ntjess/showman
https://raw.githubusercontent.com/ntjess/showman/main/examples/external-code.typ
typst
MIT License
#import "@preview/showman:0.1.1": runner, formatter #set page(height: auto) #show raw: it => { let kwargs = if it.block { (width: 100%, line-numbers: false) } else { (inline: true) } formatter.format-raw(it, ..kwargs) } #show <example-output>: formatter.format-raw // #show <example-input>: formatter.format-raw #let cache = json("/.coderunner.json").at("examples/external-code.typ", default: (:)) #let show-rule = runner.external-code.with( result-cache: cache, direction: ttb, ) = A mini rosseta code example: Fibonacci numbers The outputs for each language will be visible after running ```bash showman execute ./examples/external-code.typ ``` - *Note*: If you're on Windows, the `bash` example will not evaluate. - `typst` will render for free, independent of `showman execute`. #show raw: it => { if it.at("label", default: none) != <continue> { heading(it.lang) } if it.lang != "typst" { show-rule(it) } else { runner.standalone-example(it, direction: ttb) } } ```typst #let fib(n) = { if n < 2 { n } else { // Typst memoizes by default :) fib(n - 1) + fib(n - 2) } } #fib(50) ``` ```python import functools @functools.lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) fib(50) ``` ```cpp #include <iostream> #include <vector> typedef unsigned long long ulong; ulong fib(ulong n, std::vector<ulong> &cache) { if (n < 2) { return n; } if (cache[n] != -1) { return cache[n]; } cache[n] = fib(n-1, cache) + fib(n-2, cache); return cache[n]; } int main() { std::vector<ulong> cache(101, -1); std::cout << fib(50, cache) << std::endl; return 0; } ``` ```c #include <stdio.h> typedef unsigned long long ulong; unsigned long long fib(ulong n, ulong *cache) { if (n < 2) { return n; } // Warning -- this can result in buffer overflow if (cache[n] != -1) { return cache[n]; } cache[n] = fib(n-1, cache) + fib(n-2, cache); return cache[n]; } int main() { ulong cache[101]; for (ulong i = 0; i < 101; i++) { cache[i] = -1; } printf("%llu\n", fib(50, cache)); return 0; } ``` ```bash fib() { local n=$1 if [ $n -lt 2 ]; then echo $n return fi local a=$(fib $((n-1))) local b=$(fib $((n-2))) echo $((a+b)) } # Not memoized, so use a much smaller number fib 10 ``` ```js var cache = {}; function fib(n) { if (n < 2) { return n; } if (cache[n] !== undefined) { return cache[n]; } cache[n] = fib(n-1) + fib(n-2); return cache[n]; } fib(50); ``` ```r fib <- local({ memory <- list() function(x) { valueName <- as.character(x) if (!is.null(memory[[valueName]])) return(memory[[valueName]]) if (x < 2) return(x) res <- Recall(x - 1) + Recall(x - 2) memory[[valueName]] <<- res # store results res } }) print(fib(50)) ``` The execution environment persists across code blocks: ```r print(fib(25)) ```<continue>
https://github.com/An-314/Notes-of-DSA
https://raw.githubusercontent.com/An-314/Notes-of-DSA/main/advanced_BST.typ
typst
= 高级BST == 伸展树Splay Tree === 局部性/Locality 时间:刚被访问过的节点,极有可能很快地再次被访问 空间:下一将要访问的节点,极有可能就在刚被访问过节点的附近 AVL连续的m次查找(m >> n),共需$O(m log n)$时间,希望可以利用局部性加速。 - 自适应链表:节点一旦被访问,随即移动到最前端 - 模仿:希望BST的节点一旦被访问,随即调整到树根 如果节点被访问,就将其旋转到根节点,这样下次访问时,就可以直接访问到了。 === 逐层伸展 #figure( image("fig\BST\33.png", width: 80%), caption: "逐层伸展" ) 但这样很有可能导致树的不平衡,比如下面的例子: #figure( image("fig\BST\34.png", width: 80%), caption: "逐层伸展——最坏情况" ) === 双层伸展 向上追溯两层,而非一层。 反复考察祖孙三代:`g = parent(p), p = parent(v), v`。根据它们的相对位置,经两次旋转,使`v`上升两层,成为(子)树根。 *zig-zag/zag-zig* #figure( image("fig\BST\35.png", width: 80%), caption: "双层伸展——情形1" ) 对于`v`是`p`的左孩子,`p`是`g`的右孩子的情况,先对`p`进行一次旋转,再对`v`进行一次旋转。 这样的效果事实上和逐层旋转是一样的。 *zig-zig/zag-zag* #figure( image("fig\BST\36.png", width: 80%), caption: "双层伸展——情形2" ) 但是如果是`v`是`p`的左孩子,`p`是`g`的左孩子的情况,两种旋转方式就有区别。 连续两次旋转根节点(上图下面的旋转方法),可以使得`v`上升两层,成为(子)树根。 这种情况下,节点访问之后,对应路径的长度随即折半。最坏情况不致持续发生。 伸展操作分摊下来,仍然是$O(log n)$的。 #figure( image("fig\BST\37.png", width: 80%), caption: "双层伸展——情形2" ) *zig/zag* 如果`v`只有父亲,没有祖父,此时必有`v.parent() == T.root()`,只做一次旋转即可。只会出现在最后一次。 === 算法实现 接口 ```cpp template <typename T> class Splay : public BST<T> { //由BST派生 protected: BinNodePosi<T> splay( BinNodePosi<T> v ); //将v伸展至根 public: //伸展树的查找也会引起整树的结构调整,故search()也需重写 BinNodePosi<T> & search( const T & e ); //查找(重写) BinNodePosi<T> insert( const T & e ); //插入(重写) bool remove( const T & e ); //删除(重写) }; ``` 伸展算法 ```cpp template <typename T> BinNodePosi<T> Splay<T>::splay( BinNodePosi<T> v ) { if ( ! v ) return NULL; BinNodePosi<T> p; BinNodePosi<T> g; //父亲、祖父 while ( (p = v->parent) && (g = p->parent) ) { /* 自下而上, 反复地双层伸展 */ } if ( p = v->parent ) { /* 若p果真是根,只需再额外单旋一次 */ } v->parent = NULL; return v; //伸展完成, v抵达树根 } ``` 填充上面的空白,得到伸展算法的实现。 ```cpp while ( (p = v->parent) && (g = p->parent) ) { //自下而上,反复双层伸展 BinNodePosi<T> gg = g->parent; //每轮之后, v都将以原曾祖父为父 if ( IsLChild( * v ) ) if ( IsLChild( * p ) ) { /* zig-zig */ } else { /* zig-zag */ } else if ( IsRChild( * p ) ) { /* zag-zag */ } else { /* zag-zig */ } if ( !gg ) v->parent = NULL; //无曾祖父gg的v即为树根;否则, gg此后应以v为 else ( g == gg->lc ) ? attachAsLC(v, gg) : attachAsRC(gg, v); //左或右孩子 updateHeight( g ); updateHeight( p ); updateHeight( v ); } ``` 对于`zig-zig`的情况,有: ```cpp if ( IsLChild( * v ) ) if ( IsLChild( * p ) ) { //zIg-zIg attachAsLC( p->rc, g ); //Y attachAsLC( v->rc, p ); //X attachAsRC( p, g ); attachAsRC( v, p ); } else { /* zIg-zAg */ } else if ( IsRChild( * p ) ) { /* zAg-zAg */ } else { /* zAg-zIg */ } ``` 剩下情况类似,不再赘述。 查找算法。伸展树的查找,与常规`BST::search()`不同:很可能会改变树的拓扑结构,不再属于静态操作: ```cpp template <typename T> BinNodePosi<T> & Splay<T>::search( const T & e ) { // 调用标准BST的内部接口定位目标节点 BinNodePosi<T> p = BST<T>::search( e ); // 无论成功与否,最后被访问的节点都将伸展至根 _root = splay( p ? p : _hot ); //成功、失败 // 总是返回根节点 return _root; } ``` 插入算法。`Splay::search()`已集成`splay()`,查找失败之后, `_hot`即是根,随即就在树根附近接入新节点。 ```cpp template <typename T> BinNodePosi<T> Splay<T>::insert( const T & e ) { if ( !_root ) { _size = 1; return _root = new BinNode<T>( e ); } //原树为空 BinNodePosi<T> t = search( e ); if ( e == t->data ) return t; //t若存在,伸展至根 if ( t->data < e ) { //在右侧嫁接(rc或为空, lc == t必非空) t->parent = _root = new BinNode<T>( e, NULL, t, t->rc ); if ( t->rc ) { t->rc->parent = _root; t->rc = NULL; } } else { //e < t->data,在左侧嫁接(lc或为空, rc == t必非空) t->parent = _root = new BinNode<T>( e, NULL, t->lc, t ); if ( t->lc ) { t->lc->parent = _root; t->lc = NULL; } } _size++; updateHeightAbove( t ); return _root; //更新规模及t与_root的高度,插入成功 } //无论如何, 返回时总有_root->data == e ``` #figure( image("fig\BST\38.png", width: 80%), caption: "伸展树——插入" ) 删除算法。`Splay::search()`成功之后,目标节点即是树根,在树根附近完成目标节点的摘除。 ```cpp template <typename T> bool Splay<T>::remove( const T & e ) { if ( !_root || ( e != search( e )->data ) ) return false; //若目标存在,则伸展至根 BinNodePosi<T> L = _root->lc, R = _root->rc; release(_root); //记下子树后,释放之 if ( !R ) { //若R空 if ( L ) L->parent = NULL; _root = L; //则L即是余树 } else { //否则 _root = R; R->parent = NULL; search( e ); //在R中再找e:注定失败, 但最小节点必 if (L) L->parent = _root; _root->lc = L; //伸展至根, 故可令其以L作为左子树 } _size--; if ( _root ) updateHeight( _root ); //更新记录 return true; //删除成功 } ``` #figure( image("fig\BST\39.png", width: 80%), caption: "伸展树——删除" ) *综合评价*: - 无需记录高度或平衡因子;编程实现简单——优于AVL树 - 分摊复杂度$O(n log n)$ ——与AVL树相当 - 局部性强、缓存命中率极高时(即 $k << n << m $)时候($k$是被访问的节点数,$m$是被访问次数),性能优于AVL树 - 效率甚至可以更高——自适应的$O(log k)$ - 任何连续的$m$次查找, 仅需$O(m log k + n log n)$时间 - 若反复地顺序访问任一子集,分摊成本仅为常数 - 不能杜绝单次最坏情况,不适用于对效率敏感的场合 === 分摊分析 利用势能的方法,对伸展树的分摊复杂度进行分析。 对于伸展树,势能函数定义为: $ Phi(S) = log(product_(v in S) "size"(v)) = sum_(v in S) log("size"(v)) = sum_(v in S) "rank"(v) = sum_(v in S) log V $ 越平衡/倾侧的树,势能越小/大。单链是$O(n log n)$,满树是$O(n)$。 考查对伸展树$S$的$m>>n$次连续访问(不妨仅考查`search()`),记 $ A^(k) = T^(k) + Delta Phi^(k) $ 则有 $ A - O(n log n) <= T = A - Delta Phi <= A + O(n log n) $ 下面证明 $ A = O(m log n) $ 则有 $ T = O(n log n) $ 而$A^(k)$都不致超过节点v的势能变化量, 即:$O("rank"^(k)(v)-"rank"^(k-1)(v))= O(log n)$。 $A^(k)$是`v`的若干次连续伸展操作(时间成本)的累积,这些操作无非三种情况。 #figure( image("fig\BST\40.png", width: 70%), caption: "伸展树——分摊分析" ) #figure( image("fig\BST\41.png", width: 70%), caption: "伸展树——分摊分析" ) #figure( image("fig\BST\42.png", width: 70%), caption: "伸展树——分摊分析" ) == B树 === 缓存Cache 先考虑这样一个问题:_就地循环位移_ _仅用$O(1)$辅助空间,将数组`A[0, n)`中的元素向左循环移动k个单元 `void shift( int * A, int n, int k );`_ *蛮力解法*:每次移动一个单元,共移动k次,时间复杂度$O(k n)$。 ```cpp void shift0( int * A, int n, int k ) //反复以1为间距循环左移 { while ( k-- ) shift( A, n, 0, 1 ); } //共迭代k次, O(n*k) ``` #figure( image("fig\BST\43.png", width: 70%), caption: "就地循环位移——蛮力解法" ) *迭代版Stride-k Reference Pattern *:分成k组,每组内部循环左移,共移动n次,时间复杂度$O(n)$。 ```cpp int shift( int * A, int n, int s, int k ) { // O( n / GCD(n, k) ) int b = A[s]; int i = s, j = (s + k) % n; int mov = 0; //mov记录移动次数 while ( s != j ) //从A[s]出发,以k为间隔,依次左移k位 { A[i] = A[j]; i = j; j = (j + k) % n; mov++; } A[i] = b; return mov + 1; //最后,起始元素转入对应位置 } //[0, n)由关于k的g = GCD(n, k)个同余类组成, shift(s, k)能够且只能够使其中之一就位 void shift1(int* A, int n, int k) { //经多轮迭代,实现数组循环左移k位,累计O(n+g) for (int s = 0, mov = 0; mov < n; s++) //O(g) = O(GCD(n, k)) mov += shift(A, n, s, k); } ``` #figure( image("fig\BST\44.png", width: 70%), caption: "就地循环位移——Stride-k Reference Pattern" ) *倒置版Stride-1 Reference Pattern*:如下图,经过三次倒置即可。复杂度是$O(3n)$。 ```cpp void shift2( int * A, int n, int k ) { reverse( A, k ); //O(3k/2) reverse( A + k, n – k ); //O(3(n-k)/2) reverse( A, n ); //O(3n/2) } //O(3n) ``` #figure( image("fig\BST\45.png", width: 70%), caption: "就地循环位移——Stride-1 Reference Pattern" ) 可以看到这种方法虽然看上去常系数很大,但是实际上是最快的。这是因为利用了缓存。 - 实用的存储系统,由不同类型的存储器级联而成,以综合其各自的优势 #figure( image("fig\BST\46.png", width: 70%), caption: "存储系统" ) - 分级存储:利用数据访问的局部性 #figure( image("fig\BST\47.png", width: 70%), caption: "分级存储" ) - 这就导致:在外存读写1B,与读写1KB几乎一样快 - 以页(page)为单位, 借助缓冲区批量访问, 可大大缩短单位字节的平均访问时间 === B树的结构 出于缓存的考虑,B树每$d$代合并为超级节点 - $m = 2^d$ 路 - $m-1$ 个关键码 逻辑上与BBST完全等价。 #figure( image("fig\BST\48.png", width: 70%), caption: "B树" ) I/O优化: 多级存储系统中使用B-树,可针对外部查找,大大减少I/O次数。 #figure( image("fig\BST\49.png", width: 50%), caption: "B树" ) 所谓$m$阶B-树, 即m路完全平衡搜索树($m >= 3$) - 外部节点的深度统一相等,约定以此深度作为树高$h$ - 叶节点的深度统一相等$h-1$ - 内部节点 - 各含 $n <= m-1$ 个关键码:$K_1 < K_2 < ... < K_n$ - 各有 $n+1 <= m$个分支:$A_0, A_1, ... , A_n$ - 反过来,分支数也不能太少 - 树根:$2 <= n+1$ - 其余:$ceil(m/2) <= n+1$ - 故也称作$(ceil(m/2), m)$-树 #figure( image("fig\BST\50.png", width: 70%), caption: "B树——紧凑表示" ) `BTNode`:用两个长度差1的向量存储关键码和孩子 ```cpp template <typename T> struct BTNode { //B-树节点 BTNodePosi<T> parent; //父 Vector<T> key; //关键码(总比孩子少一个) Vector< BTNodePosi<T> > child; //孩子 BTNode() { parent = NULL; child.insert( NULL ); } BTNode( T e, BTNodePosi<T> lc = NULL, BTNodePosi<T> rc = NULL ) { parent = NULL; //作为根节点 key.insert( e ); //仅一个关键码,以及 child.insert( lc ); if ( lc ) lc->parent = this; //左孩子 child.insert( rc ); if ( rc ) rc->parent = this; //右孩子 } }; ``` #figure( image("fig\BST\51.png", width: 40%), caption: "B树——节点" ) `BTree`模板类 ```cpp template <typename T> using BTNodePosi = BTNode<T>*; //B-树节点位置 template <typename T> class BTree { //B-树 protected: Rank _size, _m; //关键码总数、 阶次 BTNodePosi<T> _root, _hot; //根、 search()最后访问的非空节点 void solveOverflow( BTNodePosi<T> ); //因插入而上溢后的分裂处理 void solveUnderflow( BTNodePosi<T> ); //因删除而下溢后的合并处理 public: BTNodePosi<T> search( const T & e ); //查找 bool insert( const T & e ); //插入 bool remove( const T & e ); //删除 }; ``` === B树的查找 和BST一样,B树的查找也是从根节点开始,逐层向下,直到外部节点。 ```cpp 从(常驻RAM的)根节点开始 只要当前节点不是外部节点 在当前节点中顺序查找 //RAM内部 若找到目标关键码,则 return 查找成功 否则 //止于某一向下的引用 沿引用找到孩子节点 将其读入内存 //I/O耗时 return 查找失败 ``` #figure( image("fig\BST\52.png", width: 50%), caption: "B树——查找" ) ```cpp template <typename T> BTNodePosi<T> BTree<T>::search( const T & e ) { BTNodePosi<T> v = _root; _hot = NULL; //从根节点出发 while ( v ) { //逐层深入地 Rank r = v->key.search( e ); //在当前节点对应的向量中顺序查找 if ( 0 <= r && e == v->key[r] ) return v; //若成功,则返回;否则... _hot = v; v = v->child[ r + 1 ]; //沿引用转至对应的下层子树,并载入其根(I/O) } //若因!v而退出,则意味着抵达外部节点 return NULL; //失败 } ``` 性能:忽略内存中的查找,运行时间主要取决于I/O次数,在每一深度至多一次I/O,故$O(h)$。可以证明,$log_m (N+1) <= h <= 1 + floor(log_ceil(m/2)((N+1)/2))$,其中$N$是关键码总数,$h$是树高。$h = O(log_m N)$。 === B树的插入 插入算法的核心是`solveOverflow()`,它的作用是:将上溢的节点分裂为两个节点,分别作为两个儿子,选出中位数推送到原来的父亲。 ```cpp template <typename T> bool BTree<T>::insert( const T & e ) { BTNodePosi<T> v = search( e ); if ( v ) return false; //确认e不存在 Rank r = _hot->key.search( e ); //在节点_hot中确定插入位置 _hot->key.insert( r+1, e ); //将新关键码插至对应的位置 _hot->child.insert( r+2, NULL ); _size++; //创建一个空子树指针 solveOverflow( _hot ); //若上溢,则分裂 return true; //插入成功 } ``` 设上溢节点中的关键码依次为: $ {k_0, k_1, ..., k_(m-1)} $ 取中位数$s = floor(m/2)$,则有划分: $ {k_0, k_1, ..., k_(s-1)} {k_s} {k_(s+1), ..., k_(m-1)} $ 关键码$k_s$上升一层。 #figure( image("fig\BST\53.png", width: 30%), caption: "B树——上溢" ) 若上溢节点的父亲本已饱和,则在接纳被提升的关键码之后,也将上溢:套用前法,继续分裂。 上溢可能持续发生,并逐层向上传播,直至根节点。次数是$O(h)$的。 此时,如果根节点也上溢,需创建新的根节点,作为B树的新根。注意:新生的树根仅有两个分支。 #figure( image("fig\BST\54.png", width: 70%), caption: "B树——上溢——实例" ) ```cpp template <typename T> void BTree<T>::solveOverflow( BTNodePosi<T> v ) { while ( _m <= v->key.size() ) { //除非当前节点不再上溢 Rank s = _m / 2; //轴点(此时_m = key.size() = child.size() - 1) BTNodePosi<T> u = new BTNode<T>(); //注意:新节点已有一个空孩子 for ( Rank j = 0; j < _m - s - 1; j++ ) { //分裂出右侧节点u(效率低可改进) u->child.insert( j, v->child.remove( s + 1 ) ); //v右侧_m–s-1个孩子 u->key.insert( j, v->key.remove( s + 1 ) ); //v右侧_m–s-1个关键码 } u->child[ _m - s - 1 ] = v->child.remove( s + 1 ); //移动v最靠右的孩子 if ( u->child[ 0 ] ) //若u的孩子们非空,则统一令其以u为父节点 for ( Rank j = 0; j < _m - s; j++ ) u->child[ j ]->parent = u; BTNodePosi<T> p = v->parent; //v当前的父节点p if ( ! p ) //若p为空,则创建之(全树长高一层,新根节点恰好两度) { _root = p = new BTNode<T>(); p->child[0] = v; v->parent = p; } Rank r = 1 + p->key.search( v->key[0] ); //p中指向u的指针的秩 p->key.insert( r, v->key.remove( s ) ); //轴点关键码上升 p->child.insert( r + 1, u ); u->parent = p; //新节点u与父节点p互联 v = p; //上升一层,如有必要则继续分裂——至多O(logn)层 } //while } //solveOverflow ``` === B树的删除 和BST一样,B树的删除也是先寻找,如果节点在叶子上,直接删除;如果节点在内部节点上,找到其后继,将后继的关键码替换到当前节点,然后删除后继。 ```cpp template <typename T> bool BTree<T>::remove( const T & e ) { BTNodePosi<T> v = search( e ); if ( ! v ) return false; //确认e存在 Rank r = v->key.search(e); //e在v中的秩 if ( v->child[0] ) { //若v非叶子,则 BTNodePosi<T> u = v->child[r + 1]; //在右子树中 while ( u->child[0] ) u = u->child[0]; //一直向左,即可找到e的后继(必在底层) v->key[r] = u->key[0]; v = u; r = 0; //交换 } //assert: 至此, v必位于最底层,且其中第r个关键码就是待删除者 v->key.remove( r ); v->child.remove( r + 1 ); _size--; solveUnderflow( v ); return true; //如有必要,需做旋转或合并 } ``` 处理下溢: 非根节点`V`下溢时,必恰有$ceil(m/2)-2$个关键码$ceil(m/2)-1$个个分支。视其左、右兄弟`L`、`R`的规模,可分三种情况加以处理: 1. 若`L`存在,且至少包含$ceil(m/2)$个关键码: - 将 `P` 中的分界关键码 `y` 移至 `V` 中(作为最小关键码) - 将 `L` 中的最大关键码 `x` 移至 `P` 中(取代原关键码 `y` ) - 儿子也要转走 #figure( image("fig\BST\55.jpg", width: 40%), caption: "B树——下溢——情形1" ) 如此旋转之后,局部乃至全树都重新满足B-树条件,下溢修复完毕 2. 若 `R` 存在,且至少包含$ceil(m/2)$个关键码 - 也可旋转,完全对称 #figure( image("fig\BST\56.png", width: 40%), caption: "B树——下溢——情形2" ) 3. `L` 和 `R` 或不存在,或均不足$ceil(m/2)$个关键码: - `L` 和 `R` 仍必有其一(不妨以 `L` 为例),且 - 恰含$ceil(m/2) - 1$个关键码 从 `P` 中抽出介于 `L` 和 `V` 之间的分界关键码 `y` - 通过 `y` 做粘接,将 `L` 和 `V` 合成一个节点 - 同时合并此前 `y` 的孩子引用 此处下溢得以修复,但可能继而导致 `P` 下溢,继续旋转或合并 - 下溢可能持续发生并向上传播;但至多不过 $O(h)$ 层 #figure( image("fig\BST\57.png", width: 40%), caption: "B树——下溢——情形3" ) 下溢修复: ```cpp template <typename T> void BTree<T>::solveUnderflow( BTNodePosi<T> v ) { while ( (_m + 1) / 2 > v->child.size() ) {//除非当前节点没有下溢 BTNodePosi<T> p = v->parent; if ( !p ) { /* 已到根节点 */ } Rank r = 0; while ( p->child[r] != v ) r++; //确定v是p的第r个孩子 if ( 0 < r ) { /∗ 情况 #1:若v的左兄弟存在,且... ∗/ } if ( p−>child.size() − 1 > r ) { /∗ 情况 #2:若v的右兄弟存在,且... ∗/ } if ( 0 < r ) { /∗ 与左兄弟合并 ∗/ } else { /∗ 与右兄弟合并 ∗/ } //情况 #3 v = p; //上升一层, 如有必要则继续旋转或合并——至多O(logn)层 } //while } //solveUnderflow ``` 情况#1:旋转(向左兄弟借关键码) ```cpp if (0 < r) { //若v不是p的第一个孩子,则 BTNodePosi<T> ls = p->child[r - 1]; //左兄弟必存在 if ( (_m + 1) / 2 < ls->child.size() ) { //若该兄弟足够“胖”,则 v->key.insert( 0, p->key[r-1] ); //p借出一个关键码给v(作为最小关键码) p->key[r - 1] = ls->key.remove( ls->key.size() – 1 ); //ls的最大key转入p v->child.insert( 0, ls->child.remove( ls->child.size() – 1 ) );//同时ls的最右侧孩子过继给v(作为v的最左侧孩子) if ( v->child[0] ) v->child[0]->parent = v; return; //至此,通过右旋已完成当前层(以及所有层)的下溢处理 } } //情况#2完全对称 ``` 情况#3:合并 ```cpp if (0 < r) { //与左兄弟合并 BTNodePosi<T> ls = p->child[r-1]; //左兄弟必存在 ls->key.insert( ls->key.size(), p->key.remove(r - 1) ); p->child.remove( r ); //p的第r - 1个关键码转入ls, v不再是p的第r个孩子 ls->child.insert( ls->child.size(), v->child.remove( 0 ) ); if ( ls->child[ ls->child.size() – 1 ] ) //v的最左侧孩子过继给ls做最右侧孩子 ls->child[ ls->child.size() – 1 ]->parent = ls; while ( !v->key.empty() ) { //v剩余的关键码和孩子,依次转入ls ls->key.insert( ls->key.size(), v->key.remove(0) ); ls->child.insert( ls->child.size(), v->child.remove(0) ); if ( ls->child[ ls->child.size() – 1 ] ) ls->child[ ls->child.size() – 1 ]->parent = ls; } //while release(v); //释放v } else { /* 与右兄弟合并,完全对称 */ } ``` 下面的图就给了下溢处理的例子: #figure( image("fig\BST\58.png", width: 70%), caption: "B树——下溢——实例" ) #figure( image("fig\BST\59.png", width: 70%), caption: "B树——下溢——实例" ) == 红黑树Red-Black Tree === 动机 *并发性*:Concurrent Access To A Database 修改之前先加锁(lock);完成后解锁(unlock),访问延迟主要取决于“lock/unlock”周期 对于BST而言,每次修改过程中,唯结构有变(reconstruction)处才需加锁,访问延迟主要取决于这类局部之数量... - Splay:结构变化剧烈,最差可达$O(n)$ - AVL: `remove()`时$0(log n)$,`insert()`时可保证$O(1)$ - Red-Black:无论`insert/remove`, 均不超过$O(1)$ *持久性*:Persistent structures:支持对历史版本的访问 #figure( image("fig\BST\60.png", width: 80%), caption: "持久性" ) #figure( image("fig\BST\61.png", width: 80%), caption: "持久性" ) 对于这样的版本控制,我们希望就树形结构的拓扑而言,相邻版本之间的差异不能超过$O(1)$,而Red-Black树可以做到。 === 红黑树的结构 由红、黑两类节点组成的BST,统一增设外部节点NULL, 使之成为真二叉树。 规则: 1. 树根:必为黑色 2. 外部节点:均为黑色 3. 红节点:只能有黑孩子(及黑父亲) 4. 外部节点: 黑深度(黑的真祖先数目)相等 - 亦即根(全树)的黑高度 - 子树的黑高度,即后代NULL的相对黑深度 #figure( image("fig\BST\62.png", width: 40%), caption: "红黑树" ) 将红节点提升至与其(黑)父亲等高,红边折叠起来——可以得到一棵等价的(2,4)树。 #figure( image("fig\BST\63.png", width: 80%), caption: "红黑树——等价的(2,4)树" ) 将黑节点与其红孩子视作关键码,再合并为B-树的超级节点。四种组合,分别对应于4阶B-树的一类内部节点。 #figure( image("fig\BST\64.png", width: 80%), caption: "红黑树——等价的B树" ) 包含$n$个内部节点的红黑树$T$,高度$h = O(log n)$: $ log_2 (n+1) <= h <= 2 log_2 (n+1) $ 若$T$高度为$h$,红/黑高度为$R$/$H$,则 $ H <= h <= H + R <= 2H $ 若$T$所对应的B-树为$T_B$,则$H$即是$T_B$的高度。$T_B$的每个节点,都恰好包含$T$的一个黑节点。 $ H <= log_2 ((n+1)/2) +1 = log_2 (n+1) $ 从而*红黑树是一棵BBST*。 `RedBlack`模板类 ```cpp template <typename T> class RedBlack : public BST<T> { //红黑树 public: //BST::search()等其余接口可直接沿用 BinNodePosi<T> insert( const T & e ); //插入(重写) bool remove( const T & e ); //删除(重写) protected: void solveDoubleRed( BinNodePosi<T> x ); //双红修正 void solveDoubleBlack( BinNodePosi<T> x ); //双黑修正 Rank updateHeight( BinNodePosi<T> x ); //更新节点x的高度(重写) }; #define stature( p ) ( ( p ) ? ( p )->height : 0 ) //外部节点黑高度为0,以上递推 template <typename T> int RedBlack<T>::updateHeight( BinNodePosi<T> x ) { return x->height = IsBlack( x ) + max( stature( x->lc ), stature( x->rc ) ); } ``` === 红黑树的插入 按BST规则插入关键码`e` ,`x = insert(e)`必为叶节点。 - 除非是首个节点(根), `x`的父亲`p = x->parent`必存在 - 首先将`x`染红:`x->color = isRoot(x) ? B : R` - 至此,条件1、 2、 4依然满足;但3不见得,有可能出现*双红/double-red*:`p->color == x->color == R` - 考查: - 祖父`g = p->parent` 必为黑 - 叔父`u = uncle( x ) = sibling( p )` 视`u`的颜色,分两种情况处理: #figure( image("fig\BST\65.png", width: 30%), caption: "红黑树——插入" ) ```cpp template <typename T> BinNodePosi<T> RedBlack<T>::insert( const T & e ) { // 确认目标节点不存在(留意对_hot的设置) BinNodePosi<T> & x = search( e ); if ( x ) return x; // 创建红节点x,以_hot为父,黑高度 = 0 x = new BinNode<T>( e, _hot, NULL, NULL, 0 ); _size++; // 如有必要,需做双红修正,再返回插入的节点 BinNodePosi<T> xOld = x; solveDoubleRed( x ); return xOld; } //无论原树中是否存有e,返回时总有x->data == e ``` 双红修正 ```cpp template <typename T> void RedBlack<T>::solveDoubleRed( BinNodePosi<T> x ) { if ( IsRoot( *x ) ) { //若已(递归)转至树根, 则将其转黑, 整树黑高度也随之递增 { _root->color = RB_BLACK; _root->height++; return; } //否则... BinNodePosi<T> p = x->parent; //考查x的父亲p(必存在) if ( IsBlack( p ) ) return; //若p为黑, 则可终止调整; 否则 BinNodePosi<T> g = p->parent; //x祖父g必存在,且必黑 BinNodePosi<T> u = uncle( x ); //以下视叔父u的颜色分别处理 if ( IsBlack( u ) ) { /* ... u为黑(或NULL) ... */ } else { /* ... u为红 ... */ } } } ``` ==== RR-1: u->color == B——一次3+4重构+两点反转红黑【一蹴而就】 此时, `x`、 `p`、 `g`的四个孩子(可能是外部节点) - 全为黑, 且 - 黑高度相同 按照B树理解如下图 #figure( image("fig\BST\66.png", width: 20%), caption: "红黑树——插入——RR-1" ) #figure( image("fig\BST\67.png", width: 20%), caption: "红黑树——插入——RR-1" ) 局部“3+4”重构:`b`转黑, `a`或`c`转红。在某三叉节点中插入红关键码后,原黑关键码不再居中(RRB或BRR)。调整的效果,是将三个关键码的颜色改为RBR。 #figure( image("fig\BST\68.png", width: 20%), caption: "红黑树——插入——RR-1" ) 如此调整, 一蹴而就。 ```cpp template <typename T> void RedBlack<T>::solveDoubleRed( BinNodePosi<T> x ) { /* ...... */ if ( IsBlack( u ) ) { //u为黑或NULL // 若x与p同侧,则p由红转黑, x保持红;否则, x由红转黑, p保持红 if ( IsLChild( *x ) == IsLChild( *p ) ) p->color = RB_BLACK; else x->color = RB_BLACK; g->color = RB_RED; //g必定由黑转红 BinNodePosi<T> gg = g->parent; //great-grand parent BinNodePosi<T> r = FromParentTo( *g ) = rotateAt( x ); r->parent = gg; //调整之后的新子树,需与原曾祖父联接 } else { /* ... u为红 ... */ } } ``` ==== RR-2: u->color == R——上溢解决(无需旋转):叔父染黑+祖父染红【递归上溯】 在B-树中,等效于超级节点发生上溢。 #figure( image("fig\BST\69.png", width: 20%), caption: "红黑树——插入——RR-2" ) #figure( image("fig\BST\70.png", width: 20%), caption: "红黑树——插入——RR-2" ) `p`与`u`转黑,`g`转红:在B-树中,等效于节点分裂,关键码`g`上升一层。 #figure( image("fig\BST\71.png", width: 20%), caption: "红黑树——插入——RR-2" ) 可能继续向上传递——亦即, `g`与`parent(g)`再次构成双红。等效地将`g`视作新插入的节点,区分以上两种情况,如法处置。 `g`若果真到达树根, 则强行将其转为黑色(整树黑高度加一)。 ```cpp template <typename T> void RedBlack<T>::solveDoubleRed( BinNodePosi<T> x ) { /* ...... */ if ( IsBlack( u ) ) { /* ... u为黑(含NULL) ... */ } else { //u为红色 p->color = RB_BLACK; p->height++; //p由红转黑,增高 u->color = RB_BLACK; u->height++; //u由红转黑,增高 g->color = RB_RED; //在B-树中g相当于上交给父节点的关键码,故暂标记为红 solveDoubleRed( g ); //继续调整:若已至树根,接下来的递归会将g转黑(尾递归) } } ``` `RedBlack::insert()`仅需$O(log n)$时间,至多$O(log n)$次染色和$O(1)$次旋转。 #align( center, table( columns: (auto, auto, auto, auto), align: center, // align: horizon, [], [*旋转*], [*染色*],[*此后*], [u为黑], [1 or 2], [2], [调整完成], [u为红], [0], [3], [递归上溯], ) ) #figure( image("fig\BST\72.png", width: 30%), caption: "红黑树——插入——总结" ) === 红黑树的删除 首先按照BST常规算法,执行`r = removeAt( x, _hot )`,实际被摘除的可能是`x`的前驱或后继`w`,简捷起见,以下不妨统称作`x`。 `x`由孩子`r`接替,此时另一孩子`k`必为`NULL` - 但在随后的调整过程中`x`可能逐层上升 - 故需假想地、统一地、等效地理解为: - `k`为一棵黑高度与`r`相等的子树,且 - 随`x`一并摘除(尽管实际上从未存在过) #figure( image("fig\BST\73.png", width: 30%), caption: "红黑树——删除" ) ```cpp template <typename T> bool RedBlack<T>::remove( const T & e ) { BinNodePosi<T> & x = search( e ); if ( !x ) return false; //查找定位 BinNodePosi<T> r = removeAt( x, _hot ); //删除_hot的某孩子, r指向其接替者 if ( ! ( -- _size ) ) return true; //若删除后为空树,可直接返回 if ( ! _hot ) { //若被删除的是根, 则 _root->color = RB_BLACK; //将其置黑, 并 updateHeight( _root ); //更新(全树)黑高度 return true; } //至此,原x(现r)必非根 // 若父亲(及祖先)依然平衡,则无需调整 if ( BlackHeightUpdated( * _hot ) ) return true; // 至此,必失衡 // 若替代节点r为红,则只需简单地翻转其颜色 if ( IsRed( r ) ) { r->color = RB_BLACK; r->height++; return true; } // 至此, r以及被其替代的x均为黑色 solveDoubleBlack( r ); //双黑调整(入口处必有 r == NULL) return true; } ``` 完成`removeAt()`之后 - 条件1、 2依然满足 - 但条件3、 4却不见得 *其一为红*: 在原树中,考查x与r - 若x为红,则条件3、 4自然满足 - 若r为红,则令其与x交换颜色,即可满足条件3、 4 一蹴而就。 #figure( image("fig\BST\73.png", width: 30%), caption: "红黑树——删除——RB" ) *双黑*: 若`x`与`r`均黑(double black),则不然。 - 摘除`x`并代之以`r`后,全树黑深度不再统一(稍后可见,等效于B-树中`x`所属节点下溢) - 在新树中,考查`r`的父亲、兄弟 - `p = r->parent //亦是原x的父亲` - `s = sibling( r )` 以下分四种情况处理: #figure( image("fig\BST\74.png", width: 30%), caption: "红黑树——删除——双黑" ) ```cpp template <typename T> void RedBlack<T>::solveDoubleBlack( BinNodePosi<T> r ) { BinNodePosi<T> p = r ? r->parent : _hot; if ( !p ) return; //r的父亲 BinNodePosi<T> s = (r == p->lc) ? p->rc : p->lc; //r的兄弟 if ( IsBlack( s ) ) { //兄弟s为黑 BinNodePosi<T> t = NULL; //s的红孩子(若左、右孩子皆红,左者优先;皆黑时为NULL) if ( IsRed ( s->rc ) ) t = s->rc; if ( IsRed ( s->lc ) ) t = s->lc; if ( t ) { /* ... 黑s有红孩子: BB-1 ... */ } else { /* ... 黑s无红孩子: BB-2R或BB-2B ... */ } } else { /* ... 兄弟s为红: BB-3 ... */ } } ``` ==== BB-1:s为黑,且(侄子是红的)至少有一个红孩子t——下溢解决:一次“3+4”重构+三次染色【一蹴而就】 #figure( image("fig\BST\75.png", width: 30%), caption: "红黑树——删除——双黑——BB-1" ) #figure( image("fig\BST\76.png", width: 30%), caption: "红黑树——删除——双黑——BB-1" ) “3+4”重构: - `t ~ a` - `s ~ b` - `p ~ c` 重新着色: - `r`保持黑 - `a`、 `c`染黑 - `b`继承`p`的原色 如此,红黑树性质在全局得以恢复。 如果按照B树理解:通过关键码的旋转,消除超级节点的下溢。 在对应的B-树中 - `p`若为红,问号之一为黑关键码 - `p`若为黑,必自成一个超级节点 #figure( image("fig\BST\77.png", width: 30%), caption: "红黑树——删除——双黑——BB-1" ) #figure( image("fig\BST\78.png", width: 30%), caption: "红黑树——删除——双黑——BB-1" ) ```cpp if ( IsBlack( s ) ) { //兄弟s为黑 /* ...... */ if ( t ) { //黑s有红孩子: BB-1 RBColor oldColor = p->color; //备份p颜色,并对t、父亲、祖父 BinNodePosi<T> b = FromParentTo( *p ) = rotateAt( t ); //旋转 if (HasLChild( *b )) { b->lc->color = RB_BLACK; updateHeight( b->lc ); } if (HasRChild( *b )) { b->rc->color = RB_BLACK; updateHeight( b->rc ); } b->color = oldColor; updateHeight( b ); //新根继承原根的颜色 } else { /* ... 黑s无红孩子: BB-2R或BB-2B ... */ } } else { /* ... 兄弟s为红: BB-3 ... */ } ``` ==== BB-2R: s为黑,且两个孩子均为黑; p为红——下溢解决:两个染色【一蹴而就】 - `r`保持黑;`s`转红;`p`转黑 - 在对应的B-树中,等效于下溢节点与兄弟合并 - 红黑树性质在全局得以恢复——一蹴而就 失去关键码`p`后,上层节点不会继而下溢。因为合并之前,在`p`之左或右侧还应有一个黑关键码。 #figure( image("fig\BST\79.png", width: 30%), caption: "红黑树——删除——双黑——BB-2R" ) #figure( image("fig\BST\80.png", width: 30%), caption: "红黑树——删除——双黑——BB-2R" ) ==== BB-2B: s为黑,且两个孩子均为黑; p为黑——下溢解决:一次染色【递归上溯】 - `s`转红; `r`与`p`保持黑 - 红黑树性质在*局部*得以恢复 - 在对应的B-树中,等效于下溢节点与兄弟合并 - 合并前,`p`和`s`均属于单关键码节点 孩子的下溢修复后,父节点继而下溢,递归上溯$O(log n)$层 #figure( image("fig\BST\81.png", width: 30%), caption: "红黑树——删除——双黑——BB-2B" ) #figure( image("fig\BST\82.png", width: 30%), caption: "红黑树——删除——双黑——BB-2B" ) ```cpp if ( IsBlack( s ) ) { //兄弟s为黑 /* ...... */ if ( t ) { /* ... 黑s有红孩子: BB-1 ... */ } else { /* 黑s无红孩子 */ s->color = RB_RED; s->height--; //s转红 if ( IsRed( p ) ) //BB-2R: p转黑,但黑高度不变 { p->color = RB_BLACK; } else //BB-2B: p保持黑,但黑高度下降;递归修正 { p->height--; solveDoubleBlack( p ); } } } else { /* ... 兄弟s为红: BB-3 ... */ } ``` ==== BB-3: s为红(其孩子均为黑)——一次旋转+两次染色【化归成一蹴而就】 - 绕`p`单旋; `s`红转黑, `p`黑转红 - 黑高度依然异常,但`r`有了一个新的黑兄弟`s'` - 故转化为前述情况,而且`p`已转红,接下来 - 绝不会是BB-2B - 而只能是BB-2R或BB-1 - 于是,再经一轮调整红黑树性质必然全局恢复。 #figure( image("fig\BST\83.png", width: 30%), caption: "红黑树——删除——双黑——BB-3" ) #figure( image("fig\BST\84.png", width: 30%), caption: "红黑树——删除——双黑——BB-3" ) ```cpp if ( IsBlack( s ) ) { //兄弟s为黑 if ( t ) { /* ... 黑s有红孩子: BB-1 ... */ } else { /* ... 黑s无红孩子: BB-2R或BB-2B ... */ } } else { //兄弟s为红: BB-3 s->color = RB_BLACK; p->color = RB_RED; //s转黑, p转红 BinNodePosi<T> t = IsLChild( *s ) ? s->lc : s->rc; //取t与其父s同侧 _hot = p; FromParentTo( *p ) = rotateAt( t ); //对t及其父亲、祖父做平衡调整 solveDoubleBlack( r ); //继续修正r——此时p已转红,故后续只能是BB-1或BB-2R } ``` `RedBlack::remove()`仅需$O(log n)$时间,至多$O(log n)$次染色和$O(1)$次旋转。 #align( center, table( columns: (auto, auto, auto, auto), align: center, // align: horizon, [], [*旋转*], [*染色*],[*此后*], [BB-1:黑s有红子t], [1or2], [3], [调整完成], [BB-2R:黑s无红子,p红], [0], [2], [调整完成], [BB-2B:黑s无红子,p黑], [0], [1], [递归上溯], [BB-3:红s], [1], [2], [转为(1)或(2R),调整完成], ) ) #figure( image("fig\BST\85.png", width: 80%), caption: "红黑树——删除——双黑——总结" )
https://github.com/xbunax/tongji-undergrad-thesis
https://raw.githubusercontent.com/xbunax/tongji-undergrad-thesis/main/README-EN.md
markdown
MIT License
# :page_facing_up: Tongji University Undergraduate Thesis Typst Template (STEM) [中文](README.md) | English > [!CAUTION] > Since the Typst project is still in the development stage and support for some features is not perfect, there may be some issues with this template. If you encounter problems while using it, please feel free to submit an issue or PR and we will try our best to solve it. > > In the mean time, we also welcome you to use [our $\LaTeX$ template](https://github.com/TJ-CSCCG/tongji-undergrad-thesis). ## Sample Display Below are displayed in order the "Cover", "Chinese Abstract", "Table of Contents", "Main Content", "References", and "Acknowledgments". <p align="center"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0001.jpg" width="30%"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0002.jpg" width="30%"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0004.jpg" width="30%"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0005.jpg" width="30%"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0019.jpg" width="30%"> <img src="https://media.githubusercontent.com/media/TJ-CSCCG/TJCS-Images/tongji-undergrad-thesis-typst/preview/main_page-0020.jpg" width="30%"> </p> ## How to Use ### Local Compilation #### 1. Install Typst Refer to the [Typst](https://github.com/typst/typst?tab=readme-ov-file#installation) official documentation for installation. #### 2. Clone this project ```bash git clone https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst.git cd tongji-undergrad-thesis-typst ``` #### 3. Download Fonts Please download the font files from the [`fonts`](https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst/tree/fonts) branch of this repository and place them in the `fonts` folder, or install the font files to your system. #### 4. Compile Modify related files as needed, then execute the following command to compile. ```bash typst --font-path ./fonts compile main.typ ``` > [!TIP] > If you find that the fonts are not displayed properly, please install the font files in the `fonts` folder to your system and then execute the compile command. ### Online Compilation Use this template for online compilation at [Typst App](https://typst.app). ## How to Contribute to This Project? Please see [How to pull request](CONTRIBUTING.md/#how-to-pull-request). ## Open Source License This project is licensed under the [MIT License](LICENSE). ### Disclaimer This project uses fonts from the FounderType font library, with copyright belonging to FounderType. This project is for learning and communication purposes only and must not be used for commercial purposes. ## Acknowledgments for Outstanding Contributions * This project originated from [FeO3](https://github.com/seashell11234455)'s initial version project [tongji-undergrad-thesis-typst](https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst/tree/lky). * Later, [RizhongLin](https://github.com/RizhongLin) improved the template to better meet the requirements of Tongji University undergraduate thesis, and added basic tutorials for Typst. We are very grateful to the above contributors for their efforts, which have provided convenience and help to more students. When using this template, if you find this project helpful for your graduation project or thesis, we hope you can express your thanks and respect in your acknowledgments section. ## Acknowledgments for Open Source Projects We have learned a lot from the excellent open-source projects of top universities: * [lucifer1004/pkuthss-typst](https://github.com/lucifer1004/pkuthss-typst) * [werifu/HUST-typst-template](https://github.com/werifu/HUST-typst-template) ## Contact ```python # Python [ 'rizhonglin@$.%'.replace('$', 'epfl').replace('%', 'ch'), ] ```
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/clamp-panic_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 20pt, margin: 0pt) #v(22pt) #block(fill: red, width: 100%, height: 10pt, radius: 4pt)
https://github.com/OR-gatti/ThesisTemplate-Typst
https://raw.githubusercontent.com/OR-gatti/ThesisTemplate-Typst/main/README.md
markdown
# ThesisTemplate-Typst 論文をTypstで書く人向けのサンプル、テンプレートです。添付の[PDFファイル](https://github.com/OR-gatti/ThesisTemplate-Typst/blob/main/sample.pdf)でどのようになるのか確認できます。足りないところは各自補ってください。 フォントや空白、改行などのフォーマットが調整不足なところがあるので随時修正します。
https://github.com/Blezz-tech/math-typst
https://raw.githubusercontent.com/Blezz-tech/math-typst/main/Варианты/Остальное.typ
typst
#import "/lib/my.typ": * = Остальное == Задание 50. #task("Задание") Смешав $43%$ и $89%$ растворы кислоты и добавив $10$ кг чистой воды, получили $69%$ раствор кислоты. Если бы вместо $10$ кг воды добавили $10$ кг $50%$ раствора той же кислоты, то получили бы $73%$ раствор кислоты. Сколько килограммов $43%$ раствора использовали для получения смеси? #answer("Решение") Ответ: $$ == Задание 51. #task("Задание") Смешав $38%$ и $52%$ растворы кислоты и добавив $10$ кг чистой воды, получили $36%$ раствор кислоты. Если бы вместо $10$ кг воды добавили $10$ кг $50%$ раствора той же кислоты, то получили бы $46%$ раствор кислоты. Сколько килограммов $38%$ раствора использовали для получения смеси? #answer("Решение") Ответ: $$
https://github.com/QRWells/uni-theme
https://raw.githubusercontent.com/QRWells/uni-theme/main/uni-theme-en.typ
typst
MIT License
#import "@preview/polylux:0.3.1": * #let theme-colors = state("theme-colors", (:)) #let theme-short-title = state("theme-short-title", none) #let theme-short-author = state("theme-short-author", none) #let theme-progress-bar = state("theme-progress-bar", true) #let theme-date = state("theme-date", datetime.today()) #let theme-sans = state("theme-sans", "DejaVu Sans") #let theme-serif = state("theme-serif", "DejaVu Serif") #let uni-theme( aspect-ratio: "16-9", short-title: none, short-author: none, date: datetime.today(), progress-bar: true, color-a: rgb("115E59"), color-b: rgb("0A2463"), color-c: rgb("815E5B"), sans: "DejaVu Sans", serif: "DejaVu Serif", body ) = { set page( paper: "presentation-" + aspect-ratio, margin: 0em, header: none, footer: none, ) set text(size: 25pt, font: sans) show footnote.entry: set text(size: .6em) show link: it => underline(it) show raw.where(block: false): box.with( fill: luma(245), inset: (x: 8pt, y: 1pt), outset: (y: 4pt, x : -2pt), radius: 4pt, ) show raw.where(block: true): block.with( fill: luma(245), width: 100%, inset: (x: 8pt, y: 4pt), outset: (y: 8pt), radius: 4pt, ) theme-progress-bar.update(progress-bar) theme-colors.update((a: color-a, b: color-b, c: color-c)) theme-short-title.update(short-title) theme-short-author.update(short-author) theme-date.update(date) theme-sans.update(sans); theme-serif.update(serif); body } #let title-slide( title: [], subtitle: none, authors: (), lab-name: none, institution-name: none, logo: none, background-img: none ) = { let authors = if type(authors) == "array" { authors } else { (authors,) } let content = locate( loc => { let colors = theme-colors.at(loc) let date = theme-date.at(loc) if logo != none { align(right, logo) } align(horizon, { pad(left: 1em, { block( inset: 0em, breakable: false, { text(size: 2em, fill: colors.a, strong(title)) if subtitle != none { v(1em, weak: true) text(size: 1.25em, fill: colors.a.lighten(25%), subtitle) } } ) set text(size: 1em) grid( columns: (1fr,) * calc.min(authors.len(), 3), column-gutter: 1em, row-gutter: 1em, ..authors.map(author => text(fill: black, author)) ) if lab-name != none { parbreak() text(size: .9em, [#lab-name Lab.]) } if institution-name != none { linebreak() text(size: .8em, institution-name) } if date != none { linebreak() text(size: .7em, date.display("[month repr:long] [day padding:none] [year]")) } }) }) }) set page( background: { set image(fit: "stretch", width: 100%, height: 100%) background-img }, margin: 1em, ) if background-img != none polylux-slide(content) } #let slide( title: none, sub-title: none, header: none, footer: none, new-section: none, body ) = { let body = pad(x: 2em, y: .5em, body) let progress-barline = locate( loc => { if theme-progress-bar.at(loc) { let cell = block.with( width: 100%, height: 100%, above: 0pt, below: 0pt, breakable: false ) let colors = theme-colors.at(loc) utils.polylux-progress( ratio => { grid( rows: 2pt, columns: (ratio * 100%, 1fr), cell(fill: colors.a), cell(fill: colors.c) ) }) } else { [] } }) let header-text = { if header != none { header } else if title != none { if new-section != none { utils.register-section(new-section) } locate( loc => { let colors = theme-colors.at(loc) let serif = theme-serif.at(loc) block(inset: (x: .5em), grid( columns: (60%, 40%), stack( dir: ttb, spacing: 20%, align(top + left, heading(level: 2, text(fill: colors.a, title))), align(top + left, text(font: serif, style: "italic", size: 0.75em, fill: colors.a.lighten(55%), sub-title)) ), align(top + right, text(weight: "bold", fill: colors.b.lighten(80%), utils.current-section) ))) }) } else { [] } } let header = { set align(top) grid(rows: (auto, auto), row-gutter: .5em, progress-barline, header-text) } let footer = { set text(size: 10pt) set align(center + bottom) let cell(fill: none, it) = rect( width: 100%, height: 100%, inset: 1mm, outset: 0mm, fill: fill, stroke: none, align(horizon, text(fill: white, it)) ) if footer != none { footer } else { locate( loc => { let colors = theme-colors.at(loc) let date = theme-date.at(loc) show: block.with(width: 100%, height: auto, fill: colors.b) grid( columns: (25%, 1fr, 15%, 10%), rows: (1.5em, auto), cell(fill: colors.a, theme-short-author.display()), cell(theme-short-title.display()), cell(fill: colors.c, date.display("[year]/[month]/[day]")), cell(fill: colors.c, logic.logical-slide.display() + [~/~] + utils.last-slide-number) ) }) } } let top-margin = if sub-title != none { 3em } else { 2.5em } set page( margin: ( top: top-margin, bottom: 0.6em, x: 0em ), header: header, footer: footer, footer-descent: 0em, header-ascent: 0.6em, ) logic.polylux-slide(body) } #let focus-slide(background-color: none, background-img: none, body) = { let background-color = if background-img == none and background-color == none { rgb("#0C6291") } else { background-color } set page(fill: background-color, margin: 1em) if background-color != none set page( background: { set image(fit: "stretch", width: 100%, height: 100%) background-img }, margin: 1em, ) if background-img != none set text(fill: white, size: 2em) logic.polylux-slide(align(horizon, body)) }
https://github.com/typst-cn/typst-programming-tutorial
https://raw.githubusercontent.com/typst-cn/typst-programming-tutorial/master/README.md
markdown
# Typst 编程入门(WIP) ## Hello Typst `代码` ```rust #let content = "Hello Typst! \n 你好, Typst!" #[ #content ] ``` `输出` ![Hello Typst](./assets/images/hello-typst-result.png)
https://github.com/dikkadev/typst-statastic
https://raw.githubusercontent.com/dikkadev/typst-statastic/main/lib.typ
typst
The Unlicense
/// Extracts a specific column from the given dataset based on the column. /// /// - data (array): The dataset. /// - colId (int): The identifier for the column to be extracted. /// -> array #let extractColumn(data, colId) = { let column = () for row in data { column.push(row.at(colId)) } column } /// Converts an array's elements to floating point numbers. /// /// - arr (array): Array with elements to be converted. /// -> array #let tofloatArray(arr) = { let res = () for el in arr { if el == "" { res.push(0.0) } else { res.push(float(el)) } } res } /// Converts an array's elements to integers. /// /// - arr (array): Array with elements to be converted. /// -> array #let toIntArray(arr) = { let res = () for el in arr { if el == "" { res.push(0) } else { res.push(int(el)) } } res } /// Determines if a given value is an integer. /// /// - val (mixed): The value to be checked. /// -> boolean #let isInt(val) = { let f = float(val) let i = int(f) val == i } /// Calculates a value between two numbers at a specific fraction. /// /// - lower (float): The lower number. /// - upper (float): The upper number. /// - fraction (float): The fraction between the two numbers. /// -> float #let lerp(lower, upper, fraction) = { let diff = upper - lower lower + (diff * fraction) } /// Calculates the average of an array's elements. /// /// - arr (array): Array of numbers. /// -> float #let arrayAvg(arr) = { let col = tofloatArray(arr) col.sum() / col.len() } /// Calculates the average of a specific column in a dataset. /// /// - data (array): The dataset. /// - colId (int): The identifier for the column. /// -> float #let avg(data, colId) = { arrayAvg(extractColumn(data, colId)) } /// Calculates the median of an array's elements. /// /// - arr (array): Array of numbers. /// -> float #let arrayMedian(arr) = { let col = tofloatArray(arr).sorted() let len = col.len() if calc.rem(len, 2) == 0 { let middle = calc.quo(len, 2) (col.at(middle - 1) + col.at(middle)) / 2 } else { let middle = calc.quo(len, 2) col.at(middle) } } /// Calculates the median of a specific column in a dataset. /// /// - data (array): The dataset. /// - colId (int): The identifier for the column. /// -> float #let median(data, colId) = { arrayMedian(extractColumn(data, colId)) } /// Calculates the mode of an integer array. /// Converts all floats to integers. /// /// - arr (array): Array of integers. /// -> array #let arrayIntMode(arr) = { let col = arr let unique = col.dedup() let counts = (:) for k in unique { counts.insert(str(k), 0) } for k in col { counts.at(str(k)) += 1 } let highestModeCount = 0 for (k, v) in counts.pairs() { if (v > highestModeCount) { highestModeCount = v } } let modes = () for (k, v) in counts.pairs() { if (v == highestModeCount) { modes.push(int(k)) } } modes } /// Calculates the integer mode of a specific column in a dataset. /// Converts all floats to integers. /// /// - data (array): The dataset. /// - colId (int): The identifier for the column. /// -> array #let intMode(data, colId) = { arrayIntMode(toIntArray(tofloatArray((extractColumn(data, colId))))) } /// Calculates the variance of an array's elements. /// /// - arr (array): Array of numbers. /// -> float #let arrayVar(arr) = { let col = tofloatArray(arr) let len = col.len() let mean = col.sum() / len let varSum = 0 for el in col { varSum += calc.pow(el - mean, 2) } varSum / (len - 1) } /// Calculates the variance of a specific column in a dataset. /// /// - data (array): The dataset. /// - colId (int): The identifier for the column. /// -> float #let var(data, colId) = { arrayVar(extractColumn(data, colId)) } /// Calculates the standard deviation of an array's elements. /// /// - arr (array): Array of numbers. /// -> float #let arrayStd(arr) = { let var = arrayVar(arr) calc.sqrt(var) } /// Calculates the standard deviation of a specific column in a dataset. /// /// - data (array): The dataset. /// - colId (int): The identifier for the column. /// -> float #let std(data, colId) = { arrayStd(extractColumn(data, colId)) } /// Calculates a specific percentile of an array's elements. /// /// - arr (array): Array of numbers. /// - p (float): The desired percentile (between 0 and 1). /// -> float #let arrayPercentile(arr, p) = { let col = tofloatArray(arr).sorted() let n = col.len() - 1 let pos = p * n if (isInt(pos)) { col.at(int(pos)) } else { let low = col.at(calc.floor(pos)) let high = col.at(calc.ceil(pos)) lerp(low, high, calc.fract(pos)) } } /// Calculates a specific percentile of a column in a dataset. /// /// - data (array): The dataset. /// - colId (int): The identifier for the column. /// - p (float): The desired percentile (between 0 and 1). /// -> float #let percentile(data, colId, p) = { arrayPercentile(extractColumn(data, colId), p) } /// Computes a set of statistical measures for an array. /// Includes: average, median, integer mode, variance, standard deviation, and some percentiles. /// /// - arr (array): Array of numbers. /// -> dictionary #let arrayStats(arr) = { ( "avg": arrayAvg(arr), "median": arrayMedian(arr), "intMode": arrayIntMode(arr), "var": arrayVar(arr), "std": arrayStd(arr), "25percentile": arrayPercentile(arr, 0.25), "50percentile": arrayPercentile(arr, 0.50), "75percentile": arrayPercentile(arr, 0.75), "95percentile": arrayPercentile(arr, 0.95), ) } /// Computes a set of statistical measures for a specific column in a dataset. /// Includes: average, median, integer mode, variance, standard deviation, and some percentiles. /// /// - data (array): The dataset. /// - colId (int): The identifier for the column. /// -> dictionary #let stats(data, colId) = { ( "avg": avg(data, colId), "median": median(data, colId), "intMode": intMode(data, colId), "var": var(data, colId), "std": std(data, colId), "25percentile": percentile(data, colId, 0.25), "50percentile": percentile(data, colId, 0.50), "75percentile": percentile(data, colId, 0.75), "95percentile": percentile(data, colId, 0.95), ) } /// Calculates the covariance between two arrays' elements. /// /// - arrX (array): First array of numbers. /// - arrY (array): Second array of numbers. /// -> float #let arrayCovariance(arrX, arrY) = { let x = tofloatArray(arrX) let y = tofloatArray(arrY) let n = x.len() if n != y.len() { error("Arrays must have the same length") } let meanX = arrayAvg(x) let meanY = arrayAvg(y) let covSum = 0.0 for ((xi, yi)) in x.zip(y) { covSum += (xi - meanX) * (yi - meanY) } covSum / (n - 1) } /// Performs quadratic regression on two arrays of data. /// Fits the model [$ y = a x^{2} + b x + c $]. /// Returns a dictionary with keys "a", "b", "c", and "r_squared". /// /// - arrX (array): Array of independent variable values. /// - arrY (array): Array of dependent variable values. /// -> dictionary with keys "slope", "intercept", "r_squared" #let arrayLinearRegression(arrX, arrY) = { let x = tofloatArray(arrX) let y = tofloatArray(arrY) let n = x.len() if n != y.len() { error("Arrays must have the same length") } let meanX = arrayAvg(x) let meanY = arrayAvg(y) let varX = arrayVar(x) let covXY = arrayCovariance(x, y) let slope = covXY / varX let intercept = meanY - slope * meanX // Compute R-squared let totalSS = 0.0 let residualSS = 0.0 for ((xi, yi)) in x.zip(y) { let yPred = intercept + slope * xi totalSS += calc.pow(yi - meanY, 2) residualSS += calc.pow(yi - yPred, 2) } let r_squared = 1 - residualSS / totalSS ( "slope": slope, "intercept": intercept, "r_squared": r_squared, ) } /// Performs linear regression on two columns in a dataset. /// /// - data (array): The dataset. /// - colX (int): The column index for the independent variable. /// - colY (int): The column index for the dependent variable. /// -> dictionary with keys "slope", "intercept", "r_squared" #let linearRegression(data, colX, colY) = { let x = extractColumn(data, colX) let y = extractColumn(data, colY) arrayLinearRegression(x, y) } /// Performs exponential regression on two arrays of data. /// Fits the model [$ y = a e^{b x} $]. /// Returns a dictionary with keys "a", "b", and "r_squared". /// /// - arrX (array): Array of independent variable values. /// - arrY (array): Array of dependent variable values. /// -> dictionary #let arrayQuadraticRegression(arrX, arrY) = { let x = tofloatArray(arrX) let y = tofloatArray(arrY) let n = x.len() if n != y.len() { error("Arrays must have the same length") } // Compute sums needed for the normal equations let sumX = x.sum() let sumY = y.sum() let sumXX = x.map(xi => xi * xi).sum() let sumXXX = x.map(xi => calc.pow(xi, 3)).sum() let sumXXXX = x.map(xi => calc.pow(xi, 4)).sum() let sumXY = x.zip(y).map(((xi, yi)) => xi * yi).sum() let sumXXY = x.zip(y).map(((xi, yi)) => calc.pow(xi, 2) * yi).sum() // Build the matrices for the normal equations let Sxx = sumXX - (sumX * sumX) / n let Sxy = sumXY - (sumX * sumY) / n let Sxx2 = sumXXX - (sumXX * sumX) / n let Sx2x2 = sumXXXX - (sumXX * sumXX) / n let Sx2y = sumXXY - (sumXX * sumY) / n // Calculate the coefficients let denom = Sxx * Sx2x2 - calc.pow(Sxx2, 2) if denom == 0 { error("Denominator in quadratic regression is zero") } let a = (Sx2y * Sxx - Sxy * Sxx2) / denom let b = (Sxy * Sx2x2 - Sx2y * Sxx2) / denom let c = (sumY - b * sumX - a * sumXX) / n // Compute R-squared let y_mean = sumY / n let totalSS = y.map(yi => calc.pow(yi - y_mean, 2)).sum() let residualSS = x.zip(y).map(((xi, yi)) => { let yi_pred = a * calc.pow(xi, 2) + b * xi + c calc.pow(yi - yi_pred, 2) }).sum() let r_squared = 1 - residualSS / totalSS ( "a": a, "b": b, "c": c, "r_squared": r_squared, ) } /// Performs quadratic regression on two columns in a dataset. /// Returns a dictionary with keys "a", "b", "c", and "r_squared". /// /// - data (array): The dataset. /// - colX (int): The column index for the independent variable. /// - colY (int): The column index for the dependent variable. /// -> dictionary #let quadraticRegression(data, colX, colY) = { let x = extractColumn(data, colX) let y = extractColumn(data, colY) arrayQuadraticRegression(x, y) } /// Performs logarithmic regression on two arrays of data. /// Fits the model [$ y = a + b \ln(x) $]. /// Returns a dictionary with keys "a", "b", and "r_squared". /// /// - arrX (array): Array of independent variable values. /// - arrY (array): Array of dependent variable values. /// -> dictionary #let arrayExponentialRegression(arrX, arrY) = { let x = tofloatArray(arrX) let y = tofloatArray(arrY) let n = x.len() if n != y.len() { error("Arrays must have the same length") } // Transform y by taking the natural logarithm let lnY = y.map(yi => calc.ln(yi)) // Now perform linear regression on x and lnY let meanX = arrayAvg(x) let meanLnY = arrayAvg(lnY) let varX = arrayVar(x) let covXY = arrayCovariance(x, lnY) let b = covXY / varX let lnA = meanLnY - b * meanX let a = calc.exp(lnA) // Compute R-squared let y_pred = x.map(xi => a * calc.exp(b * xi)) let totalSS = y.map(yi => calc.pow(yi - arrayAvg(y), 2)).sum() let residualSS = y.zip(y_pred).map(((yi, ypi)) => calc.pow(yi - ypi, 2)).sum() let r_squared = 1 - residualSS / totalSS ( "a": a, "b": b, "r_squared": r_squared, ) } /// Performs exponential regression on two columns in a dataset. /// Returns a dictionary with keys "a", "b", and "r_squared". /// /// - data (array): The dataset. /// - colX (int): The column index for the independent variable. /// - colY (int): The column index for the dependent variable. /// -> dictionary #let exponentialRegression(data, colX, colY) = { let x = extractColumn(data, colX) let y = extractColumn(data, colY) arrayExponentialRegression(x, y) } /////////////////////////// /// Performs logarithmic regression on two arrays of data. /// Fits the model [$ y = a + b \ln(x) $]. /// Returns a dictionary with keys "a", "b", and "r_squared". /// /// - arrX (array): Array of independent variable values (must be > 0). /// - arrY (array): Array of dependent variable values. /// -> dictionary #let arrayLogarithmicRegression(arrX, arrY) = { let x = tofloatArray(arrX) let y = tofloatArray(arrY) let n = x.len() if n != y.len() { error("Arrays must have the same length") } // Check that x values are greater than zero if x.any(xi => xi <= 0) { error("All x values must be greater than zero for logarithmic regression") } // Transform x by taking the natural logarithm let lnX = x.map(xi => calc.ln(xi)) // Now perform linear regression on lnX and y let meanLnX = arrayAvg(lnX) let meanY = arrayAvg(y) let varLnX = arrayVar(lnX) let covXY = arrayCovariance(lnX, y) let b = covXY / varLnX let a = meanY - b * meanLnX // Compute R-squared let y_pred = lnX.map(xi => a + b * xi) let totalSS = y.map(yi => calc.pow(yi - meanY, 2)).sum() let residualSS = y.zip(y_pred).map(((yi, ypi)) => calc.pow(yi - ypi, 2)).sum() let r_squared = 1 - residualSS / totalSS ( "a": a, "b": b, "r_squared": r_squared, ) } /// Performs logarithmic regression on two columns in a dataset. /// Returns a dictionary with keys "a", "b", and "r_squared". /// /// - data (array): The dataset. /// - colX (int): The column index for the independent variable (must be > 0). /// - colY (int): The column index for the dependent variable. /// -> dictionary #let logarithmicRegression(data, colX, colY) = { let x = extractColumn(data, colX) let y = extractColumn(data, colY) arrayLogarithmicRegression(x, y) } /////////////////////////////////////// /// Performs power regression on two arrays of data. /// Fits the model [$ y = a x^{b} $]. /// Returns a dictionary with keys "a", "b", and "r_squared". /// /// - arrX (array): Array of independent variable values (must be > 0). /// - arrY (array): Array of dependent variable values (must be > 0). /// -> dictionary #let arrayPowerRegression(arrX, arrY) = { let x = tofloatArray(arrX) let y = tofloatArray(arrY) let n = x.len() if n != y.len() { error("Arrays must have the same length") } // Check that x and y values are greater than zero if x.any(xi => xi <= 0) or y.any(yi => yi <= 0) { error("All x and y values must be greater than zero for power regression") } // Transform both x and y by taking the natural logarithm let lnX = x.map(xi => calc.ln(xi)) let lnY = y.map(yi => calc.ln(yi)) // Now perform linear regression on lnX and lnY let meanLnX = arrayAvg(lnX) let meanLnY = arrayAvg(lnY) let varLnX = arrayVar(lnX) let covXY = arrayCovariance(lnX, lnY) let b = covXY / varLnX let lnA = meanLnY - b * meanLnX let a = calc.exp(lnA) // Compute R-squared let y_pred = x.map(xi => a * calc.pow(xi, b)) let totalSS = y.map(yi => calc.pow(yi - arrayAvg(y), 2)).sum() let residualSS = y.zip(y_pred).map(((yi, ypi)) => calc.pow(yi - ypi, 2)).sum() let r_squared = 1 - residualSS / totalSS ( "a": a, "b": b, "r_squared": r_squared, ) } /// Performs power regression on two columns in a dataset. /// Returns a dictionary with keys "a", "b", and "r_squared". /// /// - data (array): The dataset. /// - colX (int): The column index for the independent variable (must be > 0). /// - colY (int): The column index for the dependent variable (must be > 0). /// -> dictionary #let powerRegression(data, colX, colY) = { let x = extractColumn(data, colX) let y = extractColumn(data, colY) arrayPowerRegression(x, y) }
https://github.com/HKFoggyU/hkust-thesis-typst
https://raw.githubusercontent.com/HKFoggyU/hkust-thesis-typst/main/hkust-thesis/templates/abstract-page.typ
typst
LaTeX Project Public License v1.3c
#import "../imports.typ": * #import "../utils/invisible-heading.typ": invisible-heading #let abstract-page( config: (:), info: (:), it, ) = { let (degreeFull, degreeShort) = set-degree(info.degree) [ #set align(center) #pagebreak(weak: true, to: if config.twoside { "odd" }) #invisible-heading("Abstract") #heading(outlined: false)[#text(size: constants.font-sizes.title)[#info.title.join("\n")]] #do-repeat([#linebreak()], 1) by #info.author #do-repeat([#linebreak()], 2) #info.department #do-repeat([#linebreak()], 1) The Hong Kong University of Science and Technology #do-repeat([#linebreak()], 2) Abstract #do-repeat([#linebreak()], 1) ] // abstract text set align(left) set par( leading: constants.abstract-linespacing, ) it }
https://github.com/NamLe0609/bias-ai-report
https://raw.githubusercontent.com/NamLe0609/bias-ai-report/main/table.typ
typst
= Ethical impact assessment informed by VSD #show figure: set block(breakable: true) #figure( table( columns: (1fr, 2fr, 2fr), inset: 5.9pt, align: left, [Stakeholders], [Values], [Potential risks/harms], [Healthcare providers, such as a doctor or a nurse (Direct)], [Respect for human autonomy -\ - The model's decisions should not be absolute, and it's limits needs to be recognized - The model should act as an aid to help healthcare providers make their decisions, providing an additional point of view], [A misdiagnosis might be given, in which case the healthcare provider might be forced to blindly follow the model's decision. If this results in harm to the patient, the healthcare provider could be held accountable for medical negligence, potentially leading to revocation of their medical license.], [Patient (Indirect)], [Privacy, informed consent -\ - A patient should have absolute authority over their data - Hospitals/medical institutions are expected to not record, store and process data unless given explicit consent], [Personal data stored in hospital databases could be breached and leaked. Bad actors could then use this data for nefarious purposes, such as identity theft or blackmail. In rare cases, institutions could (mis)use this data for their own benefit, such as selling it to third parties despite GDPR regulations.], [Medical institution (Indirect)], [Human welfare, freedom from bias, efficiency -\ - Existing system must work well for all individuals despite their differences to minimize casualties - All forms of bias must be prevented to ensure equal treatment of all patients - The model should be able to provide diagnoses in a timely manner], [A biased diagnosis, whether it be due to the model's false output or misinterpretation of the model's output by a healthcare provider, could lead to lives lost. The same applies to a delayed diagnosis. The institution could then face lawsuits, have to compensate patients financially, or even have their funding rescinded. In less grave situations, the institution's reputation could be damaged.], [Pharmaceutical Company, model output data consumer (Direct)], [Accuracy, environmental sustainability -\ - Production and distribution chains could be disrupted based on the model's output data. - Overproduction of medicine could also lead to resource wastage as well as environmental pollution], [Bad quality data could cause the company to produce and distribute the wrong amounts/types of medicine, leading to a loss of profit. The company could also be held accountable for any environmental damage caused by overproduction.], [Insurance companies (Indirect)], [Explicability -\ - The outcome of the model must be clear to prevent any ambiguity as to whether or not insurance must cover for a client], [A correct, but unexplainable diagnosis could lead to a refusal to cover the patient's medical expenses. Disputes over this would deteriorate the relationship between all parties involved.], [Government institution, regulators and policymakers (Indirect)], [Trust, accountability - - A government's aim is to maintain the trust of its citizens, and so it must regulate use of the technology - The government must also be partially accountable for the technology's use and its consequences], [Any technologies, in its inception, are prone to misuse @Datasheet-for-dataset. If the government fails to regulate the technology, lots of inhumane Even with regulation, if the technology is misused, the government has a duty to take some responsibility for the consequences.], ), caption: [Ethical impact assessment using VSD in a hospital setting.] ) <ethical-impact-assessment-hospital>
https://github.com/haxibami/haxipst
https://raw.githubusercontent.com/haxibami/haxipst/main/src/main.typ
typst
#import "./resume/resume.typ": * #import "./lib/set-metadata.typ": * #import "./lib/better-indent.typ": * #import "./lib/better-heading.typ": * #import "./lib/macro.typ"
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/101.%20credentials.html.typ
typst
credentials.html After Credentials December 2008A few months ago I read a New York Times article on South Korean cram schools that said Admission to the right university can make or break an ambitious young South Korean. A parent added: "In our country, college entrance exams determine 70 to 80 percent of a person's future." It was striking how old fashioned this sounded. And yet when I was in high school it wouldn't have seemed too far off as a description of the US. Which means things must have been changing here.The course of people's lives in the US now seems to be determined less by credentials and more by performance than it was 25 years ago. Where you go to college still matters, but not like it used to.What happened?_____Judging people by their academic credentials was in its time an advance. The practice seems to have begun in China, where starting in 587 candidates for the imperial civil service had to take an exam on classical literature. [1] It was also a test of wealth, because the knowledge it tested was so specialized that passing required years of expensive training. But though wealth was a necessary condition for passing, it was not a sufficient one. By the standards of the rest of the world in 587, the Chinese system was very enlightened. Europeans didn't introduce formal civil service exams till the nineteenth century, and even then they seem to have been influenced by the Chinese example.Before credentials, government positions were obtained mainly by family influence, if not outright bribery. It was a great step forward to judge people by their performance on a test. But by no means a perfect solution. When you judge people that way, you tend to get cram schools—which they did in Ming China and nineteenth century England just as much as in present day South Korea.What cram schools are, in effect, is leaks in a seal. The use of credentials was an attempt to seal off the direct transmission of power between generations, and cram schools represent that power finding holes in the seal. Cram schools turn wealth in one generation into credentials in the next.It's hard to beat this phenomenon, because the schools adjust to suit whatever the tests measure. When the tests are narrow and predictable, you get cram schools on the classic model, like those that prepared candidates for Sandhurst (the British West Point) or the classes American students take now to improve their SAT scores. But as the tests get broader, the schools do too. Preparing a candidate for the Chinese imperial civil service exams took years, as prep school does today. But the raison d'etre of all these institutions has been the same: to beat the system. [2]_____History suggests that, all other things being equal, a society prospers in proportion to its ability to prevent parents from influencing their children's success directly. It's a fine thing for parents to help their children indirectly—for example, by helping them to become smarter or more disciplined, which then makes them more successful. The problem comes when parents use direct methods: when they are able to use their own wealth or power as a substitute for their children's qualities.Parents will tend to do this when they can. Parents will die for their kids, so it's not surprising to find they'll also push their scruples to the limits for them. Especially if other parents are doing it.Sealing off this force has a double advantage. Not only does a society get "the best man for the job," but parents' ambitions are diverted from direct methods to indirect ones—to actually trying to raise their kids well.But we should expect it to be very hard to contain parents' efforts to obtain an unfair advantage for their kids. We're dealing with one of the most powerful forces in human nature. We shouldn't expect naive solutions to work, any more than we'd expect naive solutions for keeping heroin out of a prison to work._____The obvious way to solve the problem is to make credentials better. If the tests a society uses are currently hackable, we can study the way people beat them and try to plug the holes. You can use the cram schools to show you where most of the holes are. They also tell you when you're succeeding in fixing them: when cram schools become less popular.A more general solution would be to push for increased transparency, especially at critical social bottlenecks like college admissions. In the US this process still shows many outward signs of corruption. For example, legacy admissions. The official story is that legacy status doesn't carry much weight, because all it does is break ties: applicants are bucketed by ability, and legacy status is only used to decide between the applicants in the bucket that straddles the cutoff. But what this means is that a university can make legacy status have as much or as little weight as they want, by adjusting the size of the bucket that straddles the cutoff.By gradually chipping away at the abuse of credentials, you could probably make them more airtight. But what a long fight it would be. Especially when the institutions administering the tests don't really want them to be airtight._____Fortunately there's a better way to prevent the direct transmission of power between generations. Instead of trying to make credentials harder to hack, we can also make them matter less.Let's think about what credentials are for. What they are, functionally, is a way of predicting performance. If you could measure actual performance, you wouldn't need them.So why did they even evolve? Why haven't we just been measuring actual performance? Think about where credentialism first appeared: in selecting candidates for large organizations. Individual performance is hard to measure in large organizations, and the harder performance is to measure, the more important it is to predict it. If an organization could immediately and cheaply measure the performance of recruits, they wouldn't need to examine their credentials. They could take everyone and keep just the good ones.Large organizations can't do this. But a bunch of small organizations in a market can come close. A market takes every organization and keeps just the good ones. As organizations get smaller, this approaches taking every person and keeping just the good ones. So all other things being equal, a society consisting of more, smaller organizations will care less about credentials._____That's what's been happening in the US. That's why those quotes from Korea sound so old fashioned. They're talking about an economy like America's a few decades ago, dominated by a few big companies. The route for the ambitious in that sort of environment is to join one and climb to the top. Credentials matter a lot then. In the culture of a large organization, an elite pedigree becomes a self-fulfilling prophecy.This doesn't work in small companies. Even if your colleagues were impressed by your credentials, they'd soon be parted from you if your performance didn't match, because the company would go out of business and the people would be dispersed.In a world of small companies, performance is all anyone cares about. People hiring for a startup don't care whether you've even graduated from college, let alone which one. All they care about is what you can do. Which is in fact all that should matter, even in a large organization. The reason credentials have such prestige is that for so long the large organizations in a society tended to be the most powerful. But in the US at least they don't have the monopoly on power they once did, precisely because they can't measure (and thus reward) individual performance. Why spend twenty years climbing the corporate ladder when you can get rewarded directly by the market?I realize I see a more exaggerated version of the change than most other people. As a partner at an early stage venture funding firm, I'm like a jumpmaster shoving people out of the old world of credentials and into the new one of performance. I'm an agent of the change I'm seeing. But I don't think I'm imagining it. It was not so easy 25 years ago for an ambitious person to choose to be judged directly by the market. You had to go through bosses, and they were influenced by where you'd been to college._____What made it possible for small organizations to succeed in America? I'm still not entirely sure. Startups are certainly a large part of it. Small organizations can develop new ideas faster than large ones, and new ideas are increasingly valuable.But I don't think startups account for all the shift from credentials to measurement. My friend <NAME> told me that when he went to work for a New York law firm in the 1950s they paid associates far less than firms do today. Law firms then made no pretense of paying people according to the value of the work they'd done. Pay was based on seniority. The younger employees were paying their dues. They'd be rewarded later.The same principle prevailed at industrial companies. When my father was working at Westinghouse in the 1970s, he had people working for him who made more than he did, because they'd been there longer.Now companies increasingly have to pay employees market price for the work they do. One reason is that employees no longer trust companies to deliver deferred rewards: why work to accumulate deferred rewards at a company that might go bankrupt, or be taken over and have all its implicit obligations wiped out? The other is that some companies broke ranks and started to pay young employees large amounts. This was particularly true in consulting, law, and finance, where it led to the phenomenon of yuppies. The word is rarely used today because it's no longer surprising to see a 25 year old with money, but in 1985 the sight of a 25 year old professional able to afford a new BMW was so novel that it called forth a new word.The classic yuppie worked for a small organization. He didn't work for General Widget, but for the law firm that handled General Widget's acquisitions or the investment bank that floated their bond issues.Startups and yuppies entered the American conceptual vocabulary roughly simultaneously in the late 1970s and early 1980s. I don't think there was a causal connection. Startups happened because technology started to change so fast that big companies could no longer keep a lid on the smaller ones. I don't think the rise of yuppies was inspired by it; it seems more as if there was a change in the social conventions (and perhaps the laws) governing the way big companies worked. But the two phenomena rapidly fused to produce a principle that now seems obvious: paying energetic young people market rates, and getting correspondingly high performance from them.At about the same time the US economy rocketed out of the doldrums that had afflicted it for most of the 1970s. Was there a connection? I don't know enough to say, but it felt like it at the time. There was a lot of energy released._____Countries worried about their competitiveness are right to be concerned about the number of startups started within them. But they would do even better to examine the underlying principle. Do they let energetic young people get paid market rate for the work they do? The young are the test, because when people aren't rewarded according to performance, they're invariably rewarded according to seniority instead.All it takes is a few beachheads in your economy that pay for performance. Measurement spreads like heat. If one part of a society is better at measurement than others, it tends to push the others to do better. If people who are young but smart and driven can make more by starting their own companies than by working for existing ones, the existing companies are forced to pay more to keep them. So market rates gradually permeate every organization, even the government. [3]The measurement of performance will tend to push even the organizations issuing credentials into line. When we were kids I used to annoy my sister by ordering her to do things I knew she was about to do anyway. As credentials are superseded by performance, a similar role is the best former gatekeepers can hope for. Once credential granting institutions are no longer in the self-fullfilling prophecy business, they'll have to work harder to predict the future._____Credentials are a step beyond bribery and influence. But they're not the final step. There's an even better way to block the transmission of power between generations: to encourage the trend toward an economy made of more, smaller units. Then you can measure what credentials merely predict.No one likes the transmission of power between generations—not the left or the right. But the market forces favored by the right turn out to be a better way of preventing it than the credentials the left are forced to fall back on.The era of credentials began to end when the power of large organizations peaked in the late twentieth century. Now we seem to be entering a new era based on measurement. The reason the new model has advanced so rapidly is that it works so much better. It shows no sign of slowing.Notes[1] <NAME> (<NAME> trans.), China's Examination Hell: The Civil Service Examinations of Imperial China, Yale University Press, 1981.Scribes in ancient Egypt took exams, but they were more the type of proficiency test any apprentice might have to pass.[2] When I say the raison d'etre of prep schools is to get kids into better colleges, I mean this in the narrowest sense. I'm not saying that's all prep schools do, just that if they had zero effect on college admissions there would be far less demand for them.[3] Progressive tax rates will tend to damp this effect, however, by decreasing the difference between good and bad measurers.Thanks to <NAME>, <NAME>, <NAME>, and David Sloo for reading drafts of this.
https://github.com/mst2k/HSOS-PTP-Typst-Template
https://raw.githubusercontent.com/mst2k/HSOS-PTP-Typst-Template/main/main.typ
typst
#import "templates/template.typ": * #import "templates/acronyms.typ": * //Hier werden die Abkürzungen definiert. Die Abkürzungen werden automatisch in ein Verzeichniss geschrieben und können im Text //mit #acr("Abkürzung") bzw #acrpl("Abkürzung")referenziert werden. #let acronyms = ( //"Abkürzung": ("Vollständige Bezeichnung", "Plural") "PTP": ("Praxistransferprojekt", "Praxistransferprojekte"), ) //Die Symbole die genutzt werden, werden hier definiert. Später wird aus dieser Liste auch automatisch ein Verzeichniss erstellt. //Falls keine Symbole verwendet werden, kann diese Variable leer gelassen werden. Dadurch wird dann auch kein Verzeichniss erstellt. //Die Symbole können im Text mit #symbols.Symbolname referenziert werden. #let symbols = ( //"Beschreibung": "Symbol" "Gesamtkostenfunktion": ($K(x)$), ) //Der Anhang wird automatisch generiert, wenn die Variable appendix gesetzt ist. //Die einzelnen Anhänge werden mit == Überschrift definiert. #let appendix = [ == Erster Anhang Appendix <anhang1> test test #image("images/logos/HS-OS-Logo-Standard-rgb.jpg", width: 80%) #pagebreak() == Zweiter Anhang <anhang2> Derzeit wird noch kein PDF Embedding unterstützt. Um PDFs einzubinden, müssen diese als Bild eingebunden werden (z.B. PDF2SVG). ] //Das Abstract wird automatisch generiert, wenn die Variable abstract gesetzt ist. #let abstract = [ //Hier das Abstract schreiben #lorem(200) ] #show: project.with( title: "Beispieltitel", authors: ( (name: "<NAME>", birthday: "01.01.2000", birthplace: "Lingen (Ems)", address: "Musterstraße 12b, 49811 Lingen(Ems)", matrikelnummer: "103923", studiengruppe: "22-DWF-1"), ), betreuer: "Prof. <NAME>", modul: "Modulbezeichnung", abgabedatum: datetime.today().display("[day].[month].[year]"), language: "de", studiengang: "Wirtschaftsinformatik", abstract: abstract, acronyms: acronyms, symbols: symbols, appendix: appendix, ) #init-acronyms(acronyms) //////////////////////////////////////////////// //Hauptteil - Hier wird der Inhalt geschrieben// //////////////////////////////////////////////// = Einführung <einführung> #lorem(200) == Anlass und Problemhintergrund #lorem(200) == Zielsetzung #lorem(100) = Theoretische Grundlagen #lorem(200) = Andwendung auf die Praxis #lorem(200) = Kritische Reflexion #lorem(200) = Fazit/Schlussbetrachtung #lorem(200) //////////////////////////////////////////////////////////////////////// //Diverse Snippets zur Hilfe, alles nachstehende kann gelöscht werden!// //////////////////////////////////////////////////////////////////////// = HILFEN (ENTFERNEN) Verschiedene Snippets zur Hilfe! == Quellen Referenziert wird mit \@ - Quelle: @Vertrau.mir.Bruder[120 ff.] Zu sehen in @anhang1. Wie bereits in @einführung beschrieben == Bilder #figure( image("images/logos/HS-OS-Logo-Standard-rgb.jpg", width: 80%), caption: [Logo der Hochschule.], ) <HS-logo> @HS-logo zeigt das Logo der Hochschule == Acronyms Abkürzungen werden nur bei der ersten Verwendung voll ausgeschrieben: #acr("PTP"). Bei der zweiten Verwendung nur die Kurzform: #acr("PTP"). Der Plural ist auch möglich: #acrpl("PTP") == Code Snippet ```go package main import "fmt" func main() { fmt.Println("Some Code!"); } ``` == Mathe Mathematische Ausdrücke werden zwischen Dollarzeichen (\$) geschrieben. $ 1/2 < /2(x+1) $ <coolefunktion> Und können @coolefunktion referenziert werden! Wir nutzen #symbols.Gesamtkostenfunktion um eine Symbol darzustellen. == Tabellen #figure( table( columns: (1fr, 1fr), inset: 10pt, align: horizon, [*Deutsch*], [*Englisch*], [Boot], [boat], [Haus], [house]), caption: [Übersetzungen], )
https://github.com/sean-clayton/typst-bullet-test
https://raw.githubusercontent.com/sean-clayton/typst-bullet-test/main/test.typ
typst
#set text(font: "Gentium Book Plus", size: 24pt) ▸
https://github.com/DaAlbrecht/thesis-TEKO
https://raw.githubusercontent.com/DaAlbrecht/thesis-TEKO/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: "", abstract: [], authors: (), date: none, logo: none, school: "", degree: "", class: "", body) = { // Set the document's basic properties. set document(author: authors, title: title) set page(numbering: "1", number-align: center) set text(font: "New Computer Modern", lang: "en") set heading(numbering: "1.1") [ #set align(center) #text(school) #linebreak() #text(degree) #linebreak() #text(class) ] // Title page. // The page can contain a logo if you pass one with `logo: "logo.png"`. v(0.6fr) if logo != none { align(right, image(logo, width: 26%)) } v(3.6fr) text(1.1em, date) v(1.2em, weak: true) text(2em, weight: 700, title) // Author information. pad(top: 0.7em, right: 20%, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(start, strong(author))), )) v(2.4fr) pagebreak() // Abstract page. v(1fr) align( center, )[ #heading(outlined: false, numbering: none, text(0.85em, smallcaps[Abstract])) #abstract ] v(1.618fr) pagebreak() // Table of contents. outline(title: "Table of contents", depth: 3, indent: true) pagebreak() outline(title: "List of figures", target: figure.where(kind: image)) outline(title: "List of tables", target: figure.where(kind: table)) outline(title: "List of listings", target: figure.where(kind: raw)) pagebreak() // Main body. set par(justify: true) body pagebreak() let annex(body) = { counter(heading).update(0) set heading(numbering: "A", outlined: false) show heading: it => { if it.level == 1 { pagebreak(weak: true) block[ #set par(leading: 0.4em, justify: false) #underline(smallcaps[Annex #counter(heading).display(it.numbering): #it.body], evade: true, offset: 4pt) #v(0.2em) ] } else if it.level == 2 { block[ #underline(smallcaps(it.body), evade: true, offset: 3pt) #v(10pt) ] } } body } show: annex include "./content/annexes.typ" }