repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/HiiGHoVuTi/requin
https://raw.githubusercontent.com/HiiGHoVuTi/requin/main/fonc/lc-nuls.typ
typst
#import "../lib.typ": * #show heading: heading_fct #import "@preview/diagraph:0.2.5": * #import "@preview/gloss-awe:0.0.5": gls #show figure.where(kind: "jkrb_glossary"): it => {it.body} #import "@preview/curryst:0.3.0": rule, proof-tree _Ce sujet introduit la théorie derrière les languages fonctionnels comme OCaml : le lambda-calcul_ === Définitions et $alpha$-équivalence Soit $cal(V) = {a,b,x,...}$ un ensemble infini dénombrable de _variables_. Soit $Lambda$ l'ensemble des _lambda termes_ défini inductivement par: #align(center, grid(columns: (1fr, 1fr, 1fr), [$\"x\" in Lambda$ pour $x in cal(V)$\ *Axiome*], [$\"lambda x. u\" in Lambda$ pour $u in Lambda$ et $x in cal(V)$\ *$lambda$-abstraction*], [$\"u space v\" in Lambda$ pour $u, v in Lambda$\ *Application*] )) Par exemple, $lambda x. y space x$ est un lambda terme. Le parenthésage se fait à gauche, avec la $lambda$-abstraction qui est de plus faible priorité. Ainsi, l'expression $lambda x. x y z$ se lit $lambda x. ((x space y) space z)$ On définit par induction l'ensemble des _variables liées_ $"BV"$ et des _variables libres_ $"FV"$ par: #align(center, grid(columns: (1fr, 1fr, 1fr), [$"BV"(x) = emptyset$\ pour $x in cal(V)$], [$"BV"(lambda x. u) = "BV"(u) union {x}$\ pour $u in Lambda$], [$"BV"(u space v) = "BV"(u) union "BV"(v)$\ pour $u, v in Lambda$] )) #align(center, grid(columns: (1fr, 1fr, 1fr), [$"FV"(x) = {x}$\ pour $x in cal(V)$], [$"FV"(lambda x. u) = "FV"(u) \\ {x}$\ pour $u in Lambda$], [$"FV"(u space v) = "FV"(u) union "FV"(v)$\ pour $u, v in Lambda$] )) #question(0)[ Quelles sont les variables libres et liées des lambda termes suivants ? #align(center, grid(columns: (1fr, 1fr, 1fr, 1fr), [$lambda x. x$], [$lambda f. lambda x. f space (f space x)$], [$lambda f. lambda x. f space (f space x space y) space y$], [$lambda x. f space (lambda f. f space (f space x))$] ))] #correct[ #align(center, grid(columns: (1fr, 1fr, 1fr, 1fr), [$"FV" = emptyset\ "BV" = {x}$], [$"FV" = emptyset\ "BV" = {f, x}$], [$"FV" = {y}\ "BV" = {f, x}$], [$"FV" = {f} \ "BV" = {x, f}$], )) ] Soient $e,a in Lambda$ et $x in cal(V)$, on défini l'_opération de substitution_ $e[x <- a]$ inductivement par : #align(center, grid(columns: (1fr, 1fr), [$x [x <- a] := a$], [$y [x <- a] := y$ pour $ y in V \\{x}$] )) #align(center, grid(columns: (auto, 1fr), [$(lambda y. e) [x <- a] := lambda y. (e[x <- a])$ pour $ y in V \\{x}$], [$(lambda x. e) [x <- a] := lambda x. e$] )) #align(center,[$(e_1 space e_2) [x <- a] := (e_1[x <- a]) (e_2 [x <- a])$] ) #question(0)[Que donnent les substitutions suivantes ? #align(center, grid(columns: (1fr, 1fr, 1fr), [$(lambda x. y space x)[y <- x]$], [$(lambda x. x space y)[y <- lambda x. x]$], [$(y space (f space y) space f)[f <- f space (lambda y. f)]$] )) ] On appelle une _redexp_ un lambda-terme de la forme $(lambda x. e_1) e_2$. On appelle une _évaluation_ d'une redexp $(lambda x. e_1) e_2$ l'expression $e_1[x <- e_2]$. Intuitivement, on souhaite que $lambda x. e$ représente la fonction qui à $x$ associe $e$ et $e_1 e_2$ représente la fonction $e_1$ appliqué à $e_2$. #question(1)[Expliquer pourquoi "remplacer toutes les occurences de $x$ par $e_2$ dans $e_1$" ne correspond pas à ce que l'on recherche pour l'évaluation de $(lambda x. e_1) space e_2$ ] #question(1)[Proposer un algorithme renommant un lambda terme pour qu'il n'y ai pas de variables libre et liée, et que une variable liée soient associé à une unique $lambda$-abstraction.\ _Par exemple_, ($ x (lambda x. lambda x. x) arrow.squiggly x (lambda y. lambda z. z)$). ] On appelle la relation d'$alpha$-équivalence la relation déterminant si deux termes sont les mêmes, au renommage près. #question(1)[Donner un algorithme testant si deux termes sont $alpha$-équivalent ou non.] On prendra désormais la convention qu'aucun terme ne contient de variables libres et liées, quitte à étudier un terme $alpha$-équivalent. Si une expression $a$ est présente dans $A$ une autre expression, on note cela $a in A$. On appelle une dérivation $A ->A'$ s'il existe une redexp $a in A$ avec $A'$ ou l'on a remplacé $a$ par son évaluation. On dit que $A$ est sous _forme normale_ s'il n'est pas dérivable. On appelle un _calcul_ de $A$ une série finie de dérivations $A -> A_1 -> ... -> A_n$. On note cela $A ->^n A_n$ ou encore $A ->^* A_n$. Si $A_n$ est sous forme normale, on appelle cela un _calcul normalisant_. Si tout les calculs à partir de $A$ sont de longeur inférieur à un certain $n$, on dit que $A$ est fortement normalisant. On notera $lambda x_1 x_2 ... x_n. e$ pour $lambda x_1. lambda x_2. ... lambda x_n. e$. On définit $I := lambda x.x$, $K := lambda y x. y$ et $Delta := lambda x.x space x$ === Introduction ==== Préliminaires #question(0)[ Donner un calcul normalisant de $K space K space I$, de $I space I$ et de $K space I space Delta$] #question(1)[ Montrer que $Delta space Delta$ ne possède pas de calcul normalisant.] ==== Graphe des réductions Soit $e in Lambda$, on pose $G_e = (S_e,A_e)$ le _graphe orienté des réductions de $e$_ avec $S_e = { e' in Lambda : e ->^* e'}$ et $A_e = {(x,y) in S_e^2 : x -> y }$ #question(0)[ Donner le graphe des réduction de $K space I space (Delta space Delta)$ et de $Delta space ((lambda x. Delta) space I)$ ] #question(2)[ Donner une expression dont le graphe des réductions est infini] #question(2)[ Montrer que si le graphe des réduction d'un $e$ est acyclique fini, alors $e$ est fortement normalisant.] #question(2)[ Donner une expression $e in Lambda$ pour chaqun des graphes des réductions suivant : #align(center, [ #scale(x:70%,y:70%,reflow: true)[ #raw-render( ```dot digraph { node [shape=circle,label=""]; rankdir=LR; a -> b -> c; } ``` )] #scale(x:70%,y:70%,reflow: true)[ #raw-render( ```dot digraph { node [shape=circle,label=""]; rankdir=LR; a -> a -> b } ``` )] #scale(x:70%,y:70%,reflow: true)[ #raw-render( ```dot digraph { node [shape=circle,label=""]; rankdir=LR; a -> a -> b -> b -> c -> c } ``` )] ]) ] #question(3)[ Donner un lambda-terme dont le graphe des réductions est le cycle de longueur $2$ ] #question(3)[ Soit $n >0$, donner une expression $e in Lambda$ dont le graphe des réductions soit le cycle de longeur $n$. ] ==== Booléens Soient $top := lambda x y.space x$, $bot := lambda x y.space y$ et $"if" := lambda b c_1 c_2. space b space c_1 space c_2$ On pose $B := {top, bot}$ #question(0)[Montrer que, soit $e,e' in Lambda$, on a $"if" top e space e' ->^* e$ et $"if" bot e space e' ->^* e'$] #question(1)[Définir une expression $"not"$ telle que $"not" top ->^* bot$ et $"not" bot ->^* top$] #question(2)[Définir une expression $"and"$ tel que, soient $b,b' in B$, on ai : $ "and" b space b' ->^* cases(top "si" b = b' = top, bot "sinon") $ ] === Résultats Théoriques, $beta$-équivalence ==== $beta$-équivalence On pose $<->$ la fermeture symétrique de $->$ : on a $x <-> y$ si et seulement si $x -> y or y -> x$. On pose $G = (Lambda,A)$ un graphe orienté infini avec $A = {(x,y) in E^2 : x -> y}$. On défini $=_beta$ la relation d'équivalence telle que $x =_beta y$ si $x$ et $y$ appartiennent à la meme composante faiblement connexe dans $G$ #question(1)[Montrer que $=_beta$ est bien une relation d'équivalence sur $E$] #question(2)[ Montrer que $a =_beta b$ si, et seulement si il existe $n in NN$ et $M_1,...,M_n$ tel que $a <-> M_1 <-> ... <-> M_n <-> b$ ] $=_beta$ est donc la fermeture transitive de $<->$. ==== Confluence _Cette partie contiens beaucoup de lourdes preuves par induction. Elles ne sont pas particulièrement difficile, mais peuvent etre très longues._ On dit qu'une relation $cal(R)$ sur $E$ est _localement confluente_ si pour tout $t,u,v in E$ tels que $t cal(R) u$ et $t cal(R) v$ il existe $omega in E$ tel que $u cal(R) omega$ et $v cal(R) omega$. Dans le cas ou $cal(R)$ est la fermeture transitive de $R$, alors on dit que $R$ est _confluente_. On souhaite montrer que la relation $->$ soit confluente. Pour cela, on défini la réduction parralèle telle que #align(center, grid(columns: (1fr, 1fr), rows:(15pt,15pt), [$x triangle.r x$ pour $x in cal(V)$], [$lambda x. e triangle.r lambda x. e'$ pour $e triangle.r e'$], [$e_1 space e_2 triangle.r e'_1 space e'_2$ pour $e_1 triangle.r e'_1$ et $e_2 triangle.r e'_2$], [$(lambda x. space e_1) e_2 space e_2 triangle.r e_1[ x <- e_2]$] )) #question(2)[ Montrer que si $a -> b$, alors $a triangle.r b$. ] #question(2)[ Montrer que si $a triangle.r b$, alors $a ->^* b$. ] #question(2)[ Soient $e,a_1,a_2 in Lambda$ et $x,y in cal(V)$, montrer _les règles d'inversion des substitutions_ : - Si $x != y$, on a $e[x <- a_1][y <- a_2] = e[y <- a_2][x <- a_1[y <- a_2]]$\ - Si $x = y$, on a $e[x <- a_1][y <- a_2] = e[x <- a_1[y <- a_2]]$ ] #question(3)[ Montrer que soient $e, e', v, v' in Lambda$ et $x in cal(V)$, si $ e triangle.r e'$ et $e[x <- v] triangle.r e'[x <- v']$. ] #question(3)[ Démontrer que la relation $triangle.r$ est confluente. ] ==== Autour de la confluence _On pourra admettre que la relation $->^*$ est confluente._ #question(2)[ Montrer que si $e in Lambda$ admet une forme normale, alors celle-ci est unique. ] #question(2)[ Montrer que si $a =_beta b$, alors il existe un $e in E$ tel que $e ->^* e$ et $b ->^* e$ ] #question(2)[ Soit $f in Lambda$, donner $g in Lambda$ tel que pour tout $e in Lambda$, on ai $f(e) =_beta g(e)$ mais $f !=_beta g$. ] === Entiers et opérations ==== Entiers de Church Soit $n in NN$, on appelle $C_n$ _l'entier de Church_ de $n$ défini par: - $C_0 := lambda f x. x$ - $C_1 := lambda f x. f space x$ - $C_2 := lambda f x. f (f space x)$ - $C_n := lambda f x. underbrace(f (f ... (f space x)..),n "fois") $ #question(1)[ Définir $"succ" in Lambda$ tel que pour tout $n in NN$, $"succ" C_n ->^* C_(n+1)$ ] #question(1)[ Définir $"add" in Lambda$ tel que pour tout $n,m in NN$, $"add" C_n space C_m ->^* C_(n+m)$ ] #question(1)[ Définir $"mul" in Lambda$ tel que pour tout $n,m in NN$, $"mul" C_n space C_m ->^* C_(n m)$ ] ==== Soustraction L'objectif est ici d'implémenter $"sub" in Lambda$ tel que $"sub" C_n space C_m ->^* C_(max (n-m,0))$. Pour cela on défini : $ "D" := lambda x y z. z space x space y $ tel que $"D" space x space y$ représente le couple $(x,y)$ #question(0)[ Montrer que soient $e,e' in Lambda$, on a $"D" space e space e' space top ->^* e$ et $"D" space e space e' bot ->^* e'$ ] #question(2)[ Définir $"A" in Lambda$ tel que soit $e in Lambda$ on a $"A" space ("D" space e space C_n) ->^* "D" space C_n space C_(n+1)$ ] #question(3)[ Définir $"decr" in Lambda$ tel que $"decr" space C_n ->^* C_(max(n-1,0))$ ] #question(1)[ Définir $"sub" in Lambda$ tel que $"sub" space C_n space C_m ->^* C_(max (n-m,0))$. ] ==== Conditionnels // TODO: if_eq === Points fixe et récursivité ==== L'opérateur point-fixe ==== Récursivité === Typage Simple ==== Types généraliste ==== Terminaison === Système F et système T
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/pagebreak.typ
typst
Apache License 2.0
// Test forced page breaks. --- // Just a pagebreak. // Should result in two pages. #pagebreak() --- // Pagebreak, empty with styles and then pagebreak // Should result in one auto-sized page and two conifer-colored 2cm wide pages. #pagebreak() #set page(width: 2cm, fill: conifer) #pagebreak() --- // Two text bodies separated with and surrounded by weak pagebreaks. // Should result in two aqua-colored pages. #set page(fill: aqua) #pagebreak(weak: true) First #pagebreak(weak: true) Second #pagebreak(weak: true) --- // Test a combination of pagebreaks, styled pages and pages with bodies. // Should result in three five pages, with the fourth one being forest-colored. #set page(width: 80pt, height: 30pt) #[#set page(width: 60pt); First] #pagebreak() #pagebreak() Third #page(height: 20pt, fill: forest)[] Fif#[#set page();th] --- // Test hard and weak pagebreak followed by page with body. // Should result in three navy-colored pages. #set page(fill: navy) #set text(fill: white) First #pagebreak() #page[Second] #pagebreak(weak: true) #page[Third]
https://github.com/Midbin/cades
https://raw.githubusercontent.com/Midbin/cades/main/typst-package/lib.typ
typst
MIT License
#import "@preview/jogs:0.2.0": compile-js, call-js-function #let qrcode-src = read("./qrcode.js") #let qrcode-bytecode = compile-js(qrcode-src) #let qr-code( content, width: auto, height: auto, color: black, background: white, error-correction: "M", ) = { assert( error-correction == "L" or error-correction == "M" or error-correction == "Q" or error-correction == "H", message: "Error correction code must be one of 'L', 'M', 'Q', 'H'") let result = call-js-function(qrcode-bytecode, "qrcode", content, color.to-hex(), background.to-hex(), error-correction) return image.decode(result, width: width, height: height) }
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2011/MS-12.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (1 - 32)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [1], [MA Long], [CHN], [3430], [2], [ZHANG Jike], [CHN], [3293], [3], [BOLL Timo], [GER], [3161], [4], [WANG Hao], [CHN], [3159], [5], [XU Xin], [CHN], [3123], [6], [WANG Liqin], [CHN], [3111], [7], [MA Lin], [CHN], [3039], [8], [CHEN Qi], [CHN], [3005], [9], [HAO Shuai], [CHN], [2952], [10], [JOO Saehyuk], [KOR], [2931], [11], [OVTCHAROV Dimitrij], [GER], [2916], [12], [RYU Seungmin], [KOR], [2886], [13], [OH Sangeun], [KOR], [2869], [14], [SKACHKOV Kirill], [RUS], [2856], [15], [CHUANG Chih-Yuan], [TPE], [2855], [16], [MIZUTANI Jun], [JPN], [2842], [17], [TOKIC Bojan], [SLO], [2832], [18], [<NAME>], [GER], [2830], [19], [LEE Sang Su], [KOR], [2825], [20], [GAO Ning], [SGP], [2817], [21], [<NAME>], [FRA], [2813], [22], [<NAME>], [CHN], [2812], [23], [<NAME>], [GRE], [2798], [24], [<NAME>], [DEN], [2783], [25], [<NAME>], [RUS], [2782], [26], [KISHIKAWA Seiya], [JPN], [2773], [27], [<NAME>], [BLR], [2747], [28], [<NAME>], [KOR], [2745], [29], [<NAME>], [KOR], [2733], [30], [<NAME>], [CHN], [2730], [31], [APOLONIA Tiago], [POR], [2716], [32], [<NAME>], [AUT], [2713], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (33 - 64)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [33], [<NAME>], [GER], [2705], [34], [NIWA Koki], [JPN], [2701], [35], [YOSHIDA Kaii], [JPN], [2693], [36], [LEE Jungwoo], [KOR], [2687], [37], [<NAME>], [GER], [2682], [38], [KARAKASEVIC Aleksandar], [SRB], [2681], [39], [TAKAKIWA Taku], [JPN], [2672], [40], [<NAME>], [AUT], [2669], [41], [#text(gray, "KO Lai Chak")], [HKG], [2668], [42], [<NAME>], [POR], [2667], [43], [<NAME>], [SWE], [2666], [44], [<NAME>], [ROU], [2654], [45], [RUBTSOV Igor], [RUS], [2653], [46], [<NAME>], [KOR], [2652], [47], [<NAME>], [TPE], [2650], [48], [<NAME>], [POR], [2640], [49], [<NAME>], [RUS], [2633], [50], [<NAME>], [ENG], [2620], [51], [<NAME>], [SWE], [2614], [52], [<NAME>], [CHN], [2610], [53], [<NAME>], [SWE], [2606], [54], [<NAME>], [CRO], [2605], [55], [<NAME>], [SGP], [2597], [56], [<NAME>], [POL], [2596], [57], [<NAME>], [JPN], [2594], [58], [<NAME>], [JPN], [2592], [59], [<NAME>], [CRO], [2589], [60], [<NAME>], [FRA], [2584], [61], [<NAME>], [AUT], [2584], [62], [<NAME>], [JPN], [2581], [63], [<NAME>], [POL], [2580], [64], [<NAME>], [TUR], [2580], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (65 - 96)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [65], [KREANGA Kalinikos], [GRE], [2580], [66], [YIN Hang], [CHN], [2577], [67], [ALAMIYAN Noshad], [IRI], [2575], [68], [JANG Song Man], [PRK], [2575], [69], [<NAME>], [HKG], [2567], [70], [PROKOPCOV Dmitrij], [CZE], [2564], [71], [HE Zhiwen], [ESP], [2563], [72], [#text(gray, "<NAME>")], [CHN], [2563], [73], [YOSHIMURA Maharu], [JPN], [2559], [74], [<NAME>], [TUR], [2559], [75], [<NAME>], [GER], [2558], [76], [<NAME>], [BEL], [2552], [77], [<NAME>], [HUN], [2546], [78], [<NAME>], [SGP], [2544], [79], [<NAME>], [KOR], [2543], [80], [<NAME>], [AUT], [2542], [81], [<NAME>], [FRA], [2540], [82], [JIANG Tianyi], [HKG], [2540], [83], [<NAME>], [HUN], [2535], [84], [LI Ping], [QAT], [2531], [85], [<NAME>], [IND], [2529], [86], [<NAME>], [DOM], [2529], [87], [UEDA Jin], [JPN], [2523], [88], [<NAME>], [SVK], [2522], [89], [YANG Zi], [SGP], [2521], [90], [<NAME>], [HKG], [2518], [91], [<NAME>], [AUT], [2518], [92], [<NAME>], [TPE], [2518], [93], [<NAME>], [CRO], [2518], [94], [<NAME>], [KOR], [2516], [95], [<NAME>], [CZE], [2509], [96], [<NAME>], [GER], [2504], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (97 - 128)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [97], [SHIBAEV Alexander], [RUS], [2501], [98], [KIM Junghoon], [KOR], [2500], [99], [<NAME>], [BRA], [2499], [100], [KASAHARA Hiromitsu], [JPN], [2497], [101], [WU Jiaji], [DOM], [2493], [102], [<NAME>], [SVK], [2491], [103], [KOSOWSKI Jakub], [POL], [2488], [104], [<NAME>], [ESP], [2488], [105], [LI Hu], [SGP], [2488], [106], [LIU Song], [ARG], [2487], [107], [<NAME>], [MEX], [2483], [108], [CHT<NAME>], [BLR], [2482], [109], [<NAME>], [EGY], [2481], [110], [<NAME>], [RUS], [2475], [111], [ZHMUDENKO Yaroslav], [UKR], [2475], [112], [<NAME>], [HKG], [2471], [113], [TSUBOI Gustavo], [BRA], [2462], [114], [SVENSSON Robert], [SWE], [2462], [115], [<NAME>], [POL], [2456], [116], [<NAME>], [FRA], [2455], [117], [<NAME>], [ROU], [2451], [118], [SIRUCEK Pavel], [CZE], [2450], [119], [<NAME>eyoung], [KOR], [2447], [120], [PLATONOV Pavel], [BLR], [2445], [121], [<NAME>], [HKG], [2445], [122], [DIDUKH Oleksandr], [UKR], [2441], [123], [MACHADO Carlos], [ESP], [2434], [124], [BLASZCZYK Lucjan], [POL], [2433], [125], [#text(gray, "<NAME>")], [PRK], [2432], [126], [LI<NAME>], [CHN], [2430], [127], [CANTERO Jesus], [ESP], [2429], [128], [OYA Hidetoshi], [JPN], [2428], ) )
https://github.com/fenjalien/cirCeTZ
https://raw.githubusercontent.com/fenjalien/cirCeTZ/main/circuitypst.typ
typst
Apache License 2.0
#import "components.typ" #import "utils.typ" #import "../typst-canvas/draw.typ": * #import "../typst-canvas/coordinate.typ" #import "../typst-canvas/vector.typ" #let canvas-fill = fill #let canvas-stroke = stroke // #let draw-component(component) = { // (( // children: components. // ),) // } #let node(component, position, label: none, name: none, anchor: none, fill: auto, stroke: auto, ..options) = { assert(component in components.node, message: "Component '" + component + "' is unknown") group(name: name, anchor: anchor, { import "../typst-canvas/draw.typ": anchor if fill != auto { canvas-fill(fill) } if stroke != auto { canvas-stroke(stroke) } set-origin(position) anchor("center", (0,0)) components.node.at(component) utils.anchors(( // IM A GENIUS "north east": ("north", "-|", "east"), "south east": ("south", "-|", "east"), "north west": ("north", "-|", "west"), "south west": ("south", "-|", "west"), n: "north", s: "south", e: "east", w: "west", )) if label != none { content("center", label) } }) move-to(position) } #let to( component, start, end, label: none, name: none, i: none, v: none, poles: none, stroke: auto, fill: auto, ) = { assert(component in components.path, message: "Component '" + component + "' is unknown") group(name: name, { if fill != auto { canvas-fill(fill) } if stroke != auto { canvas-stroke(stroke) } anchor("start", start) anchor("end", end) // This transformation moves (0,0) to the mid point of the line and rotates such that the line from -> to lies flat on the x axis rotate(( utils.get-angle, // (s, e) => panic(utils.get-angle(s, e)), "start", "end" )) // rotate(90deg) set-origin(("start", 0.5, "end")) anchor("center", (0,0)) line("start", (-0.5, 0)) line("end", (0.5, 0)) components.path.at(component) utils.anchors(( west: (-0.5, 0), east: (0.5, 0), // IM A GENIUS "north east": ("north", "-|", "east"), "south east": ("south", "-|", "east"), "north west": ("north", "-|", "west"), "south west": ("south", "-|", "west"), n: "north", s: "south", e: "east", w: "west", )) if label != none { content("label", label) } if v != none { assert(type(v) == "content" or (type(v) == "array" and i.len() == 2 and type(v.first()) == "string" and type(v.last()) == "content"), message: "Invalid voltage syntax") let y = -0.3 let plus = ((v1, v2) => vector.add(vector.lerp(v1, v2, 0.25), (0, y, 0)), "east", "end") let minus = ((v1, v2) => vector.add(vector.lerp(v1, v2, 0.75), (0, y, 0)), "start", "west") content((rel: (0,y), to: ("east", 0.25, "end")), $+$) content((rel: (0,y), to: ("start", 0.75, "west")), $-$) content("annotation", v) } if i != none { assert(type(i) == "content" or (type(i) == "array" and i.len() == 2 and type(i.first()) == "string" and type(i.last()) == "content"), message: "Invalid current label syntax") let from = "east" let to = "end" let c = i let y = 0.3 let d = 0deg if type(i) == "array" { let p = i.first() c = i.last() let ab = p.find(regex("\^|_")) assert(ab != none, message: "'^' or '_' not found in `i`") if ab == "_"{ y *= -1 } let lr = p.find(regex("<|>")) assert(lr != none, message: "'<' or '>' not found in `i`") if p.position(lr) == 0 { from = "west" to = "start" } if lr == "<" { d = 180deg y *= -1 } } else if component == "short" { from = "west" to = "east" } rotate(d) node("currarrow", (from, 0.5, to)) content((rel: (0, y)), c) rotate(-d) } if poles != none { if type(poles) == "string" { poles = (poles.first(), poles.last()).map(p => ("*": "circ", d: "diamondpole", s: "squarepole", o: "ocirc").at(p, default: none)) } assert(type(poles) == "array" and poles.len() == 2) if poles.first() != none { node(poles.first(), "start") } if poles.last() != none { node(poles.last(), "end") } } }) move-to(end) }
https://github.com/asmund20/typst-packages
https://raw.githubusercontent.com/asmund20/typst-packages/main/README.md
markdown
Place the "local" folder at {data-dir}/typst/packages/.\ {data-dir} is - $XDG_DATA_HOME or ~/.local/share on Linux - ~/Library/Application Support on macOS - %APPDATA% on Windows
https://github.com/vaibhavjhawar/typst-cv-template1
https://raw.githubusercontent.com/vaibhavjhawar/typst-cv-template1/main/cv1.typ
typst
MIT License
// ================================================== // // Typst Resume/CV Template // https://github.com/vaibhavjhawar/typst-cv-template1 // // Inspired by <NAME>'s Graduate CV LaTex template // // MIT License // // Requires: // - Typst CLI (https://github.com/typst/typst/) // - Fontin Fonts (http://www.exljbris.com/fontin.html) // // ================================================== // ================================================== // Config // ================================================== // Page and Text Setup #set page(paper: "a4", margin: (x: 3cm, y: 2cm)) //"us-letter" #set text(font: "Fontin", size: 10pt) #set par(justify: false, leading: 0.45em) // SmallCaps Function for Fontin Fonts #let sc(body) = { set text(font: "Fontin SmallCaps") [#body] } // Full Name Title Function #let title(first_name: none, last_name: none) = { set align(center) set text(font: "Fontin", size: 24pt) [#first_name] h(2.5mm) set text(font: "Fontin SmallCaps", size: 24pt) [#last_name] v(7.5mm) } // Setting Heading as Section Titles #show heading: myhead => [ #v(-1.25mm) #set text(font: "Fontin SmallCaps", weight: "regular") #myhead #v(-4.5mm) #set line(length: 100%, stroke: 0.2mm) #line() #v(-1mm) ] #let info(info_dict: none) = { grid( columns: (30%, auto), gutter: 3mm, align(right)[ #for key in info_dict.keys() { sc(key); linebreak() } ], align(left)[ #for value in info_dict.values() { value; linebreak() } ], ) } #let work( date_range: none, position: none, org: none, addr: none, desc: none, ) = { v(1.2mm) table( columns: (15%, auto), align: (right, left), row-gutter: -1.75mm, stroke: none, table.cell(rowspan: 5, inset: (top: 0.25mm))[#sc([#date_range])], table.vline(stroke: 0.25mm), table.cell(inset: (top: 0.25mm))[#position], [#emph(org)], [#addr], (v(-1.25mm)), table.cell(inset: (bottom: 0.25mm))[#text(size: 9pt, desc)], ) } #let to() = { set text(font: "Fontin", size: 8pt) align(center)[to] } #let skill(skill_dict: none) = { grid( columns: (25%, auto), gutter: 3mm, align(right)[ #for key in skill_dict.keys() { sc(key); linebreak() } ], align(left)[ #for value in skill_dict.values() { value; linebreak() } ], ) } #let edu(date_range: none, degree: none, grade: none, uni: none, addr: none) = { table( columns: (15%, auto), align: (right, left), row-gutter: -1.75mm, stroke: none, table.cell(rowspan: 3)[#sc([#date_range])], [#degree #h(2mm)|#h(2mm) #grade], [#uni], [#addr], ) v(-3.5mm) } #let project( date_range: none, title: none, org: none, addr: none, desc: none, ) = { table( columns: (15%, auto), align: (right, left), row-gutter: -1.75mm, stroke: none, table.cell(rowspan: 5, inset: (top: 0.25mm))[#sc([#date_range])], table.vline(stroke: 0.2mm), table.cell(inset: (top: 0.25mm))[#title], [#emph(org)], [#addr], (v(-1.25mm)), table.cell(inset: (bottom: 0.25mm))[#text(size: 9pt, desc)], ) } // ================================================== // Begin Document // ================================================== #title( first_name: "Firstname", // this will be Sentence Case, none to omit last_name: "Lastname", // this will be SmallCaps, none to omit ) = Personal Data #info( info_dict: ( "Place and Date of Birth:": "Lorem, Amet – Jan 12, 1234", "Address:" : "Ipsum, XY – 01234 ABC", "Phone:" : link("tel:123456789"), "Email:" : link("mailto:<EMAIL>"), ) ) = Work Experience #work( date_range: list(marker: [], [feb 1000], // start date [#to()], // comment this for single date [present], // end date - comment this for single date ), position: "Senior Software Engineer", org: "Some Software Company", addr: "Dolor, Sit Amet", desc: list( [Lorem ipsum dolor sit amet, consectetur adipiscing elit.], [sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.], [Ut enim ad minim veniam, quis nostrud exercitation ullamco.], [Laboris nisi ut aliquip ex ea commodo consequat, duis aute irure.], ), ) #work( date_range: list(marker: [], [jan 1000], // start date [#to()], // comment this for single date [feb 1000], // end date - comment this for single date ), position: "Junior Software Engineer", org: "Some Software Company", addr: "Dolor, Sit Amet", desc: list( [Dolor in reprehenderit in voluptate velit esse cillum dolore eu.], [Fugiat nulla pariatur, excepteur sint occaecat cupidatat non.], [Proident, sunt in culpa qui officia deserunt mollit anim id est laborum.], ), ) = Skills #skill( skill_dict: ( "Lectus Sit:" : "Amet, Placerat, IN, Egestas, Erat, Imperdiet, Euismod", "Nisi Porta:" : "Lorem, Mollis, Aliquam, UT, Porttitor, Loa, Diam", "Tempor:" : "Ipsum, Faucibus, Vitae, Aliquet, NEC", "Ullamcorper:" : "Sitamet, Risus, Nullam, Felis, Eget, Nunc, Lobortis, Mattis", ) ) = Education #edu( degree: "PhD in Physics", grade: "99%", uni: "University of Lorem Ipsum", addr: "Dolor, Sit Amet", date_range: list(marker: [], [1905], // start date // [#to()], // uncomment this for date range // [feb 1000], // end date - uncomment this for date range ), ) #edu( degree: "Master of Science in Physics", grade: "GPA 3.9/4.0", uni: "University of Lorem Ipsum", addr: "Dolor, Sit Amet", date_range: list(marker: [], [1900], // start date [#to()], // uncomment this for date range [1890], // end date - uncomment this for date range ), ) = Projects #project( date_range: list(marker: [], [jan 1000], // start date [#to()], // comment this for single date [feb 1000], // end date - comment this for single date ), title: "My Project 1 Title", org: "This is the desription of my project", addr: "Dolor, Sit Amet", desc: list( [Lorem ipsum dolor sit amet, consectetur adipiscing elit.], [sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.], [Ut enim ad minim veniam, quis nostrud exercitation ullamco.], ), ) #project( date_range: list(marker: [], [jan 1000], // start date [#to()], // comment this for single date [feb 1000], // end date - comment this for single date ), title: "My Project 2 Title", org: "My organization name", addr: "Dolor, Sit Amet", desc: list( [Lorem ipsum dolor sit amet, consectetur adipiscing elit.], [sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.], [Ut enim ad minim veniam, quis nostrud exercitation ullamco.], ), ) // ================================================== // End Document // ================================================== // ==================================================
https://github.com/31core/prescription
https://raw.githubusercontent.com/31core/prescription/main/README.md
markdown
# prescription 这是一个由typst编写的电子处方模板, 用于快速、方便地生成高质量处方. ## Why Typst 鉴于Word(.doc、.docx)是二进制格式, 不方便git管理; LaTex(TeX Live)安装包体积大, 语法冗余, 而且中文支持不好, 因此我们选择了typst这个轻量、语法简洁的排版工具. ## Usage 基本设置须更改`config.typ`对应的变量, 其中: * `title`: 医院的名称 * `name`: 患者姓名(汉字间建议用空格隔开) * `gender`: 性别, "男"或"女" * `age`: 患者年龄 * `diagnosis`: 诊断内容 * `doctor`: 医生名字 * `amount`: 药品总金额 添加药品: ```typst #add_medicine("<药品名>", "? 盒/瓶", "每日 ? 粒 内服/外用 ...") ``` 编译pdf: ```shell typst compile prescription.typ ``` ## Environment * Linux: View [[Typst on Repology][repology]](https://repology.org/project/typst/versions) * macOS: `brew install typst` * Windows: `winget install --id Typst.Typst` ## Requirement 本项目使用了`Noto Sans CJK SC`和`SimSun`两种字体, 编译时请确保安装了这两种字体. 由于typst编译时缺少字体不会报错, 这个问题很容易被忽略. 为保障格式符合预期,不清楚如何查看自己是否有这两款字体的话,可以在clone本项目后可以直接安装这两个字体 ## 关于打印 A5直接打印即可, A4打印时70%缩放再根据A5的规格裁剪. ## TODO List ~~* 在项目里集成公章生成器.~~ ## License <p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://github.com/31core/prescription">prescription</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://github.com/31core">31core</a> is licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/?ref=chooser-v1" target="_blank" rel="license noopener noreferrer" style="display:inline-block;">CC BY-NC-SA 4.0<img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/cc.svg?ref=chooser-v1" alt=""><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/by.svg?ref=chooser-v1" alt=""><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/nc.svg?ref=chooser-v1" alt=""><img style="height:22px!important;margin-left:3px;vertical-align:text-bottom;" src="https://mirrors.creativecommons.org/presskit/icons/sa.svg?ref=chooser-v1" alt=""></a></p>
https://github.com/dashuai009/dashuai009.github.io
https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/034.typ
typst
#let date = datetime( year: 2022, month: 9, day: 3, ) #metadata(( title: "素数的计数", subtitle: [math,数论], author: "dashuai009", description: "存在无求多个素数、存在无穷多个模4余3的素数、算术级数的素数狄利克雷定理、素数定理、哥得巴赫猜想、孪生素数猜想、N方+1猜想", pubDate: date.display(), ))<frontmatter> #import "../__template/style.typ": conf #show: conf == 无穷多个素数定理 <无穷多个素数定理> 存在无穷多个素数 === 证明 <证明> 瞪眼法 == 模4余3定理 <模4余3定理> 存在无穷多个模4余3的素数 === 证明 <证明-1> 假设我们已经有几个模4余3的素数,证明思路:从这几个素数出发可以#strong[不断找到新的];模4余3的素数。 假设初始表为$P_r = { 3 , p_1 , p_2 , p_3 , dots.h , p_r }$,考虑 #set math.equation(numbering: "(1)") $ A=4p\_1p\_2...p\_r+3 $ ,先将其分解为若干个素数乘积, $ A=q\_1q\_2...q\_s, $ ,我们可以得到以下来两个断言。 - 素数$q_1 , q_2 , dots.h , q_r$至少有一个必定是模4余3 如果该断言不成立,则这s个素数模4余1,那么A应该模4余1,这与(1)相悖 - 假设$q_i equiv 3 (m o d med 4)$,则$q_i$不在最初的表中, 从(2)可以得到$q_i \| A$,但是$3 , p_1 , dots.h , p_r$没有一个整除A的。所以我们得到了一个新的模4余3的素数。 重复以上两步,我们可以得到#strong[无穷多个模4余3的素数] // #set math.equation(numbering: "") === "模4余1"还能这样求吗? 不能,试一下就可以发现。无法得到无穷多个。 == 算数级数的素数狄利克雷定理 <算数级数的素数狄利克雷定理> 假设a和m是整数,$g c d (a , m) = 1$,则存在无穷多个素数模m余a,即存在无穷多个素数p满足 $ p equiv a (m o d med p) $ === 证明 <证明-2> 前边证明了(a,m)=(4,1)的情况。其他情况,我不会。 == 素数定理 <素数定理> 当x很大时,小于x的素数的个数近似等于$x \/ ln (x)$.也就是 $ lim_(x arrow.r oo) frac(pi (x), x \/ ln (x)) = 1 $ == 三个猜想 <三个猜想> === 歌德巴赫猜想 <歌德巴赫猜想> 每个偶数$n gt.eq 1$可以表示为两个素数之和。 === 孪生素数猜想 <孪生素数猜想> 存在无穷多个素数p使得p+2也是素数。 === $N^2 + 1$猜想 <n21猜想> 存在无穷多个形如$N^2 + 1$的素数。
https://github.com/Toniolo-Marco/git-for-dummies
https://raw.githubusercontent.com/Toniolo-Marco/git-for-dummies/main/book/git-basics-practice.typ
typst
#import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge, shapes #import fletcher.shapes: diamond #import "components/gh-button.typ": gh_button #import "components/git-graph.typ": branch_indicator, commit_node, connect_nodes, branch = Pratica == Configurare Git Prima di iniziare a utilizzare Git, è importante configurare il proprio nome utente e l'indirizzo email, poiché questi saranno associati ai tuoi commit. ```bash ➜ git config --global user.name "name" ➜ git config --global user.email "your@email" ``` == Configurare gh `gh` è il tool che utilizzeremo per interagire da CLI con GitHub, per configurare il nostro account utilizziamo: ```bash ➜ gh auth login ? What account do you want to log into? GitHub.com ? What is your preferred protocol for Git operations on this host? SSH ? Generate a new SSH key to add to your GitHub account? Yes ? Enter a passphrase for your new SSH key (Optional): ? Title for your SSH key: GitHub CLI ? How would you like to authenticate GitHub CLI? Login with a web browser ! First copy your one-time code: A111-B222 Press Enter to open github.com in your browser... ✓ Authentication complete. - gh config set -h github.com git_protocol ssh ✓ Configured git protocol ✓ Uploaded the SSH key to your GitHub account: /home/path/to/.ssh/key.pub ✓ Logged in as GitHub-Username ``` == Inizializzare un nuovo repository <init-repo> Per creare un nuovo progetto con Git, spostati nella directory del tuo progetto e inizializza un repository con il comando #footnote("Ignoriamo per ora l'output che verrà analizzato in seguito"): `git init` Abbiamo crato così il repository locale, sul nostro computer. Come abbiamo visto nel capitolo precedente: @remote[Remote Repository], Git si basa sui concetti di *local* e *remote*. Dunque le modifiche effettuate in locale *non influiscono automaticamente* sul remote. Solitamente, per i progetti più piccoli, come quelli individuali o quello affrontato nel corso di Advanced Programming, il remote repository è uno solo e sarà hostato su *GitHub*. Questo passaggio richiede l'aver già creato l'organizzazione alla quale apparterrà il repository. In alternativa è possibile crearla come personale e poi passare l'ownership. 1. Aprite la pagina: _“https://github.com/orgs/organization/repositories”_ 2. Premete sul pulsante: #box(fill: rgb("#29903B"),inset: 7pt, baseline: 25%, radius: 4pt)[#text(stroke: white, font: "Noto Sans", size: 7pt, weight: "light",tracking: 0.5pt)[New Repository]] 3. Da qui in poi compilate i campi, scegliendo il nome, la visibilità e la descrizione della repo. Il file README.md si può aggiungere anche in seguito. 4. La pagina della repo ora ci consiglia gli step da seguire direttamente su CLI: "_… create a new repository on the command line_" ```bash echo "# title" >> README.md git init git add README.md git commit -m "first commit" git branch -M main git remote add origin https://github.com/orgs/organization/repository.git git push -u origin main ``` Il primo comando crea un file chiamato README.md, se non esiste già e aggiunge la stringa "\# title" al suo contenuto. (Il simbolo "\#" in Markdown indica un titolo). Gli altri comandi verranno sviscerati nei prossimi capitoli, comunque, per una descrizione concisa: - `git init` lo abbiamo appena visto, inizializza un progetto di git in locale - `git add README.md` aggiunge il file `README.md` alla staging area - `git commit -m "first commit"` effettua il commit - `git branch -M main` imposta _main_ come branch principale - `git remote add origin ...` imposta la repository appena creata su GitHub come remote della nostra repository locale - `git push -u origin main` "pubblica" sul remote repository il commit che abbiamo appena effettuato.#footnote([Nota: `-u` è l'equivalente di `--set-upstream`, sostanzialmente imposta a quale remote il branch in locale dovrebbe pushare]) == Clonare un repository Nel caso il progetto esista già è sufficiente: spostarci nella cartella e clonare il repository: `git clone <url-repository>`. In questo modo avremmo una copia del repository remoto sulla nostra macchina. == Staging Area <stagin-area><git-add> Per portare i file modificati dalla directory di lavoro all'area di staging, usiamo il comando `git add`. Generalmente si usa il comando `git add -A` o `git add .` per aggiungere tutti i file modificati all'area di staging. Tuttavia è possibile aggiungere i file uno alla volta con `git add <nomefile>`. Similmente possiamo aggiungre tutti i file che rispettano una Regex con `git add <regex>`; ad esempio: `git add Documentation/\*.txt`, aggiungerà tutti i file `.txt` presenti nella cartella `Documentation`. == Difetti di Git #grid( columns: (3fr,2fr), [ Durante lo sviluppo di git, sono state sviluppate diverse funzionalità molto utili e nel tempo sono state aggiunte quasi tutte al comando `git checkout`. Attualmente il team di Git, sta lavorando per separare queste funzionalità in comandi distinti. Allo stesso anche in altri casi troveremo comandi diversi che hanno lo stesso scopo. In questo documento vedremo entrambe le versioni per completezza; tuttavia è consigliabile utilizzare i comandi più recenti. Per dare subito un esempio di questo problema, analizziamo il caso in cui vogliamo vedere l'attuale stato in cui ci troviamo. ], figure( image("img/graphical-representation-git-checkout.png"), caption: [Rappresentazione grafica del comando `git checkout`] ) ) == Analisi Per visualizzare la lista dei file nella staging area e altre informazioni generiche, possiamo usare il comando: ```bash ➜ git status On branch main # Current branch No commits yet Changes to be committed: # File in stage (use "git rm --cached <file>..." to unstage) new file: README.md # File added to stage (new file) ``` Questo è il caso in cui abbiamo appena creato il repository e aggiunto il file README.md. Se invece abbiamo delle modifiche in stage ed altre che non lo sono, otterremo un output simile a questo: ```bash ➜ git status On branch git-basics # The current branch Your branch is up to date with 'origin/git-basics'. # Last commit is the same as the remote Changes to be committed: # List of staged files (use "git restore --staged <file>..." to unstage) modified: book/git-basics-theory.typ Changes not staged for commit: # List of not staged files (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: book/git-basics-practice.typ Untracked files: # List of Untracked files (use "git add <file>..." to include in what will be committed) book/untracked-file.ops ``` In modo simile con `git checkout` possiamo avere un riassunto grossolano; in output vedremo solo i file modificati, senza ulteriori dettagli e non verranno mostrati i file *untracked*. ```bash ➜ git checkout M book/git-basics-practice.typ # Show only modified files M book/git-basics-theory.typ # Your branch is up to date with 'origin/git-basics'. # ``` == Analisi delle Modifiche Oltre allo stato per esaminare tutte le differenze tra i file dell'ultimo commit e gli attuali possiamo utilizzare il comando `git status -vv`, abbreviazione di `git status -v -v`. Alternativamente possiamo utilizzare `git diff @` dalla versione 1.8.5, o `git diff HEAD` per versioni precedenti. #footnote([Nessuno dei due mostra il contenuto dei file *untracked*; `git stastus -vv` mostra solo che esistono]) Con `HEAD` si fa riferimento all'ultimo commit in cui ci troviamo. Se abbiamo apportato modifiche a più file, risulterebbe molto utile avere un controllo granulare sulle differenze che vogliamo visualizzare: - Per visualizzare le modifiche apportate sul singolo file possiamo utilizzare il comando `git diff <nomefile>`. - Per visualizzare tutte le modifiche dei file in stage possiamo utilizzare `git diff --cached` (o il suo alias `--staged`). Altrimenti possiamo utilizzare `git status -v`. - Per visulizzare invece le modifiche le modifiche dei file che non sono in stage possiamo utilizzare `git diff`. #footnote([l'argomento `--no-index` è necessario se non siamo in un repository git]) == Commit Una volta che aggiunti i file all'area di staging, possiamo creare un commit con il comando: ```bash ➜ git commit -m "Message describing changes made" ``` Il messaggio di commit dovrebbe essere chiaro e descrivere cosa hai fatto. Se si vogliono aggiungere tutti i *file modificati* alla staging area e creare un commit in un solo comando, si può usare: ```bash ➜ git commit -am "Message describing changes made" ``` Se si vogliono aggiungere tutti i file, anche quelli untracked, non è possibile farlo in un solo comando. Si dovrà prima aggiungere i file all'area di staging con `git add -A` e poi creare il commit, seguendo l'iter classico. === Alias Spesso si utilizzano alias per abbreviare i comandi più lunghi, o combinare più comandi in uno solo. Per esempio, per creare un alias per aggiungere tutti i file in stage e quindi commitare anche i file untracked: ```bash ➜ git config --global alias.commit-all '!git add -A && git commit' ➜ git commit-all -m "MMessage describing changes made" ``` Per approfondire l'argomento degli alias, consigliamo di consultare la #link("https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases")[documentazione ufficiale di Git]. === Amend Attraverso il comando `git commit --amend` possiamo modificare l'ultimo commit che abbiamo effettuato. Questo ci permette sia di modificare il messaggio del commit, sia di aggiungere file che attualmente sono in stage al commit precedente; anziché creare un nuovo commit. L'idea è quindi di trasformare una situazione come questa: #align(center)[ #scale(90%)[ #v(5%) #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", color:blue, start:(0,1), length:3, commits:("init commit","second commit","unneeded commit",), head:2 ), edge((3,1),(4,1),"--",stroke:2pt+blue,label-pos:1,`some staged files`), ) #v(5%) ] ] In questa: #align(center)[ #scale(90%)[ #v(5%) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", color:blue, start:(0,1), length:3, commits:("init commit", "second commit", "renamed message\nall changes",), head:2 ), ) #v(5%) ] ] Per _aggiungere_ file in stage al commit precedente, è sufficiente lanciare il comando `git add <file>` (se non abbiamo già i file interessati in staging area) e successivamente `git commit --amend`. A questo punto si presenterà il file di modifica del commit nel nostro editor predefinito, qui possiamo modificare il messaggio del commit, leggere i cambiamenti apportati. Una volta salvato il file e chiuso, il commit verrà modificato. Se invece necessitiamo solo di _rinominare_ il commit, è sufficiente il comando `git commit --amend -m "changed message"` senza alcun file in staging area. Ovviamente questo comando non è sfruttabile per _correggere_ commit già pushati su un repository remoto, vedremo come superare anche questo ostacolo nei successivi capitoli. === Co-author in commit #grid(columns: 2, column-gutter: 1em, [Alcune piattaforme, come GitHub, permettono di aggiungere co-autori ai commit. Per farlo basta che il messaggio del commit sia formattato nel seguente modo: ],image("img/co-authored-commit.png")) ```bash ➜ git commit -m "Commit message > > Co-authored-by: NAME <<EMAIL>> Co-authored-by: ANOTHER-NAME <<EMAIL>>" ``` Per ulteriori informazionei consultare la #link("https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors")[documentazione ufficiale di GitHub]. === Visualizzare i commit Per visualizzare la cronologia dei commit, si utilizza: `git log`. Questo mostrerà i commit con il loro hash, l'autore, la data e il messaggio. Puoi anche usare opzioni come `--oneline` per una visualizzazione più compatta. ```bash ➜ git log --oneline 4f60048 (HEAD -> main, origin/main, my-fork/main, my-fork/HEAD) Merge pull request #3 from Username/main 7b6bc5a (my-fork/feature-1, feature-2, feature-1) Merge branch 'feature-2' 81a7ba6 feature 2 commit f679048 feature 1 commit ff2e750 renamed 0a0d983 ops 8732acf Create README.md ``` == Branch Le opzioni e operazioni sui branch sono moltissime, di seguito elenchiamo le più utili. === Creare un Nuovo Branch Per creare un nuovo branch, possiamo usare il comando: `git switch -c <new-branch> [<start-point>]`. #footnote([Con `[start-point]` s'intente l'hash commit da cui partire; le parentesi quadre indicano che è opzionale.]) Questo comando crea un nuovo branch e ci sposta su di esso. Alternativamente possiamo usare i comandi: `git checkout -b <new_branch> [<start_point>]` o `git branch <new_branch> [<start_point>]`. #footnote([L'ultima opzione non ci sposterà automaticamente sul nuovo branch]) === Rinominare un Branch Riprendendo subito il suggerimento ricevuto da GitHub nella @init-repo[Sezione] il comando: `git branch -M main` è opzionale, semplicemenete rinomina il branch principale come _main_ che lasciarlo a _master_; sta a voi scegliere se lanciare questo comando rinominandolo. Lo stesso comando può essere usato per rinominare un branch qualsiasi. === Eliminare un Branch in Locale Per eliminare un branch, possiamo usare il comando: `git branch -d <branch-name>`. #footnote([Per forzare l'eliminazione di un branch, utilizzare l'opzione `-D` al posto di `-d`. Questa opzione elimina il branch a prescindere dallo stato.]) === Spostarsi tra Branch Per spostarsi su un branch diverso, è sufficiente usare il comando: `git switch <branch-name>` o `git checkout <branch-name>`. Prima di proseguire con la spiegazione, è importante capire meglio concetto di HEAD. L'_HEAD_ è un *puntatore* che punta al commit attuale e consecutivamente il contenuto della working directory. Nei grafici che seguono, l'HEAD è rappresentata dal commit con il cerchio completamente riempito. Dunque, ciò che otteniamo è che l'HEAD si sposterà sul commit relativo al branch selezionato; per esempio ci troviamo sul branch _main_ e volessimo spostarci sul branch _develop_, il comando sarebbe: `git switch develop` o `git checkout develop`. Visivamente il cambiamento sarebbe questo: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( name:"main", color:blue, start:(0,0), length:5, head:4 ), // edge((5,0),(6,0),"--",stroke:2pt+blue), // //... other commits // develop branch connect_nodes((1,0),(2,1),orange), branch( name:"develop", indicator-xy:(7,1), color:orange, start:(1,1), length:5, ) ) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( name:"main", color:blue, start:(0,0), length:5 ), // develop branch connect_nodes((1,0),(2,1),orange), branch( name:"develop", indicator-xy:(7,1), color:orange, start:(1,1), length:5, head:4 ) ) ] ] === Spostarsi tra Commit In modo analogo, possiamo spostarci su un commit specifico con il comando: `git switch <commit-hash>` o `git checkout <commit-hash>`. Questo comando ci permette di spostare l'HEAD su un commit specifico, tuttavia ci troveremo in uno stato chiamato _detached HEAD_. Il detached HEAD è uno stato in cui l'HEAD non punta a nessun branch, ma direttamente ad un commit. Questo significa che se creiamo un nuovo commit in questo stato, non verrà aggiunto a nessun branch e potrebbe essere perso. #footnote([Ogni repository ha la sua HEAD, anche i remote. Il commit a cui punta la HEAD nei remote è l'ultimo commit del branch principale (generalmente _main_); ed è anche quello che si vede nella pagina web della repository]) Una rappresentazione visiva di questo stato è la seguente: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", color:blue, start:(0,1), length:5, ), connect_nodes((3,1),(4,2),orange), branch( // develop branch name:"develop", color:orange, start:(3,2), length:5, ), connect_nodes((3,0),(2,1),red), branch(// detached HEAD commits color: red, start:(2,0), length:3, head:2, ) ) ] ] === Spostare un Branch ad un commit specifico Fin'ora abbiamo sempre immaginato un branch come un come un'intera linea di commit, in realtà un branch non è altro che una label associata ad un commit specifico. Proprio per questo possiamo spostare un branch ad un altro commit con il comando `git branch --force <branch-name> [<new-tip-commit>]`. Per questo motivo alcuni grafici o alcuni plugin rappresentano, non solo ogni branch con colore diverso, ma anche la label del branch vicino al commit stesso. Per esempio, il grafico che abbiamo appena visto potrebbe essere rappresentato come: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", indicator-xy:(5.5,1), color:blue, start:(0,1), length:5, ), connect_nodes((3,1),(4,2),orange), branch( // develop branch name:"develop", indicator-xy:(7.75,1.5), color:orange, start:(3,2), length:5, ), connect_nodes((3,0),(2,1),red), branch(// detached HEAD commits color: red, start:(2,0), length:3, head:2, ) ) ] ] == Merge Per combinare le funzionalità implementate in 2 branch diversi, esistono diverse tecniche; in questa sezione copriremo solo il metodo di merge, in quanto è il più _sicuro_ e _semplice_. Nel capitolo riguardante la teoria, abbiamo visto il workflow (@workflow[Figure]) che vogliamo ottenere. Ci sono diverse situazioni in cui ci possiamo trovare: se il branch che vogliamo unire non ha subito modifiche durante lo sviluppo della nostra feature, il merge sarà detto _fast-forward_. #footnote([Si presuppone che l'etichetta del branch `main` sia sempre sull'ultimo commit _blu_. Ogni plug-in o rappresentazione grafica rappresenta i branch in maniera leggermente differente]) #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", color:blue, start:(0,1), length:3, ), connect_nodes((3,1),(4,2),orange), branch( // feature branch name:"feature", color:orange, start:(3,2), length:3, head: 2, ), ) ] ] In situazioni simili siamo sicuri che non si presenteranno conflitti di merge, e questo potrà avvenire con i comandi: `git switch main`, seguito da `git merge feature`. Così facendo otterremo un albero simile a questo: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", color:blue, start:(0,1), length:6, head: 5 ), branch_indicator("feature", (0,1.5), blue) ) ] ] Cosa accadrebbe se invece ci fossero stati dei commit sul main durante lo sviluppo della feature a cui siamo interessati? #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", color:blue, start:(0,1), length:3, ), connect_nodes((3,1),(4,1), blue, bend:20deg), branch( // feature 1 branch name:"feature 1", indicator-xy: (3.5,1.5), color:blue, start:(3,1), length:3, ), connect_nodes((3,1),(4,2),teal), branch( // feature 2 branch name:"feature 2", color: teal, start: (3,2), length: 3, head: 2 ) ) ] ] Il grafico si presenterebbe in questo modo: il branch _main_ ha subito delle modifiche e per evidenziare che la _feature 1_ è stata integrata nel _main_ abbiamo utilizzato lo stesso colore blu ma con il collegamento dei nodi diverso per evidenziare l'inizio dei commit appartenenti alla _feature 1_. Per capire meglio la situazione, possiamo anche ridisegnare il grafico nel seguente modo, dove le etichette dei branch sono allineate con il commit su cui si trovano: #footnote([Questa rappresentazione è simile a quella del plug-in per VS-Code Git Graph che raccomandiamo]) #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", indicator-xy: (5.75,0), color:blue, start:(0,1), length:3, ), connect_nodes((3,1),(4,1), blue, bend:0deg), branch( // feature 1 branch name:"feature 1", indicator-xy: (5.75,0.5), color:blue, start:(3,1), length:3, ), connect_nodes((3,1),(4,2),teal), branch( // feature 2 branch name:"feature 2", indicator-xy: (5.75,2.5), color: teal, start: (3,2), length: 3, head: 2 ) ) ] ] In questo caso non possiamo sapere a priori se ci saranno o meno conflitti di merge. Per unire i due branch, come prima, possiamo usare i comandi: `git switch main`, seguito da `git merge feature-2`. In questo caso, se ci sono conflitti di merge, ci verranno notificati sul terminale e dovremo risolverli manualmente. Come esempio, ho utilizzato una stringa diversa sulla stessa linea del file README.md in due branch diversi. Il risultato quando si tenta di fare il merge del secondo branch è il seguente: ```bash ➜ git merge feature-2 Auto-merging README.md CONFLICT (content): Merge conflict in README.md Automatic merge failed; fix conflicts and then commit the result. ``` A seconda dell'editor che utilizziamo i file contenenti i conflitti saranno o meno evidenziati. Comunque ogni file con conflitto all'apertura mostrerà qualcosa di simile: #align(center)[ #image("/book/img/file-with-merge-conflicts.png") ] A questo punto non ci rimane che rimuovere il cambiamento che non vogliamo mantenere o in alternativa combinare entrambi. Proseguiamo salvando il file, chiudendolo e assicurandoci che sia nella staging area con il comando: `git add ...`. Ora possiamo lanciare il comando `git commit` (che assegnerà il messaggio di default: _"Merge branch feature-2"_). Ora il nostro albero sarà: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", indicator-xy: (6.75,0.5), color:blue, start:(0,1), length:7, head: 6, commits:("", "", "", "", "", "", "Merge branch feature-2"), alignment: bottom ), branch_indicator("feature 1", (5.75,0.5), blue), connect_nodes((3,1),(4,2),teal), branch( // feature 2 branch name:"feature 2", indicator-xy: (5.75,2.5), color: teal, start: (3,2), length: 3, ), //merge edge connect_nodes((6,2),(7,1),teal), ) ] ] È importante notare diverse cose: - Il branch _feature-2_ non è stato eliminato ed è ancora al suo ultimo commit. - Anche il branch _feature-1_ è ancora al suo ultimo commit. - Per entrambi i branch _feature_ si tratta di un "merge _fast-forward_": infatti se ci spostiamo su uno dei due e diamo il comando `git merge main` non avremo conflitti di alcun tipo. Se lo facciamo per entrambi otterremo: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", indicator-xy: (6.75,0.5), color:blue, start:(0,1), length:7, head: 6, commits:("", "", "", "", "", "", "Merge branch feature-2"), alignment: bottom ), branch_indicator("feature 1", (6.75,0), blue), branch_indicator("feature 2", (6.75,-0.5), blue), //other branch stuff connect_nodes((3,1),(4,2),teal), branch( // old branch name:"", color: teal, start: (3,2), length: 3, ), connect_nodes((6,2),(7,1),teal), ) ] ] == Gestione dei Remote Repository Finora abbiamo lavorato solo sul repository locale, affrontando gli scenari senza considerare il remote repository. In questo capitolo sopperiremo a questa mancanza. === Analisi Per avere informazioni sui remote possiamo servirci di diversi comandi: ```bash ➜ git remote show #show the name of all remotes origin ➜ git remote show origin #show info about one remote * remote origin Fetch URL: https://github.com/nome-organizzazione/nome-repo.git Push URL: https://github.com/nome-organizzazione/nome-repo.git HEAD branch: (unknown) ➜ git remote -v #show info about all remotes origin https://github.com/nome-organizzazione/nome-repo.git (fetch) origin https://github.com/nome-organizzazione/nome-repo.git (push) ``` Come si può intuire il comando suggerito da GitHub: `git remote add origin URL`, (visto nella @init-repo[Sezione]) aggiungerà l'URL come repository remote, con il nome *origin*. === Aggiornamento con git fetch Il comando `git fetch` scarica nuovi commit, branches e tags dai remote repository e ci permette così di confrontare le informazioni ricevute con la nostra repo locale. Tutto questo viene performato senza applicare le modifiche ai nostri branch in locale. In particolare il comando ha questa sintassi: `git fetch <remote> <refspec>`. Se lanciato senza argomenti potrebbe non aggiornare tutti i remote (o quello che ci interessa). Per sapere quali remote coinvolge l'operazione di fetch è sufficiente il comando: ```bash ➜ git fetch -v POST git-upload-pack (186 bytes) From https://github.com/Owner/repo = [up to date] main -> origin/main = [up to date] feature-1 -> origin/feature-1 = [up to date] feature-2 -> origin/feature-2 ``` Di default, git utilizza _origin_ come remote, quindi per esempio se avvessimo un remote, come quello rappresentato qui; il comando non funzionerebbe: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // origin main branch name:"main", remote: "my-fork", indicator-xy: (4.75,0.5), color:blue, start:(0,1), length:5, head: 4, ), ) ] ] Ci sono diverse soluzioni che potremmo adottare: - Ovviamente usare il comando specifico: `git fetch my-fork` - Applicare il fetch a tutti i remote: `git fetch --all` - Impostare il remote che ci interessa come default. Questo è possibile farlo sia modificando il file in `.git/config`, sia con il comando === Operazioni di Push e Pull Le operazioni di push e pull sono fondamentali per mantenere sincronizzati i repository locali e remoti. Come si evince dal nome stesso del comando, `git push` invia le modifiche locali al repository remoto, mentre `git pull` scarica le modifiche dal repository remoto. Per identificare l'appartenenza di un branch ad un repository remoto nella label del branch useremo la notazione _remote/branch_: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", indicator-xy: (6.75,0.5), color:blue, start:(0,1), length:7, head: 6, ), // origin/main indicator branch_indicator("origin/main", (3.75,0.5), blue), ) ] ] Nel caso appena presentato, il branch _main_ nella repository locale è "più avanti" rispetto a quello della repository remota. Per sincronizzare i due branch, dunque, dovremo fare un _push_. Una volta lanciato il comando `git push origin main`, se tutto va a buon fine, il risultato sarà: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // main branch name:"main", remote: "orgin", indicator-xy: (6.75,0.5), color:blue, start:(0,1), length:7, head: 6, ), ) ] ] Come potete osservare usiamo questa label speciale per indicare che il branch in locale è allineato con quello remoto. In un caso simile, invece, è utile spostarsi sul branch main ed effettuare un _pull_: stiamo sviluppando la nostra feature e qualcuno ha pushato sul branch main in remoto. #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch_indicator("main", (3.75,0.5), blue), branch( // main branch name:"main/origin", indicator-xy: (6.8,0.5), color:blue, start:(0,1), length:7, head: 6, ), //other branch stuff connect_nodes((3,1),(4,2),teal), branch( // old branch name:"feature", indicator-xy: (6,2.5), color: teal, start: (3,2), length: 3, ), ) ] ] Ci sono molte altre opzioni applicabili ai comandi `git push` e `git pull`, oltre a `-u` che abbiamo visto nei capitoli precedenti; come: `--force` e `--force-with-lease` vi consigliamo a leggere la documentazione ufficiale@git-docs prima di utilizzarle. === Pull Request Le Pull Request (PR) sono lo strumento con cui applichiamo modifiche in repository su cui non abbiamo permessi. Sono largamente utilizzate da parte della community e supportate da GitHub, Git Lab (Merge Request) e BitBucket. Le PR permettono di sottoporre le features sviluppate ai maintainers del progetto originale, queste saranno visibili a tutta l'organizzazione (se privata, o in alternativa a tutti). Successivamente può essere accettata, rifiutata o soggetta ad aggiustamenti. #footnote([Su GitHub le PR non possono essere eliminate se non contattando l'assistenza di GitHub stesso.]) Alla stregua di un merge anche le PR possono avere dei conflitti, che devono essere risolti al fine di integrare le features desiderate. È possibile creare le Pull Requests sia attraverso l'interfaccia web (per ogni repo di GitHub abbiamo la sezione in alto dedicata), sia via CLI. Di seguito un esempio di PR via CLI con il comando gh: #footnote([Se ancora non è stato fatto, prima di procedere è necessario il login tramite `gh` e l'impostazione del repo di default con il comando interattivo `gh repo set-default`]) ```bash ➜ gh pr create ? Where should we push the 'feature-1' branch? [Use arrows to move, type to filter] > Username/project Skip pushing the branch Cancel ``` Una Pull Request è generalmente composta da: titolo, body (descrizione dettagliata), lista di commits. Di seguito il comando che abbiamo dato chi chiede appunto le prime due informazioni: ```bash Creating pull request for Username:feature-1 into main in Official-Owner/project ? Title implemented feature-1 stuff ? Body <Received> ? What's next? Submit remote: remote: To https://github.com/Username/project.git * [new branch] HEAD -> feature-1 branch 'feature-1' set up to track 'my-fork/feature-1'. https://github.com/Official-Owner/project/pull/1 ``` Ad una PR sono inoltre associate delle etichette, personalizzate a seconda della repo, i reviewers richiesti, i quali possono essere modificati, ed i commenti della community. Vediamo ora un caso completo: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch_indicator("my-fork/main", (4.5,1.5), blue), branch_indicator("origin/main", (0.75,0.5), blue), branch( // main branch name:"main", indicator-xy: (5.75,0.5), color:blue, start:(0,1), length:6, head: 5, commits:("","","",none,"","",) ), //feature-2 branch connect_nodes((3.5,0),(3,1),orange), branch( name: "feature-2", indicator-xy: (5,0), color: orange, start: (2.5,0), length:2 ), connect_nodes((5,1),(4.5,0),orange), //feature-1 branch connect_nodes((2,1),(3,2),teal), branch( name:"feature-1", indicator-xy: (6,1.5), color: teal, start: (2,2), length: 3, ), connect_nodes((5,2),(6,1),teal), ) ] ] In questa situazione abbiamo sviluppato due features differenti, mergiato la _feature-2_ in locale e pushato sul fork. Successivamente abbiamo completato la _feature-1_ e la abbiamo mergiata. A questo punto applichiamo tutto quello che abbiamo visto in questo capitolo: spostandoci sul branch _main_ effettuiamo un push verso il nostro fork con il comando: `git push my-fork`. #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch_indicator("origin/main", (0.75,0.5), blue), branch( // main branch name:"main", remote:"my-fork", indicator-xy: (5.75,0.5), color:blue, start:(0,1), length:6, head: 5, commits:("","","",none,"","",) ), //feature-2 branch connect_nodes((3.5,0),(3,1),orange), branch( name: "feature-2", indicator-xy: (5,0), color: orange, start: (2.5,0), length:2 ), connect_nodes((5,1),(4.5,0),orange), //feature-1 branch connect_nodes((2,1),(3,2),teal), branch( name:"feature-1", indicator-xy: (6,1.5), color: teal, start: (2,2), length: 3, ), connect_nodes((5,2),(6,1),teal), ) ] ] A questo punto possiamo procedere con la nostra PR, scegliendo com'è comune di rimanere sul nostro branch _main_ quando lanciamo il comando `gh pr create`; in questo modo la PR verrà proprio da quello. #footnote([Non è possibile avere più PR aperte provenienti dallo stesso branch dello stesso fork.]) Una volta che la richiesta verrà accettata, possiamo lanciare il comando `git fetch origin` per conoscere le modifiche più recenti sul remote origin e ci troveremo in questo stato: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // remote origin name:"origin/main", indicator-xy: (6,-0.5), color:lime, start:(0,-1), length:7, commits:("",none,none,none,none,none,"merge pr") ), connect_nodes((1,-1),(2,1),blue), branch( // main branch name:"main", remote:"my-fork", indicator-xy: (5.75,0.5), color:blue, start:(1,1), length:5, head: 4, commits:("","",none,"","") ), connect_nodes((6,1),(7,-1),blue,bend:-25deg), //feature-2 branch connect_nodes((3.5,0),(3,1),orange), branch( name: "feature-2", indicator-xy: (5,0), color: orange, start: (2.5,0), length:2 ), connect_nodes((5,1),(4.5,0),orange), //feature-1 branch connect_nodes((2,1),(3,2),teal), branch( name:"feature-1", indicator-xy: (6,1.5), color: teal, start: (2,2), length: 3, ), connect_nodes((5,2),(6,1),teal), ) ] ] Questo tipo di grafico è normalissimo, se lo analizziamo, notiamo che _origin/main_ ha come primo commit l'ultimo commit in comune e come ultimo commit quello di merge. Fortunatamente per noi i maintainer del progetto per accettare la PR hanno dovuto performare questo merge. Ora non ci rimane che sincronizzare il nostro fork e la nostra repository locale. Sia l'interfaccia web che il tool gh permettono di sincronizzare un branch del nostro fork con la versione più recente del remote originale. Il comando per farlo è: `gh repo sync owner/cli-fork -b BRANCH-NAME`@gh-sync. Nel nostro caso il `BRANCH-NAME` sarà ovviamente _main_. Per proseguire l'esempio un passo alla volta ed accertarci che tutto sia andato come ci aspettavamo, possiamo lanciare nuovamente `git fetch`: #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch_indicator("my-fork/main", (6,-0.75), lime), branch( // remote origin name:"origin/main", indicator-xy: (6,-0.45), color:lime, start:(0,-1), length:7, commits:("",none,none,none,none,none,"merge pr") ), connect_nodes((1,-1),(2,1),blue), branch( // main branch name:"main", indicator-xy: (5.75,0.5), color:blue, start:(1,1), length:5, head: 4, commits:("","",none,"","") ), connect_nodes((6,1),(7,-1),blue,bend:-25deg), //feature-2 branch connect_nodes((3.5,0),(3,1),orange), branch( name: "feature-2", indicator-xy: (5,0), color: orange, start: (2.5,0), length:2 ), connect_nodes((5,1),(4.5,0),orange), //feature-1 branch connect_nodes((2,1),(3,2),teal), branch( name:"feature-1", indicator-xy: (6,1.5), color: teal, start: (2,2), length: 3, ), connect_nodes((5,2),(6,1),teal), ) ] ] Se tutto è andato come ci aspettiamo l'ultima cosa rimasta da fare è aggiornare il branch _main_ in locale con `git pull` se ci siamo sopra, altrimenti specificando branch e remote. #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // remote origin name:"main", remote:("origin","my-fork"), indicator-xy: (6,-0.5), color:lime, start:(0,-0.75), length:7, head: 6, commits:("",none,none,none,none,none,"merge pr") ), connect_nodes((1,-0.75),(2,1),blue), branch( // main branch name:"", indicator-xy: (5.75,0.5), color:blue, start:(1,1), length:5, commits:("","",none,"","") ), connect_nodes((6,1),(7,-0.75),blue,bend:-25deg), //feature-2 branch connect_nodes((3.5,0),(3,1),orange), branch( name: "feature-2", indicator-xy: (5,0), color: orange, start: (2.5,0), length:2 ), connect_nodes((5,1),(4.5,0),orange), //feature-1 branch connect_nodes((2,1),(3,2),teal), branch( name:"feature-1", indicator-xy: (6,1.5), color: teal, start: (2,2), length: 3, ), connect_nodes((5,2),(6,1),teal), ) ] ] === Rimuovere i branch remoti Riprendendo l'esempio precedente, per pulire tutto, vorremmo elimnare i branch delle features che abbiamo utilizzato in precedenza. Supponiamo di aver pushato _feature-2_ in precedenza; la situazione che si presenta è questa: #footnote([Se invece un branch, creato da altri, quindi di cui non abbiamo la copia in locale, viene eliminato direttamente nel remote, basterà eseguire `git fetch --all --prune`]) #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // remote origin name:"main", remote:("origin","my-fork"), indicator-xy: (6,-0.5), color:lime, start:(0,-0.75), length:7, head:6, commits:("",none,none,none,none,none,"merge pr") ), connect_nodes((1,-0.75),(2,1),blue), branch( // main branch name:"", indicator-xy: (5.75,0.5), color:blue, start:(1,1), length:5, commits:("","",none,"","") ), connect_nodes((6,1),(7,-0.75),blue,bend:-25deg), //feature-2 branch connect_nodes((3.5,0),(3,1),orange), branch( name: "feature-2", remote:("my-fork"), indicator-xy: (5,0), color: orange, start: (2.5,0), length:2 ), connect_nodes((5,1),(4.5,0),orange), //feature-1 branch connect_nodes((2,1),(3,2),teal), branch( name:"feature-1", indicator-xy: (6,1.5), color: teal, start: (2,2), length: 3, ), connect_nodes((5,2),(6,1),teal), ) ] ] Per prima cosa ci spostiamo su un branch locale diverso da quelli che vogliamo eliminare. Per eliminare il branch in remoto diamo il comando `git push my-fork -d feature-2 ` e subito dopo per elimnarlo in locale possiamo dare `git branch -d feature-1 feature-2`. Per concludere possiamo lanciare il comando `git fetch --all`. #align(center)[ #scale(90%)[ #set text(10pt) #diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, branch( // remote origin name:"main", remote:("origin","my-fork"), indicator-xy: (6,-0.5), color:lime, start:(0,-0.75), length:7, commits:("",none,none,none,none,none,"merge pr") ), connect_nodes((1,-0.75),(2,1),blue), branch( // main branch name:"", indicator-xy: (5.75,0.5), color:blue, start:(1,1), length:5, head: 4, commits:("","",none,"","") ), connect_nodes((6,1),(7,-0.75),blue,bend:-25deg), //orange branch connect_nodes((3.5,0),(3,1),orange), branch( name: "", indicator-xy: (5,0), color: orange, start: (2.5,0), length:2 ), connect_nodes((5,1),(4.5,0),orange), //teal branch connect_nodes((2,1),(3,2),teal), branch( name:"", indicator-xy: (6,1.5), color: teal, start: (2,2), length: 3, ), connect_nodes((5,2),(6,1),teal), ) ] ]
https://github.com/ddorn/cv
https://raw.githubusercontent.com/ddorn/cv/master/readme.md
markdown
This contains my resume. Feel free to copy the template if you want to, it is made with [Typst](https://typst.app/), a modern alternative to LaTeX. [link to PDF version](./out/resume.pdf)
https://github.com/darioglasl/Arbeiten-Vorlage-Typst
https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/Anhang/05_Modulbeschreibung/00_index.typ
typst
== Modulbeschreibung Studienarbeit Informatik <appendixModulbeschreibung> Auszug der Modulbeschreibung auf https://studien.rj.ost.ch/ @modulbeschreibungSA. === Meta Daten #figure( table( columns: (auto, auto), inset: 8pt, align: left, [Kurzzeichen], [M_SAI21], [Durchführungszeitraum], [HS/22-FS/25], [ECTS-Punkte], [8], [Lernziele], [Die Arbeit soll den Nachweis der Problemlösungsfähigkeit unter Anwendung ingenieurmässiger Methoden nachweisen. Entsprechend verfügt die Arbeit über einen konzeptionellen, theoretischen und einen praktischen Anteil.], [Verantwortliche Person], [<NAME>], [Standort (angeboten)], [Rapperswil-Jona], [Vorausgesetzte Module], [SE Project (M_SEProj, FS/22-FS/25)], [Zusätzlich vorausgesetzte Kenntnisse], [keine], ), caption: "Modulbeschreibung Studienarbeit Informatik", ) === Genauere Beschreibung Die Studienarbeiten werden in der Regel in 2-er Teams bearbeitet und von einem Dozent betreut. Die Studienarbeit dauert ca. 14 Wochen mit einem Arbeitsaufwand von insgesamt mindestens 240h. Das Thema der Arbeit kann von einer externen Firma, vom Dozenten oder von den Studenten vorgeschlagen werden. Die definitive Aufgabenstellung stellt der betreuende Dozent. Die Arbeit soll den Nachweis der Problemlösungsfähigkeit unter Anwendung ingenieurmässiger Methoden nachweisen. Entsprechend sollte die Arbeit über einen konzeptionellen, theoretischen und einen praktischen Anteil verfügen. In der Regel wird ein Informatik-Projekt bearbeitet mit den folgenden Teilaufgaben: - Einarbeitung in eine neue Aufgabenstellung - Planung des Projektes - Analyse der Anforderungen (inkl. Umfeldbeschreibung und Abgrenzung) - Entwurf und Realisierung der Lösung (inkl. Bewertung des Standes der Technik) - Test der Lösung - Bewertung und Ausblick
https://github.com/AOx0/expo-nosql
https://raw.githubusercontent.com/AOx0/expo-nosql/main/book/src/slide.md
markdown
MIT License
# Creating slides To fill your presentation with content, you can use the `#slide` function. The only required argument is some content that is supposed to be displayed on the slide, so in the simplest case you can just write ```typ #slide[ Your slide content ] ``` However, there are a couple optional keyword arguments you can provide in the form of ```typ #slide(key: value)[ Your slide content ] ``` These are: - `theme-variant`: when you want this slide to look slightly different, see [here](./themes.html#theme-variants-per-slide) - `override-theme`: when you want this slide to look completely different, see [here](./themes.html#per-slide-escape-hatch) - `max-repetitions`: when you create a slide with a _lot_ of dynamic content, see [here](./dynamic.html#internal-number-of-repetitions) - additional information used by the theme, see the [gallery](./theme-gallery/index.html) to find out which they are under your theme's "Extra keyword arguments" section (typically, you can at least specify a slide title as `title`) ## Slides with multiple content bodies In the vast majority of cases, you will call `#slide` the way described above with one content block. However, some [themes](./themes.html) (or some of their [variants](./themes.html#theme-variants-per-slide)) sometimes require or allow more than one such content. In that case, you will write: ```typ #slide[ The first piece of content ][ Even more content ][ Who knows how much content we can come up with? ] ```
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/page-number-align.typ
typst
Apache License 2.0
// Test page number alignment. --- #set page( height: 100pt, margin: 30pt, numbering: "(1)", number-align: top + right, ) #block(width: 100%, height: 100%, fill: aqua.lighten(50%)) --- #set page( height: 100pt, margin: 30pt, numbering: "[1]", number-align: bottom + left, ) #block(width: 100%, height: 100%, fill: aqua.lighten(50%)) --- // Error: 25-39 page number cannot be `horizon`-aligned #set page(number-align: left + horizon)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-27.typ
typst
Other
// Error: 2-14 cannot calculate product of empty array with no default #().product()
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/1e67fb-mma_final_report/main.typ
typst
= 符号计算软件大作业报告 PB21000030 马天开 #table( columns: (1fr, 1fr), align: center, [ Input ], [ Output ], image("imgs/input.jpg", width: 100%), image("imgs/output.png", width: 100%), ) 做了个简单的图像风格化的程序,最后代码大概100行左右,效果如上图所示。 == 处理思路 - Possion Disk Sampling,这个或许 Mathematica 有库函数,对照伪代码,自己搓了一个。 - Delaunay 三角剖分,这个 Mathematica 有现成的,拿来主义。 - 对每个三角形取中心点,取中心点的颜色,填充三角形。 - Manipulate 调整参数,可以调整采样半径。 == 使用方法 需要调整一下 `img=Import["~/Source/tiankaima/Notebooks/mma/cropped_img.jpg"];` 这一行,把图片路径改成自己的图片路径。 (当然,星空的图片我也附带打包进去了,这个效果还是美一点的) == 亮点 我也不清楚要说什么了,总之有些地方可能顺手一点用了 lambda 函数,有些地方写的也比较别扭(#strike[可能正常的编程语言写多了是这样的]) #pagebreak() == Code ```wolfram ClearAll["Global`"] img = Import["~/Source/tiankaima/Notebooks/mma/cropped_img.jpg"]; imageWidth = ImageDimensions[img][[1]]; Manipulate[ Module[ {radius = selectedRadius, width = 1.0, height = 1.0, k = 30, gridSize, grid, activeList, samplePoints, initialPoint, point, found, newPoint, idxIdx, idx, gi, gj, triangles, scaledPoints, coloredTriangles}, gridSize = radius/Sqrt[2]; grid = Table[-1, {i, Ceiling[height/gridSize]}, {j, Ceiling[width/gridSize]}]; activeList = {}; samplePoints = {}; distance[a_, b_] := Norm[a - b]; gridPos[p_] := Floor[p/gridSize] + 1; randomPointAround[{x_, y_}] := With[ {r = RandomReal[{radius, 2 radius}], theta = RandomReal[{0, 2 Pi}]}, {x + r Cos[theta], y + r Sin[theta]} ]; isValidPoint[p : {x_, y_}] := 0 <= x <= width && 0 <= y <= height && AllTrue[Flatten[ Table[ If[grid[[i, j]] != -1, distance[samplePoints[[grid[[i, j]]]], p] >= radius, True ], {i, Max[1, gridPos[p][[1]] - 2], Min[Length[grid], gridPos[p][[1]] + 2]}, {j, Max[1, gridPos[p][[2]] - 2], Min[Length[grid[[1]]], gridPos[p][[2]] + 2]}], 2], Identity ]; initialPoint = {RandomReal[width], RandomReal[height]}; AppendTo[samplePoints, initialPoint]; AppendTo[activeList, initialPoint]; {gi, gj} = gridPos[initialPoint]; grid[[gi, gj]] = 1; While[activeList != {}, idx = RandomInteger[{1, Length[activeList]}]; point = activeList[[idx]]; found = False; Do[newPoint = randomPointAround[point]; If[isValidPoint[newPoint], AppendTo[samplePoints, newPoint]; AppendTo[activeList, newPoint]; {gi, gj} = gridPos[newPoint]; grid[[gi, gj]] = Length[samplePoints]; found = True; Break[]; ], {k}]; If[! found, activeList = Delete[activeList, idx] ]; ]; scaledPoints = samplePoints*imageWidth; triangles = DelaunayMesh[scaledPoints]; triangleCentroid[pts_] := Mean[pts]; sampleColor[pt_] := PixelValue[img, pt]; coloredTriangles = Graphics[{ EdgeForm[], Table[{ RGBColor[ sampleColor[ triangleCentroid[MeshCoordinates[triangles][[triangle]]]]], Triangle[MeshCoordinates[triangles][[triangle]]] }, { triangle, First /@ MeshCells[triangles, 2]}] }, Frame -> False ]; Show[coloredTriangles, Frame -> False] ], {{selectedRadius, 0.02, "Radius"}, {0.01, 0.02, 0.04, 0.08, 0.16, 0.32}} ] ```
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/pattern-stroke_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #align( center + top, square( size: 50pt, stroke: 5pt + pattern( size: (5pt, 5pt), align(horizon + center, circle(fill: blue, radius: 2.5pt)) ) ) )
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/basic/writing-markup.typ
typst
Apache License 2.0
#import "mod.typ": * #show: book.page.with(title: [初识标记模式]) Typst是一门简明但强大的现代排版语言,你可以使用简洁直观的语法排版出好看的文档。 Typst希望你总是尽可能少的配置样式,就获得一个排版精良的文档。多数情况下,你只需要专心撰写文档,而不需要在文档内部对排版做任何更复杂的调整。 得益于此设计目标,为了使你可以用Typst编写一篇基本文档,本节仍只需涉及最基本的语法。哪怕只依靠这些语法,你已经可以编写满足很多场合需求的文档。 == 段落 <grammar-paragraph> 普通文本默认组成一个个段落。 #code(```typ 我是一段文本 ```) 另起一行文本不会产生新的段落。为了创建新的段落,你需要空至少一行。 #code(```typ 轻轻的我走了, 正如我轻轻的来; 我轻轻的招手, 作别西天的云彩。 ```) 缩进并不会产生新的空格: #code(```typ 轻轻的我走了, 正如我轻轻的来; 我轻轻的招手, 作别西天的云彩。 ```) 注意:如下图的蓝框高亮所示,另起一行会引入一个小的空格。该问题会在未来修复。 #code( ```typ 轻轻的我走了,#box(fill: blue, outset: (right: 0.2em), sym.space) 正如我轻轻的来; 轻轻的我走了,正如我轻轻的来; ```, code-as: ```typ 轻轻的我走了, 正如我轻轻的来; 轻轻的我走了,正如我轻轻的来; ```, ) == 标题 <grammar-heading> 你可以使用一个或多个*连续*的#mark("=")开启一个标题。 #code(```typ = 一级标题 我走了。 == 二级标题 我来了。 === 三级标题 我走了又来了。 ```) 等于号的数量恰好对应了标题的级别。一级标题由一个#mark("=")开启,二级标题由两个#mark("=")开启,以此类推。 注意:正如你所见,标题会强制划分新的段落。 #pro-tip[ 使用show规则可以改变“标题会强制划分新的段落”这个默认规则。 #code(```typ #show heading.where(level: 3): box = 一级标题 我走了。 === 三级标题 我走了又来了。 ```) ] == 着重和强调语义 有许多与#mark("=")类似的语法标记。当你以相应的语法标记文本内容时,相应的文本就被赋予了特别的语义和样式。 #pro-tip[ 与HTML一样,Typst总是希望语义先行。所谓语义先行,就是在编写文档时总是首先考虑标记语义。所有样式都是附加到语义上的。 例如在英文排版中,#typst-func("strong")的样式是加粗,#typst-func("emph")的样式是倾斜。你完全可以在中文排版中为它们更换样式。 #code(```typ #show strong: content => { show regex("\p{Hani}"): it => box(place(text("·", size: 1.3em), dx: 0.3em, dy: 0.5em) + it) content.body } *中文排版的着重语义用加点表示。* ```) ] 与许多标记语言相同,Typst中使用一系列#term("delimiter")规则确定一段语义的开始和结束。为赋予语义,需要将一个#term("delimiter")置于文本*之前*,表示某语义的开始;同时将另一个#term("delimiter")置于文本*之后*,表示该语义的结束。 例如,#mark("*")作为定界符赋予所包裹的一段文本以#term("strong semantics", postfix: "。") <grammar-strong> #code(```typ 着重语义:这里有一个*重点!* ```) 与#term("strong semantics")类似,#mark("_")作为定界符将赋予#term("emphasis semantics", postfix: ":") <grammar-emph> #code(```typ 强调语义:_emphasis_ ```) 着重语义一般比强调语义语气更重。着重和强调语义可以相互嵌套: #code(```typ 着重且强调:*_strong emph_* 或 _*strong emph*_ ```) 注意:中文排版一般不使用斜体表示着重或强调。 == (计算机)代码片段 <grammar-raw> Typst的#term("raw block")标记语法与Markdown完全相同。 配对的#mark("`")包裹一段内容,表示内容为#term("raw block", postfix: "。") #code(````typ 短代码片段:`code` ````) 有时候你希望允许代码内容包含换行或#mark("`", postfix: "。")这时候,你需要使用*至少连续*三个#mark("`")组成定界符标记#term("raw block", postfix: ":")<grammar-long-raw> #code(`````typ 使用三个反引号包裹:``` ` ``` 使用四个反引号包裹:```` ``` ```` `````) 对于长代码片段,你还可以在起始定界符后*紧接着*指定该代码的语言类别,以便Typst据此完成语法高亮。<grammar-lang-raw> #code(`````typ 一段有高亮的代码片段:```javascript function uninstallLaTeX {}``` 另一段有高亮的代码片段:````typst 包含反引号的长代码片段:``` ` ``` ```` `````) 除了定界符的长短,代码片段还有是否成块的区分。如果代码片段符合以下两点,那么它就是一个#term("blocky raw block", postfix: ":") <grammar-blocky-raw> + 使用*至少连续*三个#mark("`"),即其需为长代码片段。 + 内容包含至少一个#term("line break", postfix: "。") #code(`````typ 非块代码片段:```rust trait World``` 块代码片段:```js function fibnacci(n) { return n <= 1 ?: `...`; } ``` `````) // typ // typc == 列表 Typst的列表语法与Markdown非常类似,但*不完全相同*。 一行以#mark("-")开头即开启一个无编号列表项: <grammar-enum> #code(```typ - 一级列表项1 ```) 与之相对,#mark("+")开启一个有编号列表项。 <grammar-list> #code(```typ + 一级列表项1 ```) 利用缩进控制列表项等级: #code(```typ - 一级列表项1 - 二级列表项1.1 - 三级列表项1.1.1 - 二级列表项1.2 - 一级列表项2 - 二级列表项2.1 ```) 有编号列表项可以与无编号列表项相混合。<grammar-mix-list-emum> #code(```typ + 一级列表项1 - 二级列表项1.1 + 三级列表项1.1.1 - 二级列表项1.2 + 一级列表项2 - 二级列表项2.1 ```) 和Markdown相同,Typst同样允许使用显式的编号`1.`开启列表。这方便对列表继续编号。<grammar-continue-list> #code(```typ 1. 列表项1 1. 列表项2 ```) #code(```typ 1. 列表项1 + 列表项2 列表间插入一段描述。 3. 列表项3 + 列表项4 + 列表项5 ```) == 转义序列 <grammar-escape-sequences> 你有时希望直接展示标记符号本身。例如,你可能想直接展示一个#mark("_", postfix: ",")而非使用强调语义。这时你需要利用#term("escape sequences")语法: #code(````typ 在段落中直接使用下划线 >\_<! ````) 遵从许多编程语言的习惯,Typst使用#mark("\\")转义特殊标记。下表给出了部分可以转义的字符: #let escaped-sequences = ( (`\\`, [\\]), (`\/`, [\/]), (`\[`, [\[]), (`\]`, [\]]), (`\{`, [\{]), (`\}`, [\}]), (`\<`, [\<]), (`\>`, [\>]), (`\(`, [\(]), (`\)`, [\)]), (`\#`, [\#]), (`\*`, [\*]), (`\_`, [\_]), (`\+`, [\+]), (`\=`, [\=]), (`\~`, [\~]), // @typstyle off (```\` ```, [\`]), (`\$`, [\$]), (`\"`, [\"]), (`\'`, [\']), (`\@`, [\@]), (`\a`, [\a]), (`\A`, [\A]), ) #let mk-tab(seq) = { set align(center) let u = it => raw(it.at(0).text, lang: "typ") let ovo = it => it.at(1) let w = 8 table( columns: w + 2, [代码], ..seq.slice(w * 0, w * 1).map(u), u((`\u{cccc}`, [\u{cccc}])), [效果], ..seq.slice(w * 0, w * 1).map(ovo), [\u{cccc}], [代码], ..seq.slice(w * 1, w * 2).map(u), u((`\u{cCCc}`, [\u{cCCc}])), [效果], ..seq.slice(w * 1, w * 2).map(ovo), [\u{cCCc}], [代码], ..seq.slice(w * 2).map(u), [], u((`\u{2665}`, [\u{2665}])), [效果], ..seq.slice(w * 2).map(ovo), [], [\u{2665}], ) } #mk-tab(escaped-sequences) 以上大部分#term("escape sequences")都紧跟单个字符,除了表中的最后一列。 <grammar-unicode-escape-sequences> 表中的最后一列所展示的`\u{unicode}`语法被称为Unicode转义序列,也常见于各种语言。你可以通过将`unicode`替换为#link("https://zh.wikipedia.org/zh-cn/%E7%A0%81%E4%BD%8D")[Unicode码位]的值,以输出该特定字符,而无需*输入法支持*。例如,你可以这样输出一句话: #code( ````typ \u{9999}\u{8FA3}\u{725B}\u{8089}\u{7C89}\u{597D}\u{5403}\u{2665} ````, code-as: ````typ \u{9999}\u{8FA3}\u{725B}\u{8089}\u{7C89} \u{597D}\u{5403}\u{2665} ````, ) 诸多#term("escape sequences")无需死记硬背,你只需要记住: + 如果其在Typst中已经被赋予含义,请尝试在字符前添加一个#mark("\\", postfix: "。") + 如果其不可见或难以使用输入法获得,请考虑使用`\u{unicode}`。 == 输出换行符 <grammar-newline> 输出换行符是一种特殊的#term("escape sequences", postfix: ",")它使得文档输出换行。 #mark("\\")后紧接一个任意#term("whitespace", postfix: ",")表示在此处主动插入一个段落内的换行符: <grammar-newline-by-space> #code(````typ 转义空格可以换行 \ 转义回车也可以换行 \ 换行! ````) 空白字符可以取短空格(`U+0020`)、长空格(`U+3000`)、回车(`U+000D`)等。 == 速记符号 <grammar-shorthand> 在#term("markup mode")下,一些符号需要用特殊的符号组合打出,这种符号组合被称为#term("shorthand", postfix: "。")它们是: 空格(`U+0020`)的#term("shorthand")是#mark("~", postfix: ":") <grammar-shorthand-space> #code(```typ AB v.s. A~B ```) 连接号(en dash, `U+2013`)的#term("shorthand")由两个连续的#mark("hyphen")组成: #code(```typ 北京--上海路线的列车正在到站。 ```) // 破折号的#term("shorthand")由三个连续的#mark("hyphen")组成(有问题,毋用,请直接使用em dash,`—`): // #code(```typ // 你的生日------四月十八日------每年我总记得。\ // 你的生日——四月十八日——每年我总记得。 // ```) 省略号的#term("shorthand")由三个连续的#mark(".")组成: #code(```typ 真的假的...... ```) // - minusi // -? soft-hyphen 完整的速记符号列表参考#link("https://typst.app/docs/reference/symbols/")[Typst Symbols]。 == 注释 <grammar-inline-comment> Typst的#term("comment")直接采用C语言风格的注释语法,有两种表示方法。 第一种写法是将注释内容放在两个连续的#mark("/")后面,从双斜杠到行尾都属于#term("comment")。 #code(````typ // 这是一行注释 一行文本 // 这也是注释 ````) 与代码片段的情形类似,Typst也提供了另外一种可以跨行的#term("comment"),形如`/*...*/`。<grammar-cross-line-comment> #code(````typ 你没有看见/* 混入其中 */注释 ````) 值得注意的是,Typst会将#term("comment")从源码中剔除后再解释你的文档,因此它们对文档没有影响。 以下两个段落等价: #code(````typ 注释不会 // 这是一行注释 // 注释内的注释还是注释 插入换行 // 这也是注释 注释不会 插入换行 ````) 以下三个段落等价: #code(````typ 注释不会/* 混入其中 */插入空格 注释不会/* 混入其中 */插入空格 注释不会插入空格 ````) == 总结 基于《编写一篇基本文档》前半部分掌握的知识,你应该编写一些非常简单的文档。 == 习题 #let q1 = ````typ 欲穷千里目,/* */更上一层楼。 ```` #exercise[ 使源码至少有两行,第一行包含“欲穷千里目,”,第二行包含“更上一层楼。”,但是输出不换行不空格:#rect(width: 100%, eval(q1.text, mode: "markup")) ][ #q1 ] #exercise[ 输出一个#mark("*", postfix: ",")期望的输出:#rect(width: 100%)[\*] ][ ```typ \* ``` ] #let q1 = ````typ ``` ` ``` ```` #exercise[ 插入代码片段使其包含一个反引号,期望的输出:#rect(width: 100%, eval(q1.text, mode: "markup")) ][ #q1 ] #let q1 = ```typ ``` #let q1 = `````typ ```` ``` ```` ````` #exercise[ 插入代码片段使其包含三个反引号,期望的输出:#rect(width: 100%, eval(q1.text, mode: "markup")) ][ #q1 ] #let q1 = ````typ 你可以在Typst内通过插件 ```typc plugin("typst.wasm")``` 调用Typst编译器。 ```` #exercise[ 插入行内的“typc”代码,期望的输出:#rect(width: 100%, eval(q1.text, mode: "markup")) ][ #q1 ] #let q2 = ```typ 约法五章。 1. 其一。 + 其二。 前两条不算。 3. 其三。 + 其四。 + 其五。 ``` #exercise[ 在有序列表间插入描述,期望的输出:#rect(width: 100%, eval(q2.text, mode: "markup")) ][ #q2 ]
https://github.com/a-dixon/typst-template-ieee
https://raw.githubusercontent.com/a-dixon/typst-template-ieee/main/thesis.typ
typst
#import "template.typ": * #show: ieee.with( title: [Title of paper], abstract: [ This is abstract... ], authors: ( ( name: "<NAME>", organization: [Organisation name], email: "Author email" ), ), bibliography: bibliography("literature.bib"), ) // Uncomment the following lines and add further chapters below #include "./chapters/introduction.typ" // #include "./chapters/some-other-chapter.typ" #include "./chapters/conclusion.typ" // hacky way of doing this, but oh well = Acronyms
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/src/stokes.typ
typst
MIT License
#import "@local/evan:1.0.0":* = Generalized Stokes' theorem == [TEXT] The only two things you need to remember for this section Remember the red arrows in @fig-int-chart-stokes? If you followed my advice in @exer-poster, you probably remember where the red arrows in the picture are now. Now it'll pay off in spades, because there's only two things you need to know about them for this section. #memo(title: [Memorize: Two red arrows gives zero])[ In @fig-int-chart-stokes, if you follow two red arrows consecutively, you get zero. ] #memo(title: [Memorize: Generalized Stokes' Theorem, for 18.02])[ In @fig-int-chart-stokes, take any of the six red arrows #text(rgb("ff0000"))[$ X -> op("del")(X). $] Let $cal(R)$ be a compact region. Then the integral of $X$ over the *boundary* of $cal(R)$ equals the integral of $op("del")(X)$ over $cal(R)$: $ int_(op("boundary")(cal(R))) X = int_(cal(R)) op("del")(X). $ ] Because the chart in @fig-int-chart-stokes is so big, the first item will give $3$ different theorems, while the second item will give $6$ different theorems (one for each red arrow). But you don't need to memorize all $3+6=9$ results. All you have to do is remember the two items above. Then all $9$ results will fall out.
https://github.com/typst-community/valkyrie
https://raw.githubusercontent.com/typst-community/valkyrie/main/tests/types/stroke/test.typ
typst
Other
#import "/src/lib.typ" as z #import "/tests/utility.typ": * #show: show-rule.with(); #let schema = z.stroke() = types/stroke == Input types #let _ = z.parse(stroke(), schema)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/raw-align-02.typ
typst
Other
// Error: 17-20 alignment must be horizontal #set raw(align: top)
https://github.com/berceanu/activity-report
https://raw.githubusercontent.com/berceanu/activity-report/main/ultra-short-activity-report.typ
typst
BSD 3-Clause "New" or "Revised" License
#let mk_header( proiect, contract, ) = { set text(font: "DejaVu Sans", 12pt) show text: strong stack(dir: ltr, [#upper(proiect) \ #upper(contract)] ) v(1fr) } #let mk_title( title, ) = { set text(font: "DejaVu Sans", 14pt) show text: strong align(center, [#upper(title)]) } #let mk_date( month, ) = { set text(font: "DejaVu Sans", 12pt) align(center, [*Period:* #month]) } #let mk_name_position( your_name, your_position, ) = { v(1fr) block[ *Full Name:* #your_name \ *Position within the project:* #your_position ] } #let activities = v(1fr) + [*During this period, the following activities have been carried out.*] + v(1em) #let mk_signatures( department_head, group_leader, sign_date, ) = { v(1fr) grid( columns: (1fr, 1fr, 1fr), rows: (auto, auto, auto), row-gutter: 0.5em, align(left)[*Date:* #sign_date], align(center, upper(strong("Endorse,"))), align(right, upper(strong("Endorse,"))), align(left)[*Signature,*], align(center)[*Head of LGED*], align(right)[*Group Leader*], align(left, move(dy: -0.4em, image("signature.png", height: 1em))), align(center, department_head), align(right, group_leader), ) v(2em) } #let report( proiect: "ELI-NP Project", contract: "Financing Contract no. 1/2016", title: "Short Activity Report", month: none, your_name: "<NAME>", your_position: "CS-III", sign_date: none, department_head: "Ovidiu Teșileanu", group_leader: "<NAME>", body, ) = { set document( title: title, author: your_name, ) set page( paper: "a4", margin: (top: 1.5cm, bottom: 1.5cm, left: 2cm, right: 2cm), ) mk_header(proiect, contract) mk_title(title) mk_date(month) set text( lang: "en", font: "Linux Libertine", size: 12pt, ) set par( justify: true, ) mk_name_position(your_name, your_position) body mk_signatures(department_head, group_leader, sign_date) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/mark-shapes.typ
typst
Apache License 2.0
#import "drawable.typ" #import "path-util.typ" #import "vector.typ" // Calculate triangular tip offset, depending on the strokes // join type. // // The angle is calculated for an isosceles triangle of base style.widh // and height style.length #let calculate-tip-offset(style) = { if style.stroke.join == "round" { return style.stroke.thickness / 2 } if style.length == 0 { return 0 } let angle = calc.atan(style.width / (2 * style.length) / if style.harpoon { 2 } else { 1 } ) * 2 // If the miter length divided by the stroke width exceeds // the stroke miter limit then the miter join is converted to a bevel. // See: https://svgwg.org/svg2-draft/painting.html#LineJoin if style.stroke.join == "miter" { let angle = calc.abs(angle) if angle > 0deg { let miter-limit = 1 / calc.sin(angle / 2) if miter-limit <= style.stroke.miter-limit { return miter-limit * (style.stroke.thickness / 2) } } } // style.stroke.join must be "bevel" return calc.sin(angle/2) * (style.stroke.thickness / 2) } #let _star-shape(n, style, angle-offset: 0deg) = { let radius(angle) = { vector.dist((0,0), (calc.cos(angle) * style.length, calc.sin(angle) * style.width)) / 2 } range(0, n) .map(i => i * 360deg / n + angle-offset) .filter(a => not style.harpoon or (a >= 0deg and a <= 180deg)) .map(a => { let d = vector.scale(vector.rotate-z((1, 0, 0), a), radius(a)) drawable.path(path-util.line-segment(((0,0,0), vector.add((0,0,0), d))), stroke: style.stroke, close: false) }) } // Dictionary of built-in mark styles // // (style) => (drawables:, tip-offset:, distance:) #let marks = ( triangle: (style) => ( drawables: drawable.path( path-util.line-segment( ( (0, 0), (style.length, style.width/2), if style.harpoon { (style.length, 0) } else { (style.length, -style.width/2) } ) ), close: true, fill: style.fill, stroke: style.stroke ), tip-offset: calculate-tip-offset(style), distance: style.length ), stealth: (style) => ( drawables: drawable.path( path-util.line-segment( ( (0, 0), (style.length, style.width/2), (style.length - style.inset, 0), if not style.harpoon { (style.length, -style.width/2) } ).filter(c => c != none) ), stroke: style.stroke, close: true, fill: style.fill ), distance: style.length - style.inset, tip-offset: calculate-tip-offset(style) ), bar: (style) => ( drawables: drawable.path( path-util.line-segment( if style.harpoon { ((0, 0), (0, +style.width/2)) } else { ((0, -style.width/2), (0, +style.width/2)) }), stroke: style.stroke, fill: none, close: false, ), distance: 0, tip-offset: style.stroke.thickness / 2, ), ellipse: (style) => ( drawables: drawable.ellipse( style.length / 2, 0, 0, style.length / 2, style.width / 2, stroke: style.stroke, fill: style.fill), distance: style.length, tip-offset: style.stroke.thickness / 2, ), circle: (style) => { let radius = calc.min(style.length, style.width) / 2 ( drawables: drawable.ellipse( radius, 0, 0, radius, radius, stroke: style.stroke, fill: style.fill), distance: radius * 2, tip-offset: style.stroke.thickness / 2, ) }, bracket: (style) => ( drawables: drawable.path( path-util.line-segment( if style.harpoon { ((style.length - style.inset, style.width/2), (0, style.width/2), (0, 0)) } else { ((style.length - style.inset, -style.width/2), (0, -style.width/2), (0, +style.width/2), (style.length - style.inset, +style.width/2)) }), stroke: style.stroke, fill: none, close: false, ), distance: style.length, inset: style.length + style.stroke.thickness / 2, tip-offset: style.stroke.thickness / 2, ), diamond: (style) => ( drawables: drawable.path( path-util.line-segment( if style.harpoon { ((0,0), (style.length / 2, style.width / 2), (style.length, 0)) } else { ((0,0), (style.length / 2, style.width / 2), (style.length, 0), (style.length / 2, -style.width / 2)) } ), close: true, fill: style.fill, stroke: style.stroke ), tip-offset: calculate-tip-offset(style), base-offset: calculate-tip-offset(style), distance: style.length ), rect: (style) => { let top = if style.harpoon { 0 } else { -style.width / 2 } let width = if style.harpoon { style.width / 2 } else { style.width } (drawables: drawable.path( path-util.line-segment( ((0, top), (0, top + width), (style.length, top + width), (style.length, top)) ), close: true, fill: style.fill, stroke: style.stroke ), tip-offset: calculate-tip-offset(style), distance: style.length )}, hook: (style) => { let rx = calc.min(style.length, style.width / 2) / 2 let length = calc.max(style.length - style.inset, rx) let lower = ( path-util.line-segment(((length, style.width / 2), (rx, style.width / 2))), path-util.cubic-segment( (rx, style.width / 2), (rx, 0), (-rx, style.width / 2), (-rx, 0)), path-util.line-segment(((rx, 0), (style.length, 0)))) let upper = ( path-util.line-segment(((style.length, 0), (rx, 0))), path-util.cubic-segment( (rx, 0), (rx, -style.width / 2), (-rx, 0), (-rx, -style.width / 2)), path-util.line-segment(((rx, -style.width / 2), (length, -style.width / 2)))) (drawables: drawable.path( lower + (if not style.harpoon { upper } else { () }), close: false, fill: none, stroke: style.stroke ), tip-offset: calculate-tip-offset(style), distance: style.length )}, straight: (style) => ( drawables: drawable.path( path-util.line-segment( if style.harpoon { ((style.length, style.width/2), (0, 0),) } else { ((style.length, +style.width/2), (0, 0), (style.length, -style.width/2),) }), close: false, fill: none, stroke: style.stroke ), tip-offset: calculate-tip-offset(style), distance: style.length, inset: style.length ), barbed: (style) => { // Force join to "round" as other joins look bad style.stroke.join = "round" let ctrl-a = (style.length, 0) let ctrl-b = (0, 0) (drawables: drawable.path( (path-util.cubic-segment( (style.length, style.width / 2), (0,0), ctrl-a, ctrl-b),) + if not style.harpoon { (path-util.cubic-segment( (0,0), (style.length, -style.width / 2), ctrl-b, ctrl-a),) } else { () }, close: false, fill: none, stroke: style.stroke), tip-offset: calculate-tip-offset(style), distance: style.length, inset: style.length )}, plus: (style) => ( drawables: _star-shape(4, style), tip-offset: style.length / 2, distance: style.length / 2, ), x: (style) => ( drawables: _star-shape(4, style, angle-offset: 45deg), tip-offset: style.length / 2, distance: style.length / 2, inset: style.length / 2 ), star: (style) => ( drawables: _star-shape(5, style), tip-offset: style.length / 2, distance: style.length / 2, ) ) #let names = marks.keys() // Mark mnemonics #let mnemonics = ( ">": ("triangle", false), "<": ("triangle", true), "<>": ("diamond", false), "[]": ("rect", false), "]": ("bracket", false), "[": ("bracket", true), "|": ("bar", false), "o": ("circle", false), "+": ("plus", false), "x": ("x", false), "*": ("star", false), ) // Get a mark shape + reverse tuple for a mark name #let get-mark(ctx, symbol) = { // TODO: Support user supplied marks by looking them up in the ctx style let reverse = false if not symbol in marks { (symbol, reverse) = mnemonics.at(symbol) } return (marks.at(symbol), reverse) }
https://github.com/0xPARC/0xparc-intro-book
https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/summer-notes-evan/src/0813-math-seminar.typ
typst
#import "@local/evan:1.0.0":* = Sum-check (<NAME>) This follows the notes at #url("https://notes.0xparc.org/notes/sum-check/"), so I won't retype them here.
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S5/PST/docs/4-ProbabilitéConditionnelle/probabilite-conditionnelle.typ
typst
#import "/_settings/typst/template-note.typ": conf #show: doc => conf( title: [ Probabilité conditionnelle ], lesson: "PST", chapter: "4 - Probabilité conditionnelle", definition: "Definition", col: 1, doc, ) = Probabilité conditionnelle == Concept La probabilité conditionnelle nous permet de calculer la probabilité d'un événement en fonction d'une condition. L'opération permettant de calculer la probabilité conditionnelle est la suivante: $ A = "probabilité que l'évenement A se passe" \ B = "événement qui s'est réalisé" $ Nous cherchons donc la chance que l'évenement A se passe en sachant que l'événement B s'est réalisé: $ P(A | B) $ La formule de base permettant de calculer cette probabilité est: $ P(A bar B) = frac(P(A sect B), P(B)), " "P(B) eq.not 0 $ === Remarques $ P(B bar B) = 1 $ si $A$ est inclus dans $B$, alors $A sect B = A$ et donc $ P(A bar B) = frac(P(A), P(B)) $ == Théorème de multiplication En utilisant l'inverse de la formule présentée au point 2 nous pouvons retrouver $P(A sect B)$, pour cela nous aurons la formule suivante: $ P(A sect B) =& P(A bar B) * P(B) \ =& P(B bar A) * P(A) $ == Théorème des probabilités totales Soient $A$ et $B$ deux événements quelconques. Comme $B$ et $overline(B)$ forment une partition de $Omega$, on aura selon le théorème des probabilités totales, $ P(A) &= P(A bar B) * P(B) + P(A bar overline(B)) * P(overline(B)) \ &= P(A bar B) * P(B) + P(A bar overline(B)) * P(1 - P(B)) $ = Théorème de Bayes Le théorème de Bayes qui fait appel aux théorèmes de multiplication et de probabilités totales est très important. Par exemple, il donna naissance à une autre approche de la statistique. Nous présenterons d'abord la version simple du théorème puis sa version composée. == Version simplifiée Supposons que $A$ et $B$ soient deux événements d'un ensemble fondamental $Omega$, avec $P(B) eq.not 0$. Alors, $ P(A bar B) = frac(P(A sect B), P(B)) = frac(P(B bar A) * P(A), P(B)) $ == Version composée Soient une partition $H_1, H_2, ..., H_k$ et un événement $B$ d'un ensemble fondamental $Omega$, avec $P(B) eq.not 0$. Pour tout indice $1 eq.lt j eq.lt k$, on aura, $ P(H_j bar B) &= frac(P(H_j sect B), P(B)) \ &= frac(P(B bar H_j) * P(H_j), P(B bar H_1) * P(H_1) + ... + P(B bar H_k) * P(H_k)) $ == Filtre bayesien anti-spam $ p_i : "probabilité qu'un mot choisi au hasard dans un message électronique " \ " est le mot " i " en sachat que le mot est un spam." \ q_i : "probabilité qu'un mot choisi au hasard dans un message électronique " \ " est le mot " i " en sachant que le message n'est pas un spam" $ === Exemple $ M_i : "le mot choisi au hasard dans le message électronique est le mot" i; \ S : "le message électronique est un spam" $ Ainsi, $ p_i = P(M_i bar S) " et " q_i = P(M_i bar overline(S)) $ Pour illustrer le fonctionnement du filtre bayesien, supposons que la proportion de messages spam d'une certaine compagnie vaut $0.9$ et que pour le mot "hypothèque" noté $1, p_1 = 0.05 " et " q_1 = 0.001$. Pour ce mot, on a alors $ p_1 = P(M_1 bar S) = 0.05 " et " q_1 = P(M bar overline(S)) = 0.001 $ Un nouveau message électronique vient d'arriver et le mot "hypothèque" y apparaît exactement une fois. En appliquant le théroème de Bayes, la probabilité que le message électronique soit un spam est $ P(S bar M_1) &= frac(P(M_1 bar S) * P(S), P(M_1 bar S) * P(S) + P(M_1 bar overline(S)) * P(overline(S))) = 0.998 $ #colbreak() === Formules utiles Dans le cas ou les événements $M_1$ et $M_2$ sont dit *indépendants* nous aurons, $ P(S bar M_1 sect M_2) &= frac(P(M_1 sect M_2 bar S) * P(S), P(M_1 sect M_2 bar S) * P(S) + P(M_1 sect M_2 bar overline(S)) * P(overline(S))) \ \ &= frac(P(M_1 bar S) * P(M_2 bar S) * P(S), P(M_1 bar S) * P(M_2 bar S) * P(S) + P(M_1 bar overline(S)) * P(M_2 bar overline(S)) * P(overline(S))) $ = Indépendance L'événement $A$ est *indépendant* de l'événement B si le fait de savoir que $B$ s'est déroulé n'influence pas la probabilité de $A$. Nous aurons donc $ P(A bar B) = P(A) $ Or, par définition d'une probabilité conditionnelle, $ P(A bar B) = frac(P(A sect B), P(B)) $ Ainsi, on obtient $ P(A) = frac(P(A sect B),P(B)) $ On peut donc dire que $A$ est indépendant de $B$ si $ P(A sect B) = P(A) * P(B) $ *Deux événements sont dépendants s'ils ne sont pas indépendants.*
https://github.com/jiang131072/casual-szu-report
https://raw.githubusercontent.com/jiang131072/casual-szu-report/main/lib.typ
typst
MIT License
#let template( body, course-title: auto, experiment-title: auto, faculty: auto, major: auto, instructor: auto, reporter: auto, student-id: auto, class: auto, experiment-date: auto, submission-date: datetime.today(), features: (), ) = { // let font-family = ("Noto Serif", "Noto Serif CJK SC") let font-family = ("New Computer Modern", "Noto Serif CJK SC") // BUG biblioraphy file can only used relative path to // lib.typ if declared in lib.typ. While Typst do not // support absolute path. If you manually add // biblioraphy in template file, it will be wrapped in // table.cell (unless we add an extra test for // biblioraphy func, but that is very hacky, and will // birng many uncertaities, ex. biblioraphy not in the // end). No good idea. // Workaround: copy lib.typ to workdir. let bibliography-file = none let citation-style = "gb-7714-2015-numeric" for (key, value) in features { if key == "FontFamily" { font-family = value } else if key == "Bibliography" { bibliography-file = value } else if key == "CitationStyle" { citation-style = value } else if key == "CourseID" { // TODO Course ID box on first page assert(false, "Not yet implemented") } else { assert(false, "Unknown Feature") } } // BUG Legacy Microsoft font for Simplified Chinese (as // list below) are lack of bold weitht (bold and font // weight do not work), so we try to use @preview/cuti // to fake bold. But cuti's support is very simple, // properties like tracking do not work, and it doesn't // recogenize `semibold` or specified weight. So we // can't use it. No good idea. // Workaround: use Noto Serif CJK SC. // let version-cuti = "0.2.1" // let font-family = ("Times New Roman", "SimSun") // for font in font-family { // if font in ("KaiTi", "SimHei", "SimSun") { // // Legacy Microsoft font for Simplified Chinese // // are lack of bold weight, so we use fake bold // import "@preview/cuti:" + version-cuti: show-cn-fakebold // show: show-cn-fakebold // } // } set document( title: experiment-title, author: reporter.text, ) set page(footer: context { set align(center) set text(8pt) counter(page).display( "1 / 1", both: true, ) }) set text( font: font-family, lang: "zh", region: "cn", size: 10.5pt, ) // Workaround for https://github.com/typst/typst/issues/311 // By https://github.com/Myriad-Dreamin set par(justify: true, first-line-indent: 2em) let sel-fake = selector(heading).or(figure).or(math.equation.where(block: true)).or(pad).or(list).or(enum) show sel-fake: it => { it let b = par(box()) b let t = measure(b * 2) v(-t.height) } let st-indent = selector(raw.where(block: true)) show st-indent: it => { pad(it, left: 2em) } show enum: set enum(indent: 1em) show list: set list(indent: 1em) // Heading show heading.where(depth: 1): set text(size: 12pt) show heading.where(depth: 2): set text(size: 11.5pt) show heading.where(depth: 3): set text(size: 11pt) // Enum show enum: set enum(numbering: "1)a)i)") /* Header Line */ line(length: 100%) /* Title */ { set align(center) set text( weight: "semibold", size: 20pt, tracking: 0.8em, ) pad([深圳大学实验报告], y: 2em) } /* Info Grid */ { set align(center) set text( weight: "semibold", size: 14pt, ) // Underline Box let u(it) = { v(-5pt) // TODO use mearure to get precise value rect( it, width: 100%, stroke: (bottom: 1pt), ) } grid( columns: (4em, 1em, 22em), row-gutter: 3.5em, "课程名称", ":", u(course-title), "实验名称", ":", u(experiment-title), "学  院", ":", u(faculty), "专  业", ":", u(major), "指导老师", ":", u(instructor), ) pad( grid( columns: (3em, 1em, 4.5em, 2em, 1em, 7em, 2em, 1em, 5.5em), row-gutter: 3.5em, "报告人", ":", u(reporter), "学号", ":", u(student-id), "班级", ":", u(class), ), y: 2em, ) // TODO use mearure to get precise value let fstr = "[year]年[month]月[day]日" grid( columns: (4em, 1em, 22em), row-gutter: 3.5em, "实验日期", ":", u(experiment-date.display(fstr)), "提交日期", ":", u(submission-date.display(fstr)), ) } /* Footer Line */ v(3.5em) { set align(center) set text(weight: "semibold", size: 12pt) [教育部制] } pagebreak(weak: true) /* Body */ let cells = () let s = () for it in body.children { let is-h1 = it.func() == heading and it.depth == 1 if s.len() == 0 { if is-h1 { s = (it,) } } else { if is-h1 { cells.push(s.sum()) s = (it,) } else { s.push(it) } } } cells.push(s.sum()) table( columns: (100%), ..cells ) /* Summary */ pagebreak(weak: true) { set par(first-line-indent: 0em) table( columns: (100%), [ 指导教师批阅意见: #v(10em) 成绩评定: #v(5em) #h(24em) 指导教师签字: #h(24em) #h(4em)年#h(2em)月#h(2em)日 ], [ 备注: #v(7em) ] ) [ 注: + 报告内的项目或内容设置,可根据实际情况加以调整和补充。 + 教师批改学生实验报告时间应在学生提交实验报告时间后10日内。 ] } /* Bibliography */ if bibliography-file != none { bibliography(bibliography-file, style: citation-style) } }
https://github.com/ymgyt/techbook
https://raw.githubusercontent.com/ymgyt/techbook/master/cloud/aws/cdk/cdk.md
markdown
# CDK ## Install ``` npm install -g aws-cdk ``` ## Bootstrapping ```console cdk bootstrap aws://ACCOUNT-NUMBER/REGION ``` * lambdaやdocker image等、置いておくためにaccount/region毎に一度だけこの操作が必要 ## Init ```console cdk init app --language typescript ``` ## List stacks ```console cdk ls ``` ## Synth ```consle cdk synth # stackを指定することもできる cdk synth stack1 ``` * cdk appをCloudFormationに変換する * `cdk.out` directoryに結果が保持される ## Deploy ```console cdk deploy ``` ## Diff ```console cdk diff ``` * deploy後にcodeを変更したあと差分をみれる ## Destroy ```console cdk destroy ``` * CloudFormation Stackを削除する ## Runtime context ### `cdk.json`と`cdk.context.json` ## Deploy対象のAWS Account ```typescript new MyDevStack(app, 'dev', { env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }}); ``` * 環境変数 `CDK_DEFAULT_{ACCOUNT,REGION}`を利用するとcdk synth時に`--profile`で指定したaccountを対象にできる * accountをcodeにhard codeするか実行時に解決できるようにしておくかはポリシー次第 * `AWS_PROFILE`で指定があるとそこから対象環境を判定してくれる ```sh cdk diff --profile foo ``` のようにcdk実行時にprofileを指定できる
https://github.com/angelcerveraroldan/notes
https://raw.githubusercontent.com/angelcerveraroldan/notes/main/diff_geo/diff_geo.typ
typst
#import "../preamble.typ" : * #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #let abstract = align(center, "TODO") #show: project.with( title: "Diff Geometry", subtitle: "", topright: "Differential Geometry Notes", abstract: abstract, quote: "", ) #let chapters = ( "intro", ) #pagebreak() #for chapter in chapters { include("./notes/" + chapter + ".typ") }
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/notizen/algorithmen/mts.typ
typst
#import "/config.typ": theme #import "@preview/cetz:0.2.2" #set block(spacing: 4pt) #show table: set text(size: 9pt, font: "Noto Sans Mono") #let nums = (-13, 25, 34, 12, -3, 7, -87, 28, -77, 11) #cetz.canvas(length: 10%, { import cetz.draw: * set-style(content: (padding: (bottom: 4pt))) set-style(mark: (end: ">")) circle((), radius: 0) line((1.5, .8), (1.5, 0), name: "i") line((5.5, .8), (5.5, 0), name: "j") content("i.start", anchor: "south")[$i=1$] content("j.start", anchor: "south")[$j=5$] }) #table( columns: (1fr,) * 10, align: center, fill: (x, y) => if 1 <= x and x <= 5 {theme.primary_light}, ..nums.map(i => [#i]) ) #cetz.canvas(length: 10%, { import cetz.draw: * circle((), radius: 0) cetz.decorations.brace((6, 0), (1, 0), name: "brace") content("brace.content", anchor: "north")[$= 75$] })
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/VerbaliInterni/VerbaleInterno_240215/meta.typ
typst
MIT License
#let data_incontro = "15-02-2024" #let inizio_incontro = "14:00" #let fine_incontro = "15:30" #let luogo_incontro = "Discord"
https://github.com/tzx/NNJR
https://raw.githubusercontent.com/tzx/NNJR/main/README.md
markdown
MIT License
# NNJR NNJR: **N**NJR is **N**ot [**J**ake's **R**esume](https://github.com/jakegut/resume). However, it is similar and is written in `Typst`! ![example.png](./example.png) ## Usage There are two `.typ` files that you can choose to compile: 1. `resume_yaml.typ` allows you to configure just an `yaml` file for your resume. See `example.yml` for an example. 2. `resume.typ` allows you to have finer control. An example of possible behavior is to have some words bold for your bullet points (I can probably add this to `yaml` by doing something with `eval`, but that's another day) ### [Typst.app](https://typst.app) Upload all `*.typ` and `*.yaml` files to your Typst project. Change what you want and voila! Shared project demo [here](https://typst.app/project/rdCXm00mYQiDPpLtSCK4xs) ### Typst CLI ```sh # Replace resume.typ with resume_yaml.typ if desired # Compile to resume.pdf typst compile resume.typ # Compile to other path and name typst compile resume.typ your/path/here.pdf # Watch typst watch resume.pdf ```
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/.github/ISSUE_TEMPLATE/bug_report.md
markdown
Apache License 2.0
--- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **Package/Software version:** VSCode version(Help -> About): ```plain Version: 1.81.1 Commit: 6c3e3dba23e8fadc360aed75ce363ba185c49794 Date: 2023-08-09T22:18:39.991Z Electron: 22.3.18 ElectronBuildId: 22689846 Chromium: 108.0.5359.215 Node.js: 16.17.1 V8: 10.8.168.25-electron.0 OS: Linux x64 6.4.12-x64v4-xanmod1 ``` tinymist extension version: `v0.11.0`. Get it by `tinymist --version` in terminal. ```plain tinymist Build Timestamp: 2024-03-22T02:18:18.207134800Z Build Git Describe: v0.11.1-rc2-5-gf0a96cb-dirty Commit SHA: f0a9... Commit Date: None Commit Branch: None Cargo Target Triple: x86_64-pc-windows-msvc Typst Version: 0.11.0 ``` **Logs:** tinymist server log(Output Panel -> tinymist): ```plain ``` tinymist client log(Help -> Toggle Developer Tools -> Console): ```plain ``` **Additional context** Add any other context about the problem here.
https://github.com/SkymanOne/ecs-typst-template
https://raw.githubusercontent.com/SkymanOne/ecs-typst-template/main/template.typ
typst
MIT License
#import "ecsproject.typ": * // Use everything together #show: doc => use_project( title: "My project", author: ( name: "<NAME>", email: none ), supervisor: ( name: "<NAME>", email: none ), examiner: ( name: "<NAME>", email: none ), date: "January 19, 2024", program: "BSc Computer Science", department: "Electronics and Computer Science", faculty: "Faculty of Engineering and Physical Sciences", university: "University of Southampton", is_progress_report: false, originality_statements: ( acknowledged: "I have acknowledged all sources, and identified any content taken from elsewhere.", resources: "I have not used any resources produced by anyone else.", foreign: "I did all the work myself, or with my allocated group, and have not helped anyone else", material: "The material in the report is genuine, and I have included all my data/code/designs.", reuse: "I have not submitted any part of this work for another assessment.", participants: "My work did not involve human participants, their cells or data, or animals." ), abstract_text: lorem(50), acknowledgments_text: lorem(50), doc ) = Intro #lorem(540) This is me quoting someone @algorand #pagebreak() #bibliography("ECS.bib")
https://github.com/3w36zj6/typst-template
https://raw.githubusercontent.com/3w36zj6/typst-template/main/templates/article.typ
typst
#let font-sans-serif = ("<NAME> Gothic") #let font-serif = ("New Computer Modern", "<NAME>") #let font-monospace = ("HackGen Console NF") #let article( title: "Untitled", subtitle: none, author: none, date: none, paginate: true, bib: none, body, ) = { // メタデータの設定 set document(title: title) // 本文のフォントの設定 set text(font: font-serif, lang: "ja", size: 11pt, weight: "regular") // コードブロックの設定 show raw: set text(font: font-monospace) // ページの設定 set page( paper: "a4", margin: (x: 2.5cm, top: 2.8cm, bottom: 2.65cm), footer: if (paginate) { [ #set align(center) #set text(12pt) #counter(page).display("1") ] } else { none }, ) // 数式の設定 set math.equation(numbering: "(1)") show math.equation: set block(spacing: 0.65em) // 表の設定 show table.cell.where(y: 0): strong set table(stroke: (x, y) => ( x: 0pt, top: if y == 0 { 1pt } else if y == 1 { 0.5pt } else { 0pt }, bottom: 1pt, )) show figure.where(kind: table): set figure.caption(position: top) // 箇条書きの設定 set enum(indent: 1.5em) set list(indent: 1.5em) // 見出しの設定 set heading(numbering: (..nums) => { let level = nums.pos().len() let text-size = if level == 1 { 16pt } else if level == 2 { 13pt } else { 11pt } // e.g. "1.1.1" text(font: font-sans-serif, size: text-size, nums.pos().map(str).join(".")) h(1em, weak: true) }) show heading: set text(font: font-sans-serif, weight: "medium") show heading: it => { pad( top: if (it.level in (1, 2)) { 0.4em } else { 0em }, bottom: if (it.level in (1, 2)) { 0.3em } else { 0em }, left: 0em, // NOTE: 参考文献の見出しの位置がずれるのを防ぐため )[ #it ] } // インデントの設定 // https://github.com/typst/typst/issues/311 show heading: it => { it par(text(size: 0.5em, "")) } // タイトルの表示 v(1.68cm) align(center, text(font: font-serif, size: 19pt, title)) // サブタイトルの表示 if subtitle != none { v(-0.42cm) align(center, text(font: font-serif, size: 13pt, subtitle)) v(0.2cm) } // 執筆者の表示 if author != none { v(0.15cm) align(center, text(font: font-serif, size: 14pt, author)) } // 日付の表示 if date != none { v(0.15cm) align(center, text(font: font-serif, size: 14pt, date)) } // 本文の設定 set par(justify: true, first-line-indent: 1em, leading: 1em) // 本文の表示 v(1.9cm, weak: true) body // 参考文献の表示 if bib != none { set text(lang: "en") bib } }
https://github.com/IANYEYZ/epigraph
https://raw.githubusercontent.com/IANYEYZ/epigraph/main/README.md
markdown
MIT License
# epigraph epigraph is, as it name suggests, a typst package for creating epigraph. The main feature includes: - Custom position of epigraph - Custom text style for both quote and source - Custom width of epigraph ## What is an epigraph ? An epigraph is some quotes at the beginning of chapter. For example, this is an epigraph: ## Usage ### Getting started The simplest usage of epigraph is: ```typst #epigraph(source: "Ockham")[ Entities should not be multiplied unnecessarily ] ``` resulting in: ### A longer epigraph If you want a longer epigraph, set the `width` option. For example: ```typst #epigraph(source: "A Wise Man", width: 70%)[ #lorem(15) ] ``` resulting in: ### Change position Maybe you want to put epigraph on the left of the page, set the `position` option. For example: ```typst #epigraph(source: "A Wise Man", position: ( align: alignment.left, dx: 0pt, dy: 15pt ))[#lorem(15)] ``` resulting in:
https://github.com/yangwenbo99/typst-lasaveur
https://raw.githubusercontent.com/yangwenbo99/typst-lasaveur/master/README.md
markdown
# Typst-lasaveur This is a Typst package for speedy mathematical input, inspired by [vim-latex](https://github.com/vim-latex/vim-latex). This project is named after my Vim plugin [vimtex-lasaveur](https://github.com/yangwenbo99/vimtex-lasaveur), which ports the operations in vim-latex to [vimtex](https://github.com/lervag/vimtex). ## Usages in Typst Either use the file released in "Releases" or import using the following command: ```typst #import "@preview/lasaveur:0.1.3": * ``` This script generates a Typst library that defines shorthand commands for various mathematical symbols and functions. Here's an overview of what it provides and how a user can use it: 1. Mathematical Functions: - Usage: `f<key>(argument)` - Examples: `fh(x)` for hat, `ft(x)` for tilde, `f2(x)` for square root 2. Font Styles: - Usage: `f<key>(argument)` - Examples: `fb(x)` for bold, `fbb(x)` for blackboard bold, `fca(x)` for calligraphic 3. Greek Letters: - Usage: `k<key>` - Examples: `ka` for α (alpha), `kb` for β (beta), `kG` for Γ (capital Gamma) 4. Common Mathematical Symbols: - Usage: `g<key>` - Examples: `g8` for ∞ (infinity), `gU` for ∪ (union), `gI` for ∩ (intersection) 5. LaTeX-compatible Symbols: - Usage: Direct LaTeX command names - Examples: `partial` for ∂, `infty` for ∞, `cdot` for ⋅ 6. Arrows: - Usage: `ar.<key>` - Examples: `ar.l` for ←, `ar.r` for →, `ar.lr` for ↔ Users can employ these shorthands in their Typst documents to quickly input mathematical symbols and functions. The exact prefix for each category (like `f` for functions or `k` for Greek letters) can be customized using command-line arguments when running the script. For instance, in a Typst document, after importing the generated library, a user could write: ```typst $fh(x) + ka + g8 + ar.r$ ``` This would produce: x̂ + α + ∞ + → The script provides a wide range of symbols covering most common mathematical notations, making it easier and faster to type complex mathematical expressions in Typst -- especially for users migrating from vim-latex. ## Accompanying Vim Syntax File The syntax file provides more advanced and correct concealing for both Typst's built-in math syntax and the lasaveur shorthands. Download the syntax file from the "Releases" section and place it in your `~/.vim/after/syntax/` directory. The `syntax.vim` file in the repo is supposed to be used by the generation script and it _will not work_ if directly sourced in Vim.
https://github.com/roife/resume
https://raw.githubusercontent.com/roife/resume/master/chicv.typ
typst
MIT License
#import "fontawesome.typ": * #let chiline() = { v(-8pt); line(length: 100%, stroke: gray); v(-8pt) } #let iconlink( uri, text: "", icon: link-icon ) = { if text != "" { link(uri)[#fa[#icon] #text] } else { link(uri)[#fa[#icon]] } } #let ghrepo( repo, add_link: true, icon: true ) = { if add_link { if icon { iconlink("https://github.com/" + repo, text: repo, icon: github) } else { link("https://github.com/" + repo)[#repo] } } else { [#fa[#icon] #repo] } } #let cventry( tl: lorem(2), tl_comments: "", tr: "", bl: "", br: "", content ) = { block( inset: (left: 0pt), text(weight: "bold")[#tl] + tl_comments + h(1fr) + tr + linebreak() + if bl != "" or br != "" { bl + h(1fr) + br + linebreak() } + content ) } #let grid_par( content ) = { par(leading: 6pt)[#content] } // submit, post #let redact(alter: none, mark: false, color: black, body) = { let level = sys.inputs.at("level", default: none); if level == "submit" { body } else if level == "post" { if alter == none and mark { box(hide(body), fill: color) } else if alter == none and not mark { box(fill: color)[(missing)] } else { alter } } else { box(fill: color)[(missing)] } } #let chicv(body) = { let fonts = ( "Palatino", "Source Han Serif SC", "Source Han Serif", ) show heading.where( level: 1 ): set text( size: 23pt, font: fonts, weight: "light", ) show heading.where( level: 2 ): it => text( size: 12pt, font: fonts, weight: "bold", block( chiline() + it, ) ) set list(indent: 2pt) show link: it => underline(offset: 1.8pt, it) set page(margin: (x: 0.85cm, top: 1cm, bottom: 0.5cm),) set par(justify: true) set text(font: fonts, size: 10.2pt) set block(spacing: 0.9em) body }
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/216.%20greatwork.html.typ
typst
greatwork.html How to Do Great Work July 2023If you collected lists of techniques for doing great work in a lot of different fields, what would the intersection look like? I decided to find out by making it.Partly my goal was to create a guide that could be used by someone working in any field. But I was also curious about the shape of the intersection. And one thing this exercise shows is that it does have a definite shape; it's not just a point labelled "work hard."The following recipe assumes you're very ambitious. The first step is to decide what to work on. The work you choose needs to have three qualities: it has to be something you have a natural aptitude for, that you have a deep interest in, and that offers scope to do great work.In practice you don't have to worry much about the third criterion. Ambitious people are if anything already too conservative about it. So all you need to do is find something you have an aptitude for and great interest in. [1]That sounds straightforward, but it's often quite difficult. When you're young you don't know what you're good at or what different kinds of work are like. Some kinds of work you end up doing may not even exist yet. So while some people know what they want to do at 14, most have to figure it out.The way to figure out what to work on is by working. If you're not sure what to work on, guess. But pick something and get going. You'll probably guess wrong some of the time, but that's fine. It's good to know about multiple things; some of the biggest discoveries come from noticing connections between different fields.Develop a habit of working on your own projects. Don't let "work" mean something other people tell you to do. If you do manage to do great work one day, it will probably be on a project of your own. It may be within some bigger project, but you'll be driving your part of it.What should your projects be? Whatever seems to you excitingly ambitious. As you grow older and your taste in projects evolves, exciting and important will converge. At 7 it may seem excitingly ambitious to build huge things out of Lego, then at 14 to teach yourself calculus, till at 21 you're starting to explore unanswered questions in physics. But always preserve excitingness.There's a kind of excited curiosity that's both the engine and the rudder of great work. It will not only drive you, but if you let it have its way, will also show you what to work on.What are you excessively curious about — curious to a degree that would bore most other people? That's what you're looking for.Once you've found something you're excessively interested in, the next step is to learn enough about it to get you to one of the frontiers of knowledge. Knowledge expands fractally, and from a distance its edges look smooth, but once you learn enough to get close to one, they turn out to be full of gaps.The next step is to notice them. This takes some skill, because your brain wants to ignore such gaps in order to make a simpler model of the world. Many discoveries have come from asking questions about things that everyone else took for granted. [2]If the answers seem strange, so much the better. Great work often has a tincture of strangeness. You see this from painting to math. It would be affected to try to manufacture it, but if it appears, embrace it.Boldly chase outlier ideas, even if other people aren't interested in them — in fact, especially if they aren't. If you're excited about some possibility that everyone else ignores, and you have enough expertise to say precisely what they're all overlooking, that's as good a bet as you'll find. [3]Four steps: choose a field, learn enough to get to the frontier, notice gaps, explore promising ones. This is how practically everyone who's done great work has done it, from painters to physicists.Steps two and four will require hard work. It may not be possible to prove that you have to work hard to do great things, but the empirical evidence is on the scale of the evidence for mortality. That's why it's essential to work on something you're deeply interested in. Interest will drive you to work harder than mere diligence ever could.The three most powerful motives are curiosity, delight, and the desire to do something impressive. Sometimes they converge, and that combination is the most powerful of all.The big prize is to discover a new fractal bud. You notice a crack in the surface of knowledge, pry it open, and there's a whole world inside.Let's talk a little more about the complicated business of figuring out what to work on. The main reason it's hard is that you can't tell what most kinds of work are like except by doing them. Which means the four steps overlap: you may have to work at something for years before you know how much you like it or how good you are at it. And in the meantime you're not doing, and thus not learning about, most other kinds of work. So in the worst case you choose late based on very incomplete information. [4]The nature of ambition exacerbates this problem. Ambition comes in two forms, one that precedes interest in the subject and one that grows out of it. Most people who do great work have a mix, and the more you have of the former, the harder it will be to decide what to do.The educational systems in most countries pretend it's easy. They expect you to commit to a field long before you could know what it's really like. And as a result an ambitious person on an optimal trajectory will often read to the system as an instance of breakage.It would be better if they at least admitted it — if they admitted that the system not only can't do much to help you figure out what to work on, but is designed on the assumption that you'll somehow magically guess as a teenager. They don't tell you, but I will: when it comes to figuring out what to work on, you're on your own. Some people get lucky and do guess correctly, but the rest will find themselves scrambling diagonally across tracks laid down on the assumption that everyone does.What should you do if you're young and ambitious but don't know what to work on? What you should not do is drift along passively, assuming the problem will solve itself. You need to take action. But there is no systematic procedure you can follow. When you read biographies of people who've done great work, it's remarkable how much luck is involved. They discover what to work on as a result of a chance meeting, or by reading a book they happen to pick up. So you need to make yourself a big target for luck, and the way to do that is to be curious. Try lots of things, meet lots of people, read lots of books, ask lots of questions. [5]When in doubt, optimize for interestingness. Fields change as you learn more about them. What mathematicians do, for example, is very different from what you do in high school math classes. So you need to give different types of work a chance to show you what they're like. But a field should become increasingly interesting as you learn more about it. If it doesn't, it's probably not for you.Don't worry if you find you're interested in different things than other people. The stranger your tastes in interestingness, the better. Strange tastes are often strong ones, and a strong taste for work means you'll be productive. And you're more likely to find new things if you're looking where few have looked before.One sign that you're suited for some kind of work is when you like even the parts that other people find tedious or frightening.But fields aren't people; you don't owe them any loyalty. If in the course of working on one thing you discover another that's more exciting, don't be afraid to switch.If you're making something for people, make sure it's something they actually want. The best way to do this is to make something you yourself want. Write the story you want to read; build the tool you want to use. Since your friends probably have similar interests, this will also get you your initial audience.This should follow from the excitingness rule. Obviously the most exciting story to write will be the one you want to read. The reason I mention this case explicitly is that so many people get it wrong. Instead of making what they want, they try to make what some imaginary, more sophisticated audience wants. And once you go down that route, you're lost. [6]There are a lot of forces that will lead you astray when you're trying to figure out what to work on. Pretentiousness, fashion, fear, money, politics, other people's wishes, eminent frauds. But if you stick to what you find genuinely interesting, you'll be proof against all of them. If you're interested, you're not astray. Following your interests may sound like a rather passive strategy, but in practice it usually means following them past all sorts of obstacles. You usually have to risk rejection and failure. So it does take a good deal of boldness.But while you need boldness, you don't usually need much planning. In most cases the recipe for doing great work is simply: work hard on excitingly ambitious projects, and something good will come of it. Instead of making a plan and then executing it, you just try to preserve certain invariants.The trouble with planning is that it only works for achievements you can describe in advance. You can win a gold medal or get rich by deciding to as a child and then tenaciously pursuing that goal, but you can't discover natural selection that way.I think for most people who want to do great work, the right strategy is not to plan too much. At each stage do whatever seems most interesting and gives you the best options for the future. I call this approach "staying upwind." This is how most people who've done great work seem to have done it. Even when you've found something exciting to work on, working on it is not always straightforward. There will be times when some new idea makes you leap out of bed in the morning and get straight to work. But there will also be plenty of times when things aren't like that.You don't just put out your sail and get blown forward by inspiration. There are headwinds and currents and hidden shoals. So there's a technique to working, just as there is to sailing.For example, while you must work hard, it's possible to work too hard, and if you do that you'll find you get diminishing returns: fatigue will make you stupid, and eventually even damage your health. The point at which work yields diminishing returns depends on the type. Some of the hardest types you might only be able to do for four or five hours a day.Ideally those hours will be contiguous. To the extent you can, try to arrange your life so you have big blocks of time to work in. You'll shy away from hard tasks if you know you might be interrupted.It will probably be harder to start working than to keep working. You'll often have to trick yourself to get over that initial threshold. Don't worry about this; it's the nature of work, not a flaw in your character. Work has a sort of activation energy, both per day and per project. And since this threshold is fake in the sense that it's higher than the energy required to keep going, it's ok to tell yourself a lie of corresponding magnitude to get over it.It's usually a mistake to lie to yourself if you want to do great work, but this is one of the rare cases where it isn't. When I'm reluctant to start work in the morning, I often trick myself by saying "I'll just read over what I've got so far." Five minutes later I've found something that seems mistaken or incomplete, and I'm off.Similar techniques work for starting new projects. It's ok to lie to yourself about how much work a project will entail, for example. Lots of great things began with someone saying "How hard could it be?"This is one case where the young have an advantage. They're more optimistic, and even though one of the sources of their optimism is ignorance, in this case ignorance can sometimes beat knowledge.Try to finish what you start, though, even if it turns out to be more work than you expected. Finishing things is not just an exercise in tidiness or self-discipline. In many projects a lot of the best work happens in what was meant to be the final stage.Another permissible lie is to exaggerate the importance of what you're working on, at least in your own mind. If that helps you discover something new, it may turn out not to have been a lie after all. [7] Since there are two senses of starting work — per day and per project — there are also two forms of procrastination. Per-project procrastination is far the more dangerous. You put off starting that ambitious project from year to year because the time isn't quite right. When you're procrastinating in units of years, you can get a lot not done. [8]One reason per-project procrastination is so dangerous is that it usually camouflages itself as work. You're not just sitting around doing nothing; you're working industriously on something else. So per-project procrastination doesn't set off the alarms that per-day procrastination does. You're too busy to notice it.The way to beat it is to stop occasionally and ask yourself: Am I working on what I most want to work on? When you're young it's ok if the answer is sometimes no, but this gets increasingly dangerous as you get older. [9] Great work usually entails spending what would seem to most people an unreasonable amount of time on a problem. You can't think of this time as a cost, or it will seem too high. You have to find the work sufficiently engaging as it's happening.There may be some jobs where you have to work diligently for years at things you hate before you get to the good part, but this is not how great work happens. Great work happens by focusing consistently on something you're genuinely interested in. When you pause to take stock, you're surprised how far you've come.The reason we're surprised is that we underestimate the cumulative effect of work. Writing a page a day doesn't sound like much, but if you do it every day you'll write a book a year. That's the key: consistency. People who do great things don't get a lot done every day. They get something done, rather than nothing.If you do work that compounds, you'll get exponential growth. Most people who do this do it unconsciously, but it's worth stopping to think about. Learning, for example, is an instance of this phenomenon: the more you learn about something, the easier it is to learn more. Growing an audience is another: the more fans you have, the more new fans they'll bring you.The trouble with exponential growth is that the curve feels flat in the beginning. It isn't; it's still a wonderful exponential curve. But we can't grasp that intuitively, so we underrate exponential growth in its early stages.Something that grows exponentially can become so valuable that it's worth making an extraordinary effort to get it started. But since we underrate exponential growth early on, this too is mostly done unconsciously: people push through the initial, unrewarding phase of learning something new because they know from experience that learning new things always takes an initial push, or they grow their audience one fan at a time because they have nothing better to do. If people consciously realized they could invest in exponential growth, many more would do it. Work doesn't just happen when you're trying to. There's a kind of undirected thinking you do when walking or taking a shower or lying in bed that can be very powerful. By letting your mind wander a little, you'll often solve problems you were unable to solve by frontal attack.You have to be working hard in the normal way to benefit from this phenomenon, though. You can't just walk around daydreaming. The daydreaming has to be interleaved with deliberate work that feeds it questions. [10]Everyone knows to avoid distractions at work, but it's also important to avoid them in the other half of the cycle. When you let your mind wander, it wanders to whatever you care about most at that moment. So avoid the kind of distraction that pushes your work out of the top spot, or you'll waste this valuable type of thinking on the distraction instead. (Exception: Don't avoid love.) Consciously cultivate your taste in the work done in your field. Until you know which is the best and what makes it so, you don't know what you're aiming for.And that is what you're aiming for, because if you don't try to be the best, you won't even be good. This observation has been made by so many people in so many different fields that it might be worth thinking about why it's true. It could be because ambition is a phenomenon where almost all the error is in one direction — where almost all the shells that miss the target miss by falling short. Or it could be because ambition to be the best is a qualitatively different thing from ambition to be good. Or maybe being good is simply too vague a standard. Probably all three are true. [11]Fortunately there's a kind of economy of scale here. Though it might seem like you'd be taking on a heavy burden by trying to be the best, in practice you often end up net ahead. It's exciting, and also strangely liberating. It simplifies things. In some ways it's easier to try to be the best than to try merely to be good.One way to aim high is to try to make something that people will care about in a hundred years. Not because their opinions matter more than your contemporaries', but because something that still seems good in a hundred years is more likely to be genuinely good. Don't try to work in a distinctive style. Just try to do the best job you can; you won't be able to help doing it in a distinctive way.Style is doing things in a distinctive way without trying to. Trying to is affectation.Affectation is in effect to pretend that someone other than you is doing the work. You adopt an impressive but fake persona, and while you're pleased with the impressiveness, the fakeness is what shows in the work. [12]The temptation to be someone else is greatest for the young. They often feel like nobodies. But you never need to worry about that problem, because it's self-solving if you work on sufficiently ambitious projects. If you succeed at an ambitious project, you're not a nobody; you're the person who did it. So just do the work and your identity will take care of itself. "Avoid affectation" is a useful rule so far as it goes, but how would you express this idea positively? How would you say what to be, instead of what not to be? The best answer is earnest. If you're earnest you avoid not just affectation but a whole set of similar vices.The core of being earnest is being intellectually honest. We're taught as children to be honest as an unselfish virtue — as a kind of sacrifice. But in fact it's a source of power too. To see new ideas, you need an exceptionally sharp eye for the truth. You're trying to see more truth than others have seen so far. And how can you have a sharp eye for the truth if you're intellectually dishonest?One way to avoid intellectual dishonesty is to maintain a slight positive pressure in the opposite direction. Be aggressively willing to admit that you're mistaken. Once you've admitted you were mistaken about something, you're free. Till then you have to carry it. [13]Another more subtle component of earnestness is informality. Informality is much more important than its grammatically negative name implies. It's not merely the absence of something. It means focusing on what matters instead of what doesn't.What formality and affectation have in common is that as well as doing the work, you're trying to seem a certain way as you're doing it. But any energy that goes into how you seem comes out of being good. That's one reason nerds have an advantage in doing great work: they expend little effort on seeming anything. In fact that's basically the definition of a nerd.Nerds have a kind of innocent boldness that's exactly what you need in doing great work. It's not learned; it's preserved from childhood. So hold onto it. Be the one who puts things out there rather than the one who sits back and offers sophisticated-sounding criticisms of them. "It's easy to criticize" is true in the most literal sense, and the route to great work is never easy.There may be some jobs where it's an advantage to be cynical and pessimistic, but if you want to do great work it's an advantage to be optimistic, even though that means you'll risk looking like a fool sometimes. There's an old tradition of doing the opposite. The Old Testament says it's better to keep quiet lest you look like a fool. But that's advice for seeming smart. If you actually want to discover new things, it's better to take the risk of telling people your ideas.Some people are naturally earnest, and with others it takes a conscious effort. Either kind of earnestness will suffice. But I doubt it would be possible to do great work without being earnest. It's so hard to do even if you are. You don't have enough margin for error to accommodate the distortions introduced by being affected, intellectually dishonest, orthodox, fashionable, or cool. [14] Great work is consistent not only with who did it, but with itself. It's usually all of a piece. So if you face a decision in the middle of working on something, ask which choice is more consistent.You may have to throw things away and redo them. You won't necessarily have to, but you have to be willing to. And that can take some effort; when there's something you need to redo, status quo bias and laziness will combine to keep you in denial about it. To beat this ask: If I'd already made the change, would I want to revert to what I have now?Have the confidence to cut. Don't keep something that doesn't fit just because you're proud of it, or because it cost you a lot of effort.Indeed, in some kinds of work it's good to strip whatever you're doing to its essence. The result will be more concentrated; you'll understand it better; and you won't be able to lie to yourself about whether there's anything real there.Mathematical elegance may sound like a mere metaphor, drawn from the arts. That's what I thought when I first heard the term "elegant" applied to a proof. But now I suspect it's conceptually prior — that the main ingredient in artistic elegance is mathematical elegance. At any rate it's a useful standard well beyond math.Elegance can be a long-term bet, though. Laborious solutions will often have more prestige in the short term. They cost a lot of effort and they're hard to understand, both of which impress people, at least temporarily.Whereas some of the very best work will seem like it took comparatively little effort, because it was in a sense already there. It didn't have to be built, just seen. It's a very good sign when it's hard to say whether you're creating something or discovering it.When you're doing work that could be seen as either creation or discovery, err on the side of discovery. Try thinking of yourself as a mere conduit through which the ideas take their natural shape.(Strangely enough, one exception is the problem of choosing a problem to work on. This is usually seen as search, but in the best case it's more like creating something. In the best case you create the field in the process of exploring it.)Similarly, if you're trying to build a powerful tool, make it gratuitously unrestrictive. A powerful tool almost by definition will be used in ways you didn't expect, so err on the side of eliminating restrictions, even if you don't know what the benefit will be.Great work will often be tool-like in the sense of being something others build on. So it's a good sign if you're creating ideas that others could use, or exposing questions that others could answer. The best ideas have implications in many different areas.If you express your ideas in the most general form, they'll be truer than you intended. True by itself is not enough, of course. Great ideas have to be true and new. And it takes a certain amount of ability to see new ideas even once you've learned enough to get to one of the frontiers of knowledge.In English we give this ability names like originality, creativity, and imagination. And it seems reasonable to give it a separate name, because it does seem to some extent a separate skill. It's possible to have a great deal of ability in other respects — to have a great deal of what's often called "technical ability" — and yet not have much of this.I've never liked the term "creative process." It seems misleading. Originality isn't a process, but a habit of mind. Original thinkers throw off new ideas about whatever they focus on, like an angle grinder throwing off sparks. They can't help it.If the thing they're focused on is something they don't understand very well, these new ideas might not be good. One of the most original thinkers I know decided to focus on dating after he got divorced. He knew roughly as much about dating as the average 15 year old, and the results were spectacularly colorful. But to see originality separated from expertise like that made its nature all the more clear.I don't know if it's possible to cultivate originality, but there are definitely ways to make the most of however much you have. For example, you're much more likely to have original ideas when you're working on something. Original ideas don't come from trying to have original ideas. They come from trying to build or understand something slightly too difficult. [15]Talking or writing about the things you're interested in is a good way to generate new ideas. When you try to put ideas into words, a missing idea creates a sort of vacuum that draws it out of you. Indeed, there's a kind of thinking that can only be done by writing.Changing your context can help. If you visit a new place, you'll often find you have new ideas there. The journey itself often dislodges them. But you may not have to go far to get this benefit. Sometimes it's enough just to go for a walk. [16]It also helps to travel in topic space. You'll have more new ideas if you explore lots of different topics, partly because it gives the angle grinder more surface area to work on, and partly because analogies are an especially fruitful source of new ideas.Don't divide your attention evenly between many topics though, or you'll spread yourself too thin. You want to distribute it according to something more like a power law. [17] Be professionally curious about a few topics and idly curious about many more.Curiosity and originality are closely related. Curiosity feeds originality by giving it new things to work on. But the relationship is closer than that. Curiosity is itself a kind of originality; it's roughly to questions what originality is to answers. And since questions at their best are a big component of answers, curiosity at its best is a creative force. Having new ideas is a strange game, because it usually consists of seeing things that were right under your nose. Once you've seen a new idea, it tends to seem obvious. Why did no one think of this before?When an idea seems simultaneously novel and obvious, it's probably a good one.Seeing something obvious sounds easy. And yet empirically having new ideas is hard. What's the source of this apparent contradiction? It's that seeing the new idea usually requires you to change the way you look at the world. We see the world through models that both help and constrain us. When you fix a broken model, new ideas become obvious. But noticing and fixing a broken model is hard. That's how new ideas can be both obvious and yet hard to discover: they're easy to see after you do something hard.One way to discover broken models is to be stricter than other people. Broken models of the world leave a trail of clues where they bash against reality. Most people don't want to see these clues. It would be an understatement to say that they're attached to their current model; it's what they think in; so they'll tend to ignore the trail of clues left by its breakage, however conspicuous it may seem in retrospect.To find new ideas you have to seize on signs of breakage instead of looking away. That's what Einstein did. He was able to see the wild implications of Maxwell's equations not so much because he was looking for new ideas as because he was stricter.The other thing you need is a willingness to break rules. Paradoxical as it sounds, if you want to fix your model of the world, it helps to be the sort of person who's comfortable breaking rules. From the point of view of the old model, which everyone including you initially shares, the new model usually breaks at least implicit rules.Few understand the degree of rule-breaking required, because new ideas seem much more conservative once they succeed. They seem perfectly reasonable once you're using the new model of the world they brought with them. But they didn't at the time; it took the greater part of a century for the heliocentric model to be generally accepted, even among astronomers, because it felt so wrong.Indeed, if you think about it, a good new idea has to seem bad to most people, or someone would have already explored it. So what you're looking for is ideas that seem crazy, but the right kind of crazy. How do you recognize these? You can't with certainty. Often ideas that seem bad are bad. But ideas that are the right kind of crazy tend to be exciting; they're rich in implications; whereas ideas that are merely bad tend to be depressing.There are two ways to be comfortable breaking rules: to enjoy breaking them, and to be indifferent to them. I call these two cases being aggressively and passively independent-minded.The aggressively independent-minded are the naughty ones. Rules don't merely fail to stop them; breaking rules gives them additional energy. For this sort of person, delight at the sheer audacity of a project sometimes supplies enough activation energy to get it started.The other way to break rules is not to care about them, or perhaps even to know they exist. This is why novices and outsiders often make new discoveries; their ignorance of a field's assumptions acts as a source of temporary passive independent-mindedness. Aspies also seem to have a kind of immunity to conventional beliefs. Several I know say that this helps them to have new ideas.Strictness plus rule-breaking sounds like a strange combination. In popular culture they're opposed. But popular culture has a broken model in this respect. It implicitly assumes that issues are trivial ones, and in trivial matters strictness and rule-breaking are opposed. But in questions that really matter, only rule-breakers can be truly strict. An overlooked idea often doesn't lose till the semifinals. You do see it, subconsciously, but then another part of your subconscious shoots it down because it would be too weird, too risky, too much work, too controversial. This suggests an exciting possibility: if you could turn off such filters, you could see more new ideas.One way to do that is to ask what would be good ideas for someone else to explore. Then your subconscious won't shoot them down to protect you.You could also discover overlooked ideas by working in the other direction: by starting from what's obscuring them. Every cherished but mistaken principle is surrounded by a dead zone of valuable ideas that are unexplored because they contradict it.Religions are collections of cherished but mistaken principles. So anything that can be described either literally or metaphorically as a religion will have valuable unexplored ideas in its shadow. Copernicus and Darwin both made discoveries of this type. [18]What are people in your field religious about, in the sense of being too attached to some principle that might not be as self-evident as they think? What becomes possible if you discard it? People show much more originality in solving problems than in deciding which problems to solve. Even the smartest can be surprisingly conservative when deciding what to work on. People who'd never dream of being fashionable in any other way get sucked into working on fashionable problems.One reason people are more conservative when choosing problems than solutions is that problems are bigger bets. A problem could occupy you for years, while exploring a solution might only take days. But even so I think most people are too conservative. They're not merely responding to risk, but to fashion as well. Unfashionable problems are undervalued.One of the most interesting kinds of unfashionable problem is the problem that people think has been fully explored, but hasn't. Great work often takes something that already exists and shows its latent potential. Durer and Watt both did this. So if you're interested in a field that others think is tapped out, don't let their skepticism deter you. People are often wrong about this.Working on an unfashionable problem can be very pleasing. There's no hype or hurry. Opportunists and critics are both occupied elsewhere. The existing work often has an old-school solidity. And there's a satisfying sense of economy in cultivating ideas that would otherwise be wasted.But the most common type of overlooked problem is not explicitly unfashionable in the sense of being out of fashion. It just doesn't seem to matter as much as it actually does. How do you find these? By being self-indulgent — by letting your curiosity have its way, and tuning out, at least temporarily, the little voice in your head that says you should only be working on "important" problems.You do need to work on important problems, but almost everyone is too conservative about what counts as one. And if there's an important but overlooked problem in your neighborhood, it's probably already on your subconscious radar screen. So try asking yourself: if you were going to take a break from "serious" work to work on something just because it would be really interesting, what would you do? The answer is probably more important than it seems.Originality in choosing problems seems to matter even more than originality in solving them. That's what distinguishes the people who discover whole new fields. So what might seem to be merely the initial step — deciding what to work on — is in a sense the key to the whole game. Few grasp this. One of the biggest misconceptions about new ideas is about the ratio of question to answer in their composition. People think big ideas are answers, but often the real insight was in the question.Part of the reason we underrate questions is the way they're used in schools. In schools they tend to exist only briefly before being answered, like unstable particles. But a really good question can be much more than that. A really good question is a partial discovery. How do new species arise? Is the force that makes objects fall to earth the same as the one that keeps planets in their orbits? By even asking such questions you were already in excitingly novel territory.Unanswered questions can be uncomfortable things to carry around with you. But the more you're carrying, the greater the chance of noticing a solution — or perhaps even more excitingly, noticing that two unanswered questions are the same.Sometimes you carry a question for a long time. Great work often comes from returning to a question you first noticed years before — in your childhood, even — and couldn't stop thinking about. People talk a lot about the importance of keeping your youthful dreams alive, but it's just as important to keep your youthful questions alive. [19]This is one of the places where actual expertise differs most from the popular picture of it. In the popular picture, experts are certain. But actually the more puzzled you are, the better, so long as (a) the things you're puzzled about matter, and (b) no one else understands them either.Think about what's happening at the moment just before a new idea is discovered. Often someone with sufficient expertise is puzzled about something. Which means that originality consists partly of puzzlement — of confusion! You have to be comfortable enough with the world being full of puzzles that you're willing to see them, but not so comfortable that you don't want to solve them. [20]It's a great thing to be rich in unanswered questions. And this is one of those situations where the rich get richer, because the best way to acquire new questions is to try answering existing ones. Questions don't just lead to answers, but also to more questions. The best questions grow in the answering. You notice a thread protruding from the current paradigm and try pulling on it, and it just gets longer and longer. So don't require a question to be obviously big before you try answering it. You can rarely predict that. It's hard enough even to notice the thread, let alone to predict how much will unravel if you pull on it.It's better to be promiscuously curious — to pull a little bit on a lot of threads, and see what happens. Big things start small. The initial versions of big things were often just experiments, or side projects, or talks, which then grew into something bigger. So start lots of small things.Being prolific is underrated. The more different things you try, the greater the chance of discovering something new. Understand, though, that trying lots of things will mean trying lots of things that don't work. You can't have a lot of good ideas without also having a lot of bad ones. [21]Though it sounds more responsible to begin by studying everything that's been done before, you'll learn faster and have more fun by trying stuff. And you'll understand previous work better when you do look at it. So err on the side of starting. Which is easier when starting means starting small; those two ideas fit together like two puzzle pieces.How do you get from starting small to doing something great? By making successive versions. Great things are almost always made in successive versions. You start with something small and evolve it, and the final version is both cleverer and more ambitious than anything you could have planned.It's particularly useful to make successive versions when you're making something for people — to get an initial version in front of them quickly, and then evolve it based on their response.Begin by trying the simplest thing that could possibly work. Surprisingly often, it does. If it doesn't, this will at least get you started.Don't try to cram too much new stuff into any one version. There are names for doing this with the first version (taking too long to ship) and the second (the second system effect), but these are both merely instances of a more general principle.An early version of a new project will sometimes be dismissed as a toy. It's a good sign when people do this. That means it has everything a new idea needs except scale, and that tends to follow. [22]The alternative to starting with something small and evolving it is to plan in advance what you're going to do. And planning does usually seem the more responsible choice. It sounds more organized to say "we're going to do x and then y and then z" than "we're going to try x and see what happens." And it is more organized; it just doesn't work as well.Planning per se isn't good. It's sometimes necessary, but it's a necessary evil — a response to unforgiving conditions. It's something you have to do because you're working with inflexible media, or because you need to coordinate the efforts of a lot of people. If you keep projects small and use flexible media, you don't have to plan as much, and your designs can evolve instead. Take as much risk as you can afford. In an efficient market, risk is proportionate to reward, so don't look for certainty, but for a bet with high expected value. If you're not failing occasionally, you're probably being too conservative.Though conservatism is usually associated with the old, it's the young who tend to make this mistake. Inexperience makes them fear risk, but it's when you're young that you can afford the most.Even a project that fails can be valuable. In the process of working on it, you'll have crossed territory few others have seen, and encountered questions few others have asked. And there's probably no better source of questions than the ones you encounter in trying to do something slightly too hard. Use the advantages of youth when you have them, and the advantages of age once you have those. The advantages of youth are energy, time, optimism, and freedom. The advantages of age are knowledge, efficiency, money, and power. With effort you can acquire some of the latter when young and keep some of the former when old.The old also have the advantage of knowing which advantages they have. The young often have them without realizing it. The biggest is probably time. The young have no idea how rich they are in time. The best way to turn this time to advantage is to use it in slightly frivolous ways: to learn about something you don't need to know about, just out of curiosity, or to try building something just because it would be cool, or to become freakishly good at something.That "slightly" is an important qualification. Spend time lavishly when you're young, but don't simply waste it. There's a big difference between doing something you worry might be a waste of time and doing something you know for sure will be. The former is at least a bet, and possibly a better one than you think. [23]The most subtle advantage of youth, or more precisely of inexperience, is that you're seeing everything with fresh eyes. When your brain embraces an idea for the first time, sometimes the two don't fit together perfectly. Usually the problem is with your brain, but occasionally it's with the idea. A piece of it sticks out awkwardly and jabs you when you think about it. People who are used to the idea have learned to ignore it, but you have the opportunity not to. [24]So when you're learning about something for the first time, pay attention to things that seem wrong or missing. You'll be tempted to ignore them, since there's a 99% chance the problem is with you. And you may have to set aside your misgivings temporarily to keep progressing. But don't forget about them. When you've gotten further into the subject, come back and check if they're still there. If they're still viable in the light of your present knowledge, they probably represent an undiscovered idea. One of the most valuable kinds of knowledge you get from experience is to know what you don't have to worry about. The young know all the things that could matter, but not their relative importance. So they worry equally about everything, when they should worry much more about a few things and hardly at all about the rest.But what you don't know is only half the problem with inexperience. The other half is what you do know that ain't so. You arrive at adulthood with your head full of nonsense — bad habits you've acquired and false things you've been taught — and you won't be able to do great work till you clear away at least the nonsense in the way of whatever type of work you want to do.Much of the nonsense left in your head is left there by schools. We're so used to schools that we unconsciously treat going to school as identical with learning, but in fact schools have all sorts of strange qualities that warp our ideas about learning and thinking.For example, schools induce passivity. Since you were a small child, there was an authority at the front of the class telling all of you what you had to learn and then measuring whether you did. But neither classes nor tests are intrinsic to learning; they're just artifacts of the way schools are usually designed.The sooner you overcome this passivity, the better. If you're still in school, try thinking of your education as your project, and your teachers as working for you rather than vice versa. That may seem a stretch, but it's not merely some weird thought experiment. It's the truth, economically, and in the best case it's the truth intellectually as well. The best teachers don't want to be your bosses. They'd prefer it if you pushed ahead, using them as a source of advice, rather than being pulled by them through the material.Schools also give you a misleading impression of what work is like. In school they tell you what the problems are, and they're almost always soluble using no more than you've been taught so far. In real life you have to figure out what the problems are, and you often don't know if they're soluble at all.But perhaps the worst thing schools do to you is train you to win by hacking the test. You can't do great work by doing that. You can't trick God. So stop looking for that kind of shortcut. The way to beat the system is to focus on problems and solutions that others have overlooked, not to skimp on the work itself. Don't think of yourself as dependent on some gatekeeper giving you a "big break." Even if this were true, the best way to get it would be to focus on doing good work rather than chasing influential people.And don't take rejection by committees to heart. The qualities that impress admissions officers and prize committees are quite different from those required to do great work. The decisions of selection committees are only meaningful to the extent that they're part of a feedback loop, and very few are. People new to a field will often copy existing work. There's nothing inherently bad about that. There's no better way to learn how something works than by trying to reproduce it. Nor does copying necessarily make your work unoriginal. Originality is the presence of new ideas, not the absence of old ones.There's a good way to copy and a bad way. If you're going to copy something, do it openly instead of furtively, or worse still, unconsciously. This is what's meant by the famously misattributed phrase "Great artists steal." The really dangerous kind of copying, the kind that gives copying a bad name, is the kind that's done without realizing it, because you're nothing more than a train running on tracks laid down by someone else. But at the other extreme, copying can be a sign of superiority rather than subordination. [25]In many fields it's almost inevitable that your early work will be in some sense based on other people's. Projects rarely arise in a vacuum. They're usually a reaction to previous work. When you're first starting out, you don't have any previous work; if you're going to react to something, it has to be someone else's. Once you're established, you can react to your own. But while the former gets called derivative and the latter doesn't, structurally the two cases are more similar than they seem.Oddly enough, the very novelty of the most novel ideas sometimes makes them seem at first to be more derivative than they are. New discoveries often have to be conceived initially as variations of existing things, even by their discoverers, because there isn't yet the conceptual vocabulary to express them.There are definitely some dangers to copying, though. One is that you'll tend to copy old things — things that were in their day at the frontier of knowledge, but no longer are.And when you do copy something, don't copy every feature of it. Some will make you ridiculous if you do. Don't copy the manner of an eminent 50 year old professor if you're 18, for example, or the idiom of a Renaissance poem hundreds of years later.Some of the features of things you admire are flaws they succeeded despite. Indeed, the features that are easiest to imitate are the most likely to be the flaws.This is particularly true for behavior. Some talented people are jerks, and this sometimes makes it seem to the inexperienced that being a jerk is part of being talented. It isn't; being talented is merely how they get away with it.One of the most powerful kinds of copying is to copy something from one field into another. History is so full of chance discoveries of this type that it's probably worth giving chance a hand by deliberately learning about other kinds of work. You can take ideas from quite distant fields if you let them be metaphors.Negative examples can be as inspiring as positive ones. In fact you can sometimes learn more from things done badly than from things done well; sometimes it only becomes clear what's needed when it's missing. If a lot of the best people in your field are collected in one place, it's usually a good idea to visit for a while. It will increase your ambition, and also, by showing you that these people are human, increase your self-confidence. [26]If you're earnest you'll probably get a warmer welcome than you might expect. Most people who are very good at something are happy to talk about it with anyone who's genuinely interested. If they're really good at their work, then they probably have a hobbyist's interest in it, and hobbyists always want to talk about their hobbies.It may take some effort to find the people who are really good, though. Doing great work has such prestige that in some places, particularly universities, there's a polite fiction that everyone is engaged in it. And that is far from true. People within universities can't say so openly, but the quality of the work being done in different departments varies immensely. Some departments have people doing great work; others have in the past; others never have. Seek out the best colleagues. There are a lot of projects that can't be done alone, and even if you're working on one that can be, it's good to have other people to encourage you and to bounce ideas off.Colleagues don't just affect your work, though; they also affect you. So work with people you want to become like, because you will.Quality is more important than quantity in colleagues. It's better to have one or two great ones than a building full of pretty good ones. In fact it's not merely better, but necessary, judging from history: the degree to which great work happens in clusters suggests that one's colleagues often make the difference between doing great work and not.How do you know when you have sufficiently good colleagues? In my experience, when you do, you know. Which means if you're unsure, you probably don't. But it may be possible to give a more concrete answer than that. Here's an attempt: sufficiently good colleagues offer surprising insights. They can see and do things that you can't. So if you have a handful of colleagues good enough to keep you on your toes in this sense, you're probably over the threshold.Most of us can benefit from collaborating with colleagues, but some projects require people on a larger scale, and starting one of those is not for everyone. If you want to run a project like that, you'll have to become a manager, and managing well takes aptitude and interest like any other kind of work. If you don't have them, there is no middle path: you must either force yourself to learn management as a second language, or avoid such projects. [27] Husband your morale. It's the basis of everything when you're working on ambitious projects. You have to nurture and protect it like a living organism.Morale starts with your view of life. You're more likely to do great work if you're an optimist, and more likely to if you think of yourself as lucky than if you think of yourself as a victim.Indeed, work can to some extent protect you from your problems. If you choose work that's pure, its very difficulties will serve as a refuge from the difficulties of everyday life. If this is escapism, it's a very productive form of it, and one that has been used by some of the greatest minds in history.Morale compounds via work: high morale helps you do good work, which increases your morale and helps you do even better work. But this cycle also operates in the other direction: if you're not doing good work, that can demoralize you and make it even harder to. Since it matters so much for this cycle to be running in the right direction, it can be a good idea to switch to easier work when you're stuck, just so you start to get something done.One of the biggest mistakes ambitious people make is to allow setbacks to destroy their morale all at once, like a balloon bursting. You can inoculate yourself against this by explicitly considering setbacks a part of your process. Solving hard problems always involves some backtracking.Doing great work is a depth-first search whose root node is the desire to. So "If at first you don't succeed, try, try again" isn't quite right. It should be: If at first you don't succeed, either try again, or backtrack and then try again."Never give up" is also not quite right. Obviously there are times when it's the right choice to eject. A more precise version would be: Never let setbacks panic you into backtracking more than you need to. Corollary: Never abandon the root node.It's not necessarily a bad sign if work is a struggle, any more than it's a bad sign to be out of breath while running. It depends how fast you're running. So learn to distinguish good pain from bad. Good pain is a sign of effort; bad pain is a sign of damage. An audience is a critical component of morale. If you're a scholar, your audience may be your peers; in the arts, it may be an audience in the traditional sense. Either way it doesn't need to be big. The value of an audience doesn't grow anything like linearly with its size. Which is bad news if you're famous, but good news if you're just starting out, because it means a small but dedicated audience can be enough to sustain you. If a handful of people genuinely love what you're doing, that's enough.To the extent you can, avoid letting intermediaries come between you and your audience. In some types of work this is inevitable, but it's so liberating to escape it that you might be better off switching to an adjacent type if that will let you go direct. [28]The people you spend time with will also have a big effect on your morale. You'll find there are some who increase your energy and others who decrease it, and the effect someone has is not always what you'd expect. Seek out the people who increase your energy and avoid those who decrease it. Though of course if there's someone you need to take care of, that takes precedence.Don't marry someone who doesn't understand that you need to work, or sees your work as competition for your attention. If you're ambitious, you need to work; it's almost like a medical condition; so someone who won't let you work either doesn't understand you, or does and doesn't care.Ultimately morale is physical. You think with your body, so it's important to take care of it. That means exercising regularly, eating and sleeping well, and avoiding the more dangerous kinds of drugs. Running and walking are particularly good forms of exercise because they're good for thinking. [29]People who do great work are not necessarily happier than everyone else, but they're happier than they'd be if they didn't. In fact, if you're smart and ambitious, it's dangerous not to be productive. People who are smart and ambitious but don't achieve much tend to become bitter. It's ok to want to impress other people, but choose the right people. The opinion of people you respect is signal. Fame, which is the opinion of a much larger group you might or might not respect, just adds noise.The prestige of a type of work is at best a trailing indicator and sometimes completely mistaken. If you do anything well enough, you'll make it prestigious. So the question to ask about a type of work is not how much prestige it has, but how well it could be done.Competition can be an effective motivator, but don't let it choose the problem for you; don't let yourself get drawn into chasing something just because others are. In fact, don't let competitors make you do anything much more specific than work harder.Curiosity is the best guide. Your curiosity never lies, and it knows more than you do about what's worth paying attention to. Notice how often that word has come up. If you asked an oracle the secret to doing great work and the oracle replied with a single word, my bet would be on "curiosity."That doesn't translate directly to advice. It's not enough just to be curious, and you can't command curiosity anyway. But you can nurture it and let it drive you.Curiosity is the key to all four steps in doing great work: it will choose the field for you, get you to the frontier, cause you to notice the gaps in it, and drive you to explore them. The whole process is a kind of dance with curiosity. Believe it or not, I tried to make this essay as short as I could. But its length at least means it acts as a filter. If you made it this far, you must be interested in doing great work. And if so you're already further along than you might realize, because the set of people willing to want to is small.The factors in doing great work are factors in the literal, mathematical sense, and they are: ability, interest, effort, and luck. Luck by definition you can't do anything about, so we can ignore that. And we can assume effort, if you do in fact want to do great work. So the problem boils down to ability and interest. Can you find a kind of work where your ability and interest will combine to yield an explosion of new ideas?Here there are grounds for optimism. There are so many different ways to do great work, and even more that are still undiscovered. Out of all those different types of work, the one you're most suited for is probably a pretty close match. Probably a comically close match. It's just a question of finding it, and how far into it your ability and interest can take you. And you can only answer that by trying.Many more people could try to do great work than do. What holds them back is a combination of modesty and fear. It seems presumptuous to try to be Newton or Shakespeare. It also seems hard; surely if you tried something like that, you'd fail. Presumably the calculation is rarely explicit. Few people consciously decide not to try to do great work. But that's what's going on subconsciously; they shy away from the question.So I'm going to pull a sneaky trick on you. Do you want to do great work, or not? Now you have to decide consciously. Sorry about that. I wouldn't have done it to a general audience. But we already know you're interested.Don't worry about being presumptuous. You don't have to tell anyone. And if it's too hard and you fail, so what? Lots of people have worse problems than that. In fact you'll be lucky if it's the worst problem you have.Yes, you'll have to work hard. But again, lots of people have to work hard. And if you're working on something you find very interesting, which you necessarily will if you're on the right path, the work will probably feel less burdensome than a lot of your peers'.The discoveries are out there, waiting to be made. Why not by you? Notes[1] I don't think you could give a precise definition of what counts as great work. Doing great work means doing something important so well that you expand people's ideas of what's possible. But there's no threshold for importance. It's a matter of degree, and often hard to judge at the time anyway. So I'd rather people focused on developing their interests rather than worrying about whether they're important or not. Just try to do something amazing, and leave it to future generations to say if you succeeded.[2] A lot of standup comedy is based on noticing anomalies in everyday life. "Did you ever notice...?" New ideas come from doing this about nontrivial things. Which may help explain why people's reaction to a new idea is often the first half of laughing: Ha![3] That second qualifier is critical. If you're excited about something most authorities discount, but you can't give a more precise explanation than "they don't get it," then you're starting to drift into the territory of cranks.[4] Finding something to work on is not simply a matter of finding a match between the current version of you and a list of known problems. You'll often have to coevolve with the problem. That's why it can sometimes be so hard to figure out what to work on. The search space is huge. It's the cartesian product of all possible types of work, both known and yet to be discovered, and all possible future versions of you.There's no way you could search this whole space, so you have to rely on heuristics to generate promising paths through it and hope the best matches will be clustered. Which they will not always be; different types of work have been collected together as much by accidents of history as by the intrinsic similarities between them.[5] There are many reasons curious people are more likely to do great work, but one of the more subtle is that, by casting a wide net, they're more likely to find the right thing to work on in the first place.[6] It can also be dangerous to make things for an audience you feel is less sophisticated than you, if that causes you to talk down to them. You can make a lot of money doing that, if you do it in a sufficiently cynical way, but it's not the route to great work. Not that anyone using this m.o. would care.[7] This idea I learned from Hardy's A Mathematician's Apology, which I recommend to anyone ambitious to do great work, in any field.[8] Just as we overestimate what we can do in a day and underestimate what we can do over several years, we overestimate the damage done by procrastinating for a day and underestimate the damage done by procrastinating for several years.[9] You can't usually get paid for doing exactly what you want, especially early on. There are two options: get paid for doing work close to what you want and hope to push it closer, or get paid for doing something else entirely and do your own projects on the side. Both can work, but both have drawbacks: in the first approach your work is compromised by default, and in the second you have to fight to get time to do it.[10] If you set your life up right, it will deliver the focus-relax cycle automatically. The perfect setup is an office you work in and that you walk to and from.[11] There may be some very unworldly people who do great work without consciously trying to. If you want to expand this rule to cover that case, it becomes: Don't try to be anything except the best.[12] This gets more complicated in work like acting, where the goal is to adopt a fake persona. But even here it's possible to be affected. Perhaps the rule in such fields should be to avoid unintentional affectation.[13] It's safe to have beliefs that you treat as unquestionable if and only if they're also unfalsifiable. For example, it's safe to have the principle that everyone should be treated equally under the law, because a sentence with a "should" in it isn't really a statement about the world and is therefore hard to disprove. And if there's no evidence that could disprove one of your principles, there can't be any facts you'd need to ignore in order to preserve it.[14] Affectation is easier to cure than intellectual dishonesty. Affectation is often a shortcoming of the young that burns off in time, while intellectual dishonesty is more of a character flaw.[15] Obviously you don't have to be working at the exact moment you have the idea, but you'll probably have been working fairly recently.[16] Some say psychoactive drugs have a similar effect. I'm skeptical, but also almost totally ignorant of their effects.[17] For example you might give the nth most important topic (m-1)/m^n of your attention, for some m > 1. You couldn't allocate your attention so precisely, of course, but this at least gives an idea of a reasonable distribution.[18] The principles defining a religion have to be mistaken. Otherwise anyone might adopt them, and there would be nothing to distinguish the adherents of the religion from everyone else.[19] It might be a good exercise to try writing down a list of questions you wondered about in your youth. You might find you're now in a position to do something about some of them.[20] The connection between originality and uncertainty causes a strange phenomenon: because the conventional-minded are more certain than the independent-minded, this tends to give them the upper hand in disputes, even though they're generally stupider. The best lack all conviction, while the worst Are full of passionate intensity. [21] Derived from <NAME>'s "If you want to have good ideas, you must have many ideas."[22] Attacking a project as a "toy" is similar to attacking a statement as "inappropriate." It means that no more substantial criticism can be made to stick.[23] One way to tell whether you're wasting time is to ask if you're producing or consuming. Writing computer games is less likely to be a waste of time than playing them, and playing games where you create something is less likely to be a waste of time than playing games where you don't.[24] Another related advantage is that if you haven't said anything publicly yet, you won't be biased toward evidence that supports your earlier conclusions. With sufficient integrity you could achieve eternal youth in this respect, but few manage to. For most people, having previously published opinions has an effect similar to ideology, just in quantity 1.[25] In the early 1630s <NAME> made a painting of Henrietta Maria handing a laurel wreath to <NAME> then painted his own version to show how much better he was.[26] I'm being deliberately vague about what a place is. As of this writing, being in the same physical place has advantages that are hard to duplicate, but that could change.[27] This is false when the work the other people have to do is very constrained, as with SETI@home or Bitcoin. It may be possible to expand the area in which it's false by defining similarly restricted protocols with more freedom of action in the nodes.[28] Corollary: Building something that enables people to go around intermediaries and engage directly with their audience is probably a good idea.[29] It may be helpful always to walk or run the same route, because that frees attention for thinking. It feels that way to me, and there is some historical evidence for it.Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and my younger son for suggestions and for reading drafts.
https://github.com/pranphy/tymer
https://raw.githubusercontent.com/pranphy/tymer/main/README.md
markdown
MIT License
# tymer A minimalist [typst](https://typst.app/docs) packages to make slide. The theme is kinda like some beamer theme, at least the layout. This doesn't have fancy features like uncover, only etc. I don't find them useful, they are just distractions. # Installation ```bash git clone [email protected]:pranphy/tymer ~/.local/share/typst/packages/local/tymer/0.1.0/ ``` # Usage In your `slide.typ` file ```typst #import "@local/tymer:0.1.0": * #show: slides.with( authors: "<NAME>", institute: Institute("University of Virginia",short:"UVa"), short-authors: "<NAME>", title: "Background from all edges", location: "Moller Simulation Meeting", thm: (fg:white.darken(00%),bg:black.lighten(21%),ac: orange) ) #titlepage() ``` This will create just a title page. The theme can be configured with different colours. `fg:` sets the text colour. `bg:` sets the background colour and `ac:` for accent colour. You can have a example slide like ```typst #slide(title: "Background from different edges")[ - Item 1 - Item 2 $ (sin phi ) / (cos phi) = tan phi $ ] ``` You can makr the start of backup slide with `backup` function like: ```typst #backup(text(60pt)[Backup]) ``` The text passed to `backup` function would set the text on backup slide marker. The backup slides have their own independent numbering different from regular slide numbering. Backup slides are exactly same as regular slides. ```typst #slide(title: "Background from different edges")[ - Nothing different here - Same deal. ] ``` # Compile ```bash $ typst compile slide.typ ``` This should produce `slide.pdf`, which you can view with your favourite pdf viewer (zathura??).
https://github.com/Enter-tainer/typst-preview
https://raw.githubusercontent.com/Enter-tainer/typst-preview/main/addons/vscode/README.md
markdown
MIT License
# [Typst Preview VSCode](https://github.com/Enter-tainer/typst-preview) Preview your Typst files in vscode instantly! ## Features - Low latency preview: preview your document instantly on type. The incremental rendering technique makes the preview latency as low as possible. - Open in browser: open the preview in browser, so you put it in another monitor. https://github.com/typst/typst/issues/1344 - Cross jump between code and preview: We implement SyncTeX-like feature for typst-preview. You can now click on the preview panel to jump to the corresponding code location, and vice versa. Install this extension from [marketplace](https://marketplace.visualstudio.com/items?itemName=mgt19937.typst-preview), open command palette (Ctrl+Shift+P), and type `>Typst Preview:`. You can also use the shortcut (Ctrl+K V). ![demo](demo.png) For more information, please visit documentation at [Typst Preview Book](https://enter-tainer.github.io/typst-preview/). ## Extension Settings See https://enter-tainer.github.io/typst-preview/config.html ## Bug report To achieve high performance instant preview, we use a **different rendering backend** from official typst. We are making our best effort to keep the rendering result consistent with official typst. We have set up comprehensive tests to ensure the consistency of the rendering result. But we cannot guarantee that the rendering result is the same in all cases. There can be unknown corner cases that we haven't covered. **Therefore, if you encounter any rendering issue, please report it to this repo other than official typst repo.** ## Known Issues See [issues](https://github.com/Enter-tainer/typst-preview/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc) on GitHub. ## Legal This project is not affiliated with, created by, or endorsed by Typst the brand. ## Change Log See [CHANGELOG.md](CHANGELOG.md)
https://github.com/xrarch/books
https://raw.githubusercontent.com/xrarch/books/main/xr17032handbook/chapcontrol.typ
typst
#import "@preview/tablex:0.0.6": tablex, cellx, colspanx, rowspanx = Processor Control <control> === Introduction The behavior of the processor is primarily controlled by a small set of control registers (CRs). They are summarized by a table in @controlregs, and are explored in much more detail below. #box([ === RS <rs> _Processor Status_ #image("rs.png", fit: "stretch") The *RS* control register contains a three-deep "stack" of mode bits (the top of which contains the primary mode bits that control the state of the processor). The four *ECAUSE* bits identify the cause of the last exception. They are enumerated in @ecause. ], width: 100%) When an exception is taken, several of the mode bits are overwritten to place the processor into kernel mode with interrupts disabled. Because of the need to return from an exception with the state of the processor intact, there is a need to save the previous mode bits somewhere. In some CISC designs, like fox32 #footnote([fox32 is a trademark of Ryfox Computer Corp.]), this is accomplished by pushing the old state onto the stack. However, because this is a design following RISCy philosophy, performing a memory access during exception dispatch is considered unacceptable complexity. Instead, there is a small "stack" of mode bits within the *RS* control register. When an exception is taken, the current mode is shifted left by 8 into the "old mode", which itself is shifted left by 8 into the "old old mode", effectively performing a "push" onto a small stack. Any mode bits in the "old old mode" at this time are destroyed, and so manually saving *RS* is required if it is desired to go more than three levels deep. The *RFE* (Return From Exception) instruction atomically reverses this, popping the old mode bits into the current mode bits. The reason that this stack is three-deep is to account for this case: #footnote([The mode stack was once two-deep but was grown to three when software TB miss handling was introduced to the architecture, as this case would otherwise destroy the saved state in the old mode bits. Note also that the mode stack itself is an idea borrowed from the MIPS architecture's *SR* cop0 register.]) 1. Normal processing is occurring. 2. An exception occurs, pushing the original state into the old mode. 3. A TB miss exception is taken during the exception handler, before it can save *RS*, pushing the original state into the old old mode. #box([ The mode bits are defined as follows when set: #set align(center) #tablex( columns: (auto, auto), align: horizon, cellx([ #set text(fill: white) #set align(center) ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *Function* ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *U* ], fill: rgb(0,0,0,255)), [Usermode is active. Privileged instructions, which all have a major opcode of *101001*, are forbidden and will produce a privilege violation exception if executed.], cellx([ #set text(fill: white) #set align(center) *I* ], fill: rgb(0,0,0,255)), "External device interrupts are enabled.", cellx([ #set text(fill: white) #set align(center) *M* ], fill: rgb(0,0,0,255)), [Paged virtual addressing is enabled. The ITB and DTB are looked up to translate instruction fetches and data accesses, respectively (see @mmu).], cellx([ #set text(fill: white) #set align(center) *T* ], fill: rgb(0,0,0,255)), [A TB miss is in progress. This causes the *zero* register to be usable as a full register; i.e., it is not wired to read all zeroes while this bit is set. This is intended to free it as a scratch register for TB miss routines, to avoid having to save any registers. This bit also has special effects on exception handling, which are enumerated in @tbmiss.] ) #set align(left) ], width: 100%) Modifying the current mode bits must be done with a read-modify-write procedure; that is, if one wished to enable interrupts, they would need to read *RS* into some register, set the *I* bit, and then write the contents of that register back into *RS*. The same principle applies to the other mode bits. #box([ === WHAMI _Who Am I_ In a multiprocessor system, *WHAMI* contains a numeric ID which is unique to each processor in the system. It should be in a range of \[0, MAXPROC-1\], where MAXPROC is the maximum number of processors supported by the platform. Therefore, on a uniprocessor system, it should always contain zero. ], width: 100%) #box([ === EB <exceptionblock> _Exception Block Base_ #image("eb.png", fit: "stretch") The *EB* control register indicates the base address of the exception block. ], width: 100%) When an exception is taken by the processor, the program counter must be redirected to an exception handler. Some architectures use a table of exception vectors, which is indexed and loaded by the processor in order to determine whether to jump. However, as this is a RISC architecture, memory accesses during exception dispatch are unacceptable complexity. Instead, upon exception, the PC is redirected to an offset within the "exception block". The offset is calculated using the *ECAUSE* code of the exception, which is a 4-bit number between 0 and 15. The exception block occupies exactly one page frame, which is 4096 bytes in size. As there are 16 possible exception codes, each vector has room for $4096 / 16 = 256$ bytes, or $256 / 4 = 64$ instructions. This provides enough room to handle simple cases of exceptions, such as TB misses, without needing to branch outside of the exception block. The new program counter is calculated by *EB* | *ECAUSE* << 8, and so the base address of the exception block must be page-aligned, that is, the low 12 bits must be zero, otherwise garbage may be loaded into PC. Note that as the TB miss handlers themselves reside in the exception block, the system software must place the exception block page into a wired TB entry before virtual addressing is enabled, since the processor will not survive taking an ITB miss on the ITB handler. This also avoids costly TB misses when taking exceptions. See @tbindex or @managetb for more details on wired TB entries. #box([ ==== ECAUSE Codes <ecause> A table of all defined exception causes follows: ], width: 100%) #set align(center) #tablex( columns: (auto, auto, auto, auto), align: horizon, repeat-header: true, cellx([ #set text(fill: white) #set align(center) *\#* ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *EB* ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *Name* ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *Occurrence* ], fill: rgb(0,0,0,255)), "1", "+100", "INT", "An external interrupt has occurred.", "2", "+200", "SYS", [A *SYS* instruction has been executed.], "4", "+400", "BUS", "A bus error has occurred, usually caused by a non-existent physical address being accessed.", "5", "+500", "NMI", "Non-maskable interrupt.", "6", "+600", "BRK", [A *BRK* instruction has been executed.], "7", "+700", "INV", "An invalid instruction has been executed.", "8", "+800", "PRV", "A privileged instruction was executed in usermode.", "9", "+900", "UNA", "An unaligned address was accessed.", "12", "+C00", "PGF", "A virtual address matched to an unsuitable PTE in the TB during a read, causing a page fault.", "13", "+D00", "PFW", "A virtual address matched to an unsuitable PTE in the TB during a write, causing a page fault.", "14", "+E00", "ITB", "A virtual address failed to match in the ITB during instruction fetch.", "15", "+F00", "DTB", "A virtual address failed to match in the DTB during data access.", ) _Any absent ECAUSE codes are reserved for future use._ #set align(left) #box([ === EPC _Exception Program Counter_ When an exception is taken, the current program counter is saved into *EPC*. The *RFE* instruction restores the program counter from this control register, atomically with restoring the mode bits (see @rs). ], width: 100%) #box([ === EBADADDR _Exception Bad Address_ When a bus error or page fault exception is taken, *EBADADDR* is filled with the physical or virtual address, respectively, that caused the exception. ], width: 100%) #box([ === TBMISSADDR _Translation Buffer Missed Address_ When a TB miss exception is taken, and the *T* bit is not set in *RS*, *TBMISSADDR* is filled with the virtual address that failed to match in the TB. If the *T* bit is set, however (i.e., the processor is already handling a TB miss), this CR is left alone. This CR, therefore, is not affected upon a nested TB miss exception, and always contains the missed virtual address that caused the first one. ], width: 100%) #box([ === TBPC _Translation Buffer Miss Program Counter_ When a TB miss exception is taken, and the *T* bit is not set in *RS*, the current program counter is saved into *TBPC*. If the *T* bit is set, however (i.e., the processor is already handling a TB miss), this CR is left alone. This CR, therefore, is not affected upon a nested TB miss exception, and always contains the program counter that caused the first one. Additionally, if the *T* bit is set when the *RFE* instruction is executed, it will restore the program counter to the value of *TBPC* rather than that of *EPC*, allowing instant return to the original faulting instruction without having to potentially unwind several levels of nested TB misses. See @tbmiss for more details. ], width: 100%) #box([ === SCRATCH0-4 _Arbitrary Scratch_ The system software can use the *SCRATCH0* through *SCRATCH4* control registers for anything. They are fully readable and writable and do not perform any action. The intended usage is to save general purpose registers to free them up as scratch within exception handlers, but other usages are also possible. ], width: 100%) #box([ === ITBPTE/DTBPTE <tbpte> _Translation Buffer Page Table Entry_ #image("tbpte.png", fit: "stretch") When written, the *ITBPTE* and *DTBPTE* control registers will cause an entry to be written to the ITB or DTB, respectively. The upper 32 bits of the entry are taken from the current value of *ITBTAG* or *DTBTAG*, and the lower 32 bits are taken from the value written to this control register. ], width: 100%) The low 32 bits of a TB entry are its "value", indicating the page frame that the virtual page maps to. The upper 32 bits, *TBTAG*, are its "key", containing the "matching" *ASID* and the virtual page number mapped by the entry. Note that the low 32 bits form a preferred format for page table entries, hence the name of this control register. See @mmu for more information. The PTE bits are defined as follows when set: #set align(center) #tablex( columns: (auto, auto), align: horizon, cellx([ #set text(fill: white) #set align(center) ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *Function* ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *V* ], fill: rgb(0,0,0,255)), "The translation is valid. If this bit is clear, accesses within the page will result in the appropriate page fault exception.", cellx([ #set text(fill: white) #set align(center) *W* ], fill: rgb(0,0,0,255)), [The page is writable. If this bit is clear, any write within the page will result in a *PFW* (Page Fault Write) exception.], cellx([ #set text(fill: white) #set align(center) *K* ], fill: rgb(0,0,0,255)), "The page may only be accessed while the processor is in kernel mode. Accesses from user mode will result in the appropriate page fault exception.", cellx([ #set text(fill: white) #set align(center) *N* ], fill: rgb(0,0,0,255)), "Accesses within this page should bypass the caches and go directly to the bus. This is most useful for memory-mapped IO.", cellx([ #set text(fill: white) #set align(center) *G* ], fill: rgb(0,0,0,255)), [This translation is global; the virtual page number will match this entry, regardless of the current *ASID*.], ) #set align(left) #box([ === ITBTAG/DTBTAG <tbtag> _Translation Buffer Tag_ #image("tbtag.png", fit: "stretch") The *ITBTAG* and *DTBTAG* control registers contain the current *ASID* (Address Space ID), and the last virtual page number that incurred a TB miss. This control register also doubles as the uppermost 32 bits of the entry that is written to the TB when a write occurs to the *ITBPTE* or *DTBPTE* control register (see @tbpte and @tbmiss). ], width: 100%) #box([ === ITBINDEX/DTBINDEX <tbindex> _Translation Buffer Index_ The *ITBINDEX* and *DTBINDEX* control registers contain the next replacement index for the ITB and DTB, respectively. See @tbmiss for more information. ], width: 100%) #box([ === ITBCTRL/DTBCTRL <tbctrl> _Translation Buffer Control_ #image("tbctrl.png", fit: "stretch") Writes to *ITBCTRL* and *DTBCTRL* can be used to invalidate entries in the ITB or DTB, respectively. The 32-bit value written to the control register should be in one of the three formats enumerated above, distinguished by the low two bits. Any other combination of low bits will yield unpredictable results. The action of each format is as follows: ], width: 100%) #set align(center) #tablex( columns: (auto, auto), align: horizon, cellx([ #set text(fill: white) #set align(center) ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *Function* ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *11* ], fill: rgb(0,0,0,255)), [Every entry in the TB is cleared, including entries with the *G* bit set. Note that in general, this should not be done while virtual address translation is enabled, as this may clear wired entries like the exception block, and any TB miss taken will then be fatal.], cellx([ #set text(fill: white) #set align(center) *10* ], fill: rgb(0,0,0,255)), [Clear all non-wired private entries from the TB, i.e., non-wired entries with the *G* bit clear.], cellx([ #set text(fill: white) #set align(center) *01* ], fill: rgb(0,0,0,255)), [Clear all non-wired entries from the TB, including global entries.], cellx([ #set text(fill: white) #set align(center) *00* ], fill: rgb(0,0,0,255)), [Clear all TB entries that map the given virtual address. *ASIDs* are ignored; if there are multiple TB entries with the same virtual address but different *ASIDs*, they will all be cleared.], ) #set align(left) Note that reads from these control registers yield unpredictable (non-useful!) results. If one wishes to determine the size of the ITB or DTB, they can set *ITBINDEX* or *DTBINDEX* to zero, and write values to *ITBPTE* or *DTBPTE* until they see the replacement index wrap. The last value of the replacement index before it wraps, plus one, is the size of that TB. #box([ === ICACHECTRL/DCACHECTRL <cachectrl> _Cache Control_ #image("cachectrl.png", fit: "stretch") Reads from the *ICACHECTRL* and *DCACHECTRL* control registers yield a 32-bit value whose bit fields indicate the parameters of the Icache and Dcache respectively; the number of lines in the cache, the number of ways (i.e. the set associativity) of the cache, and the size of a cache line are each given, in the form of a binary logarithm. I.e., if the line count field contains 8, then there are $2^8 = 256$ lines in the cache. ], width: 100%) Writes to the *ICACHECTRL* and *DCACHECTRL* control registers cause various invalidations to occur. The 32-bit value written to the control register should be in one of the two formats enumerated above, distinguished by the low two bits. Any other combination of low bits will yield unpredictable results. The action of each format is as follows: #set align(center) #tablex( columns: (auto, auto), align: horizon, cellx([ #set text(fill: white) #set align(center) ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *Function* ], fill: rgb(0,0,0,255)), cellx([ #set text(fill: white) #set align(center) *11* ], fill: rgb(0,0,0,255)), [Every line in the cache is invalidated. This is useful for, for example, keeping the Icache coherent after things like dynamic linking that modify the instruction stream in ways that are hard to predict.], cellx([ #set text(fill: white) #set align(center) *10* ], fill: rgb(0,0,0,255)), [Every line in the cache that is logically within the given page frame is invalidated. This is useful for, for example, keeping coherency within the Dcache after a DMA operation.], ) #set align(left) #box([ === ITBADDR/DTBADDR _Translation Buffer Miss, Page Table Entry Address_ #image("tbaddr.png", fit: "stretch") The *ITBADDR* and *DTBADDR* control registers exist solely for the benefit of TB miss routines, and serve no other functional purpose. When a TB miss exception is taken, this control register is filled with the virtual address of the PTE to load from the virtually linear page table, saving a TB miss handler that implements this scheme from having to calculate this itself. System software should write the upper 10 bits of this control register with the upper 10 bits of the virtual address of a virtually linear page table. As this scheme has no way to handle a page table base containing non-zero bits in the low 22 bits, the page table base should be naturally aligned to the size of the page table, i.e. $2^22$ = 4MB-aligned. When a TB miss exception occurs, the low 22 bits of this control register are filled by the processor with the index at which the relevant PTE can be found within the virtually linear page table. As the page table is a linear array, this index is trivial to calculate; it consists simply of the upper 20 bits of the missed virtual address. The TB miss routine can load this control register into a general purpose register and use the contents as a virtual address with which to load the 32-bit PTE directly from the virtually linear page table. If the table page happens to be resident in the DTB already, this will succeed immediately. Otherwise, a nested DTB miss may be taken. See @tbmiss for more details. ], width: 100%) == NMI Masking Events A problem with non-maskable interrupts (NMIs) arises on RISC architectures. If an NMI is delivered while an exception handler is saving or restoring critical state, then this can be a fatal condition. Therefore, in order to maximize the usefulness of NMIs, the XR/17032 architecture specifies several events which delay NMI delivery for at least 64 cycles. Each occurrence of one of these events resets an internal counter that decrements once per cycle, and NMIs can only be delivered while this counter is equivalent to zero. The following events mask NMIs for a short period of at least 64 cycles: 1. An exception is taken. 2. The *MTCR* instruction is executed. 3. The *MFCR* instruction is executed.
https://github.com/LuminolT/SHU-Bachelor-Thesis-Typst
https://raw.githubusercontent.com/LuminolT/SHU-Bachelor-Thesis-Typst/main/template/template.typ
typst
#import "../body/info.typ" : * #import "font.typ" : * #import "toc.typ" : * #import "body.typ" : * #let Thesis( // 参考文献bib文件路径 body, ) = { set page(paper: "a4", margin: ( top: 2.54cm, bottom: 2.54cm, left: 2.5cm, right: 2cm), ) // 封面 include "cover.typ" // 目录 toc() // 置计数器 counter(page).update(1) // 摘要 include "abstract.typ" show_body(body) include "reference.typ" // 支持的引文格式:"apa", "chicago-author-date", "ieee", or "mla" // [] TODO: DIY 国标引文格式 }
https://github.com/maantjemol/Aantekeningen-Jaar-2
https://raw.githubusercontent.com/maantjemol/Aantekeningen-Jaar-2/main/Entrepreneurship/aantekeningen.typ
typst
#import "../template/lapreprint.typ": template #import "../template/frontmatter.typ": loadFrontmatter #import "@preview/drafting:0.2.0": * #import "@preview/cetz:0.2.2" #let default-rect(stroke: none, fill: none, width: 0pt, content) = { pad(left:width*(1 - marginRatio), rect(width: width*marginRatio, stroke: stroke)[ #content ]) } #let defaultColor = rgb("#2d75f2") #let caution-rect = rect.with(inset: 1em, radius: 0.5em, fill: defaultColor.lighten(96%), width:100%, stroke: defaultColor.lighten(80%)) #let note = (content) => inline-note(rect: caution-rect, stroke: defaultColor.lighten(60%))[#content] #show: template.with( title: "Entrepreneurship", subtitle: "Samenvatting", short-title: "IBIA Samenvatting", venue: [ar#text(fill: red.darken(20%))[X]iv], // This is relative to the template file // When importing normally, you should be able to use it relative to this file. theme: defaultColor, authors: ( ( name: "<NAME> . ", ), ), kind: "Samenvatting", abstract: ( (title: "Samenvatting", content: [#lorem(100)]), ), open-access: true, margin: ( ( title: "", content: [ ], ), ), font-face: "Open Sans" ) #set page( margin: (left: 1in, right: 1in), paper: "a4" ) #let marginRatio = 0.8 #let default-rect(stroke: none, fill: none, width: 0pt, content) = { pad(left:width*(1 - marginRatio), rect(width: width*marginRatio, stroke: stroke)[ #content ]) } #set-page-properties() #show terms: it => [ #note[#text(defaultColor, weight: 600, size: 10pt)[#it.children.first().term]\ #it.children.first().description] ] #set heading(numbering: none) #show heading: set text(defaultColor, weight: "medium") // Week 1 = Entrepreneurship and ideas Firms or businesses come from *entrepreneurs*. They play an essential role in making the decisions. An entrepreneur is important at the *start* and *throughout* the lifecycle of a businesses. Entrepreneurship creates *economic value*, *jobs* and *societal change or value*. == The starting point Entrepreneurship starts with *ideas*. Ideas start with a problem question. Things that frustrate me or people. The next step is to try to solve this problem. A process that helps with this is the *design thinking process*. This process consists of 6 steps: - Empathize (conduct interviews) - Define (reframe and create human-centered problem statements) - Ideate (brainstorm) - Prototype (create a low-fidelity prototype) - Test (test the prototype to gather data) - Assess (gather feedback and iterate) #figure( caption: "Design thinking process", )[#image("./images/ideate.png", width: 80%)] The best startups come from the bad experiences of the founders. The best ideas come from the *problems* that you have. === Change: The main source of opportunity is change. We can use *PESTEL* analysis to identify changes in the environment. PESTEL stands for: - Political change - Economic change - Social change - Technological change - Environmental change - Legal change / How can you source ideas?: #text[ *Consumers* - (In)formally monitor potential ideas and needs among consumers - Let consumers express their opinions (what do they want/need?) *Existing products and services* - Formally monitor and evaluate competitive products and services on the market - Uncovering ways to improve current products - Entrepreneurship is a response to opportunities created but not exploited by the incumbent firms *Files from the Patent Office*: - in response to government regulations - research and development ] === Trends: How might we enhance/create/improve/expand/grow/develop/innovate/transform? - How might we improve how the elderly live independently? - How might we redesign how adults learn in virtual worlds? == The next step: === Filtering ideas: We have a lot of ideas. We want to go from ideas to entrepreneurial opportunities. We need to think about: *Me* (am i ready for the idea), *Market* (is the rest ready for the idea) and *Money* (is it feasible). *Not all ideas are entrepreneurial opportunities*. Ideas must be: - *Novel:* The idea is new and has not been done before - *Value:* The idea provides value to the customer - *Unmet needs:* The idea meets unmet needs An opportunity must be: - *Desirable:* The idea is desirable - *Feasible:* The idea is feasible - *Viable:* The idea is viable // Week 4 = Founders dilemmas: == When to found? (career dilemma) #table(columns: (auto, auto, auto), [], [*Now*], [*Later*], [🟢], [ + Catch the right window + Knowledge of the present + Time to scale (already have some prototype and let people test your prototype to gather feedback) ], [ + More resources + Pick your timing + More experience ], [🔴], [ + ], [ + Duplication of your idea + More to lose + Endless loop of overthinking ] ) #figure( caption: "When to found?", )[] == Found solo or team? *Team:* - More human capital Overlap in experience is common. Trust and other soft factors are at least as important. Team cohesion is important. Overlap in soft factors can be good.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/shift_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set underline(stroke: 0.5pt, offset: 0.15em) #underline[The claim#super[\[4\]]] has been disputed. \ The claim#super[#underline[\[4\]]] has been disputed. \ It really has been#super(box(text(baseline: 0pt, underline[\[4\]]))) \
https://github.com/kajiLabTeam/ipsj-national-convention-typst-template
https://raw.githubusercontent.com/kajiLabTeam/ipsj-national-convention-typst-template/main/template/functinos.typ
typst
#let spacer(size: 0pt) = par(text(size: size, "")) #let tbl(tbl, caption: "") = { figure( tbl, caption: caption, supplement: [表], kind: "table", ) } #let img(img, caption: "") = { figure( img, caption: caption, supplement: [図], kind: "image", ) }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/container-03.typ
typst
Other
// Test fr box. Hello #box(width: 1fr, rect(height: 0.7em, width: 100%)) World
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/type_check/annotation_fn2.typ
typst
Apache License 2.0
/// #let fn = `(..args) => any`; /// /// - fn (function, fn): The `fn`. /// - args (any): The `args`. #let fn-wrapper(fn, ..args) = none
https://github.com/JunzheShen/SJTU-Resume-Template-in-Typst
https://raw.githubusercontent.com/JunzheShen/SJTU-Resume-Template-in-Typst/main/resume.typ
typst
#import "template.typ": * // 设置图标, 来源: https://fontawesome.com/icons/ // 如果要修改图标颜色, 请手动修改 svg 文件中的 fill="rgb(38, 38, 125)" 属性 #let faAward = icon("fa-award.svg") #let faCode = icon("fa-code.svg") #let faGraduationCap = icon("fa-graduation-cap.svg") #let faWrench = icon("fa-wrench.svg") #let faCompass = icon("fa-compass.svg") // 主题颜色 #let themeColor = rgb(23, 95, 139) // 个人信息 #let info = ( name: "", school: "", major: "", phone: "", email: "", wechat: "", ) // 设置简历选项与头部 #show: resume.with( // 字体基准大小 size: 10pt, // 标题颜色 themeColor: themeColor, info:info, photo_path:none ) == #faGraduationCap 小标题 == #faCode 小标题 == #faAward 小标题 == #faCompass 小标题
https://github.com/jneug/schule-typst
https://raw.githubusercontent.com/jneug/schule-typst/main/src/api/typo.typ
typst
MIT License
// TODO: Refactorings // ================================ // = Typographic enhancements = // ================================ #import "@preview/unify:0.6.0" #import "../util/typst.typ" #import "../util/args.typ" #import "../util/util.typ" #import "../theme.typ" // ============================ // Text scaling // ============================ /// Skalierter text. /// - #shortex(`#scaled[Hallo Welt.]`) /// - #shortex(`#scaled(factor:.5)[Hallo Welt.]`) /// - #shortex(`#scaled("Hallo Welt.", factor:120%)`) /// /// - content (string, content): Zu skalierender Text. /// - factor (float, ratio): Der Skalierungsfaktor. #let scaled(content, factor: 0.8) = text(factor * 1em, content) /// Kleiner text. /// - #shortex(`#small[#lorem(5)]`) /// - #shortex(`#small(lorem(5))`) /// /// - content (string, content): Zu skalierender Text. #let small(content) = scaled(content, factor: 0.88) /// Großer text. /// - #shortex(`#large[#lorem(5)]`) /// - #shortex(`#large(lorem(5))`) /// /// - content (string, content): Zu skalierender Text. #let large(content) = scaled(content, factor: 1.2) // ============================ // New text decorations // ============================ /// === Neue Textauszeichnungen /// Doppelte Unterstreichung. /// - #shortex(`#uunderline[#lorem(5)]`) /// - #shortex(`#uunderline(lorem(5), stroke:2pt+red, offset:2pt, distance: 1pt)`) /// /// - stroke (stroke): Linienstil für die Unterstreichung. /// - offset (length): Abstand der oberen Linie zum Text. /// - distance (length): Abstand der unteren Linie zur oberen Linien. /// - extent (length): #arg[extent] vonn #cmd-[underline]. /// - evade (length): #arg[evade] vonn #cmd-[underline]. /// - body (string, content): Zu unterstreichender Text. #let uunderline( stroke: auto, offset: auto, distance: auto, extent: 0pt, evade: true, body, ) = { let thickness = args.if-auto(.0416em, stroke, do: s => typst.stroke(s).thickness) distance = args.if-auto(.25em, distance) underline( stroke: stroke, offset: def.if-auto(0pt, offset) + thickness + distance, extent: extent, evade: evade, underline( stroke: stroke, offset: offset, extent: extent, evade: evade, body, ), ) } /// Zickzack Unterstreichung. /// - #shortex(`#squiggly[#lorem(5)]`) /// - #shortex(`#squiggly(lorem(5), stroke:2pt+red, offset: 4pt, amp:2, period: 2)`) /// /// - stroke (stroke): Linienstil für die Unterstreichung. /// - body (string, content): Zu unterstreichender Text. #let squiggly( stroke: 1pt + black, offset: 0pt, amp: 1, period: 1, body, ) = { amp *= .5 style(styles => { let m = measure(body, styles) let step = 2pt * period let i = 1 box(width: m.width, clip: false, baseline: -1 * m.height)[ #move( dy: m.height + 0.25em, while i * step < m.width { place( top + left, dy: offset, line( stroke: stroke, start: ((i - 1) * step, -amp * step), end: (i * step, amp * step), ), ) place( top + left, dy: offset, line( stroke: stroke, start: (i * step, amp * step), end: ((i + 1) * step, -amp * step), ), ) i += 2 }, ) #place(top + left, body) ] }) } /// Textabschnitt hervorheben (ersetzt #doc("text/highlight")). /// - #shortex(`#highlight[#lorem(5)]`) /// /// - color (color): Farbe der Hervorhebung. /// - body (string, content): Hervorzuhebender Inhalt. /// -> content #let highlight(body, color: yellow) = box(fill: color, inset: (x: 0.2em), outset: (y: 0.2em), radius: 0.1em, body) // ============================ // Text highlights // ============================ // German number format for integers / floats // - #shortex(`#num(2.3)`) #let num = unify.num // SI units // - #shortex(`#si(3.5, $m^3$)`) #let si(value, unit) = [#num(value)#h(0.2em)#unit]
https://github.com/ralphmb/My-Dissertation
https://raw.githubusercontent.com/ralphmb/My-Dissertation/main/sections/appendix.typ
typst
Creative Commons Zero v1.0 Universal
#let c = counter("appendix") #let appendix(it) = block[ #c.step() #heading([Appendix #c.display("1"): #it], numbering: none, outlined:false) ] #set par(first-line-indent: 0pt) #show table: set text(7pt) #show table: set align(center) Blank/commented lines have been automatically removed from each script. This makes it a bit harder to read but saves about 20 pages. #appendix([Weibull model selection]) R output for model selection in survival analysis section. `hyptester` is a custom function for easier to read significance tests.\ #raw(read("../assets/misc/r_output.txt"), lang:"R") #appendix([Data Prep]) Code for data preparation. \ #raw(read("../assets/code/code/data_prep.R"), lang:"R") #appendix([Exploratory]) Code for exploratory analysis. \ #raw(read("../assets/code/code/exploratory.R"), lang:"R") #appendix([Logistic Regression]) Code for logistic regression. \ #raw(read("../assets/code/code/glm.R"), lang:"R") #appendix([Survival Analysis]) Code for survival analysis. \ #raw(read("../assets/code/code/survival.R"), lang:"R") #set page(columns: 2) #set text(9pt) #appendix([Bradley Terry models]) Unfinished section on Bradley Terry models. Due to a different approach and a few errors this was written under the impression that the logistic regression portion of this thesis was much less fruitful.\ #include("../other/bradleyterry.typ") #set page(columns: 1) #set text(7pt) #appendix([Miscellaneous Scripts]) Python script used for parsing text copied from the Mirror into valid R code defining the columns of a data frame. \ #raw(read("../assets/code/code/derbies/siteparser.py"),lang:"Python") Python script for converting R output from `summary()` into Typst tables.\ #raw(read("../assets/code/tablemaker.py"), lang:"Python") Almost automated backups of all project files to Google Drive.\ #raw(read("../assets/code/committer"), lang: "zsh") Word counter for source files, since it can be annoying to word count pdf files.\ #raw(read("../assets/code/wordcounter"), lang: "zsh") #appendix([Diary of work]) #raw(read("../assets/misc/DIARY.md"))
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/components/title.typ
typst
#let title = [ #set block(below: .3em) #set par(leading: .3em) #set text(font: "Noto Serif", size: 40pt, weight: 100) #stack(dir: ltr, spacing: 4pt, [<NAME>], h(1fr), image("../assets/cc.svg", width: 16pt), image("../assets/cc0.svg", width: 16pt), ) #text(weight: 900)[Algorithmen und \ Datenstrukturen] \ ]
https://github.com/Dav1com/resume
https://raw.githubusercontent.com/Dav1com/resume/main/metadata.typ
typst
Apache License 2.0
// NOTICE: Copy this file to your root folder. /* Personal Information */ #let firstName = "David" #let lastName = "Ibáñez" #let personalInfo = ( github: "Dav1com", phone: "+569 82137345", email: "<EMAIL>", location: "Santiago, Chile", //linkedin: "johndoe", //gitlab: "mintyfrankie", //homepage: "jd.me.org", //orcid: "0000-0000-0000-0000", //researchgate: "John-Doe", //extraInfo: [], ) /* Language-specific */ // Add your own languages while the keys must match the varLanguage variable #let headerQuoteInternational = ( "": [23 years old student of Engineering in Computer Science at University of Chile, and self-taught developer, is looking for an intership starting in January. Zealous about software engineering from an early age, currently interested in software development, static analysis, proof assistants and education.], "en": [Experienced Data Analyst looking for a full time job starting from now], "es": [] ) #let cvFooterInternational = ( "": "Curriculum vitae", "en": "Curriculum vitae", "es": "Curriculum vitae" ) #let letterFooterInternational = ( "": "Cover Letter", "en": "Cover Letter", "es": "Carta de Motivación" ) #let nonLatinOverwriteInfo = ( "customFont": "Heiti SC", "firstName": "王道尔", "lastName": "", // submit an issue if you think other variables should be in this array ) /* Layout Setting */ #let awesomeColor = "nephritis" // Optional: skyblue, red, nephritis, concrete, darknight #let profilePhoto = "../src/avatar.png" // Leave blank if profil photo is not needed #let varLanguage = "" // INFO: value must matches folder suffix; i.e "zh" -> "./modules_zh" #let varEntrySocietyFirst = false // Decide if you want to put your company in bold or your position in bold #let varDisplayLogo = true // Decide if you want to display organisation logo or not
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/call-09.typ
typst
Other
// Error: 8 expected closing paren #{func(}
https://github.com/profetia/me
https://raw.githubusercontent.com/profetia/me/main/src/bin/cv.typ
typst
#show heading: set text(font: "Linux Biolinum") #show link: underline // Uncomment the following lines to adjust the size of text // The recommend resume text size is from `10pt` to `12pt` // #set text( // size: 12pt, // ) // Feel free to change the margin below to best fit your own CV #set page( margin: (x: 0.9cm, y: 1.3cm), ) // For more customizable options, please refer to official reference: https://typst.app/docs/reference/ #set par(justify: true) #let chiline() = {v(-3pt); line(length: 100%); v(-5pt)} #let today = datetime.today() = <NAME> <EMAIL> | #link("https://github.com/profetia")[github.com/profetia] #h(1fr) Last Updated: #today.display("[year]/[month]") == Education #chiline() *ShanghaiTech University* #h(1fr) 2021/09 -- present \ Bachelor of Engineering in Computer Science and Technology #h(1fr) Shanghai, China \ - Overall GPA 3.72/4.0, Rank 25/178 (15%), Major GPA 3.83/4.0 // TODO: Computer Architecture maybe removed - Relevant Courses: Algorithm and Data Structure (A), /*Computer Architecture (A+), */ Computer Networks (A+), Operating System (A+),\ #h(83pt) Software Engineering (A), Deep Learning (A+), Computer Aided Verification (A+) // - Standardized Test: // - TOFEL: 112 (Reading 30 + Listening 30 + Speaking 24 + Writing 28) == Publications #chiline() - *Understanding Hybrid Scheduling in Asymmetric Processors* #h(1fr) \ _<NAME>, *<NAME>*, <NAME>_ #h(1fr) \ *Under Review in _IEEE International Symposium on High-Performance Computer Architecture 2025_* - *pyUPPAAL: A Python Package for Risk Analysis of CPS* #link("https://dl.acm.org/doi/abs/10.1145/3576841.3589611")[doi.org/10.1145/3576841.3589611] #h(1fr) \ _<NAME>, *<NAME>*, <NAME>, <NAME>, <NAME>_ #h(1fr) \ *Published in _ACM/IEEE International Conference on Cyber-Physical Systems 2023_* == Research Experience #chiline() *Max Planck Institute for Informatics, Network and Cloud System Group* #h(1fr) 2024/09 -- 2024/11 \ Research Intern, Advised by *Prof. <NAME>* #h(1fr) Saarbrücken, Germany \ - * OpenOptics: An Open Framework for Optical Data Center Networks * // - Modified `libvma` to implement virtual output queues and perform demand estimation on elephant flows. - Built a realistic end-to-end evaluation platform for traffic-aware schedulers in DCN with Intel Tofino programmable switches, enabling reliable comparisons between scheduling algorithms such as c-Through and Mordia. *ShanghaiTech University, Wireless and Mobile System Lab* #h(1fr) 2023/12 -- 2024/08 \ Research Intern, Advised by *Prof. <NAME>* #h(1fr) Shanghai, China \ - *Understanding Hybrid Scheduling in Asymmetric Processors* - Identified a bottleneck scenario with eBPF-intensive workloads, common in malware analysis, for the Linux's CFS and demonstrated the effectiveness of ITD updates in kernel space for the proposed ITD-guided scheduler. - Provided a comprehensive performance benchmark of the proposed scheduler on virtualization related and other kernel-heavy workloads. // TODO: Replace with an official title if needed - *Exploitation of Vulnerabilities in a Popular Commodity LIDAR Model* - Evaluated the robustness of existing attack methods on newer models of LIDAR, proving their ineffectiveness. - Built an adversarial device effectively replicating a malfunction of a widely-used commodity LIDAR model and used it to explore possible attack methods exploiting this vulnerability. - *Understanding Precision Time Protocol in Embedded Systems: A Measurement Study* - Migrated the Precision Time Protocol (PTP) to Bluetooth Low Energy (BLE) on embedded systems by emulating hardware PTP clock with specific counters. - Implemented a synchronized sound recording system across 20 devices to demonstrate the capabilities of our method. *ShanghaiTech University, Human-Cyber-Physical System Lab* #h(1fr) 2022/07 -- 2023/06 \ Research Intern, Advised by *Prof. <NAME>* #h(1fr) Shanghai, China \ - *Model-Checking-Based Diagnosis Assistance for Cardiac Ablation* - Built a Python toolkit to work with UPPAAL with implementation of common use cases and algorithms in CPS. - Implemented and optimized a novel model-checking based cardiac diagnoser to achieve real-time analysis and diagnosis on cardiac electrical signals. // - Deployed a Kubernetes cluster to manage applications of HCPS Lab, providing TLS certificate automation, persistent volumes and load balancers. == Work Experience #chiline() *Tencent, Keen Security Lab* #h(1fr) 2024/04 -- 2024/07 \ System R&D Intern, Tactic Intelligence Team #h(1fr) Shanghai, China - Recreated the Linux sandbox for malware analysis by upgrading the kernel and utilizing new kernel features. - Extended the dynamic observation and analysis capabilities of the Linux sandbox using customized probing tools in eBPF and kernel modules. // - Extended dynamic analysis capabilities of the Linux sandbox with customized probing tools in eBPF and kernel modules. - Streamlined the gRPC endpoint for the malware database and rewrote the log parser with PEG. *Deemos Technologies* #h(1fr) 2023/01 -- 2023/07 \ Software Engineer Intern #h(1fr) Shanghai, China \ - Developed an interactive avatar system based on ChatAvatar, a text to 3D model, at Global AI developer Conference 2023. - Designed and implemented a Blender tool to reshape and adjust cloth mesh according to human models. == Activities #chiline() *ISC'24 Student Cluster Competition* #h(1fr) 2024/03 -- 2024/04 \ Team Leader #h(1fr) // Shanghai, China - Responsible for implementing GPU offloading and code optimization for microphysics, a climate simulation application derived from the ICON model, achieving strong scaling on CPU and more 200x speedup on GPU. - Guided the team on MPI profiling and optimization, reducing the time spend on communication by 50%. *Geekpie Association* #h(1fr) 2022/08 -- 2023/07 \ Vice President #h(1fr) // Shanghai, China \ - Developed the frontend of Coursebench, a popular course rating platform at ShanghaiTech University. - Organized events including Geekpie Games and Geekpie Linux Seminar, with more than 1k students participated. *School of Information Science and Technology* #h(1fr) 2023/02 -- 2023/06 \ Teaching Assistant #h(1fr) // Shanghai, China \ - CS100: Computer Programming, ShanghaiTech University - CS132: Software Engineering, ShanghaiTech University // *Office of Environment, Health and Safety* #h(1fr) 2022/09 -- 2022/11 \ // Assistant Manager #h(1fr) // Shanghai, China // \ == Projects #chiline() *Rathernet* #link("https://github.com/profetia/rathernet")[github.com/profetia/rathernet] #h(1fr) 2023/09 -- 2023/10 \ An acoustic userspace network stack written in Rust #h(1fr) // #lorem(2) \ - Implemented all five layers in the OSI model from bottom to up with acoustic wave as the carrier. // - Utilized existing Rust asynchronous infrastructures and avoided manual control of scheduling and synchronization. - Created a customized network address translation, achieving bidirectional interaction with the Internet. - Integrated into the operating system effortlessly, supporting common transportation and application protocols. *Pintos* #link("https://github.com/profetia/pintos")[github.com/profetia/pintos] #h(1fr) 2023/08 -- 2023/09 \ An education oriented operating system from Stanford #h(1fr) // #lorem(2) \ - Implemented core components of an operating system: kernel threads, user programs, virtual memory and file system. *BusTub* #h(1fr) 2023/11 -- 2023/12 \ A relational database management system from CMU implemented in C++ #h(1fr) // #lorem(2) \ - Completed core functions of a DBMS including storage management, indexing, query execution and concurrency control. *LBM* #link("https://github.com/winlere/lbm")[github.com/winlere/lbm] #h(1fr) 2023/04 -- 2023/05 \ An optimized numerical simulation of Computational Fluid Dynamics #h(1fr) // #lorem(2) \ - Optimized the simulation with techniques including OpenMP parallelization, SIMD vectorization, memory alignment, cache blocking and software pipelining. - Achieved 20x speed up compared to the baseline on Intel Xeon E5-2698 v4 processor (20 cores). == Awards #chiline() - Rank 9/29 (5/29 for my part on microphysics), ISC'24 Student Cluster Competition #h(1fr) 2024/04 - Outstanding Teaching Assistant, ShanghaiTech University #h(1fr) 2023/06 // - Silver Award, ICPC China Silk Road National Invitational 2023 #h(1fr) 2023/05 - Merit Student (Rank 3%-7%), ShanghaiTech University #h(1fr) 2022/10 - Level 6, the 2019 Certified Software Professional Senior Track (formerly NOIP) #h(1fr) 2019/12 == Skills #chiline() *Linguistic Proficiency*: Chinese (Native), English (Advanced, TOEFL 112: R30/L30/S24/W28) \ *Programming Languages*: Python, C, C++, Rust, Golang, Typescript, Shell, SQL \ *Tools and Frameworks*: PyTorch, OpenMP, MPI, CUDA, Linux Kernel, eBPF, UPPAAL, Dafny, Blender \ *DevOps Technologies*: Kubernetes, Docker, Gitlab, Postgres, Cloudflare Worker
https://github.com/FkHiroki/ex-D2
https://raw.githubusercontent.com/FkHiroki/ex-D2/main/docs/native-install.md
markdown
MIT No Attribution
# ローカル環境構築 ## コマンドによるインストール Typst のインストール方法は,[Typst の GitHubページ](https://github.com/typst/typst) にある通りですが,以下の 3 つのパターンが簡単かと思われます. ### Windows PowerShell を開き以下のコマンドを入力する. ```powershell winget install --id Typst.Typst ``` `winget` コマンドが有効でない場合には,Microsoft Store から [アプリインストーラー](https://apps.microsoft.com/detail/9nblggh4nns1) をインストールすると使えるようになります. ### Mac [Homebrew](https://brew.sh/ja/) を導入して,以下のコマンドを入力する. ```sh brew install typst ``` [このページ](https://brew.sh/ja/) の通りですが,Homebrew のインストールは以下のコマンドで行えます. ```sh /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` ### Rust を通してインストール Ubuntu の場合などはこの方法をオススメします. [Rust](https://www.rust-lang.org/ja/tools/install) をインストールして,以下のコマンドを入力する. ```sh cargo install --git https://github.com/typst/typst --locked typst-cli ``` [このページ](https://www.rust-lang.org/ja/tools/install) の通りですが,Rust のインストールは以下のコマンドで行えます. ```sh curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` ## コマンドによるコンパイル 1. [Typst](https://typst.app/) をインストール. 2. 解凍したフォルダーの `main.typ` を編集. 3. PowerShell やターミナルで `main.typ` のあるディレクトリに移り,以下のコマンドで `main.pdf` を生成. ``` typst compile main.typ ```
https://github.com/asmund20/typst-packages
https://raw.githubusercontent.com/asmund20/typst-packages/main/local/rapport/1.0.0/main.typ
typst
#let rapport(title: "", authors: (), date: datetime.today().display("[day].[month].[year]"), language: "en", include_outline: false, abstract: none, body) = { // Set the document's basic properties. set document(author: authors, title: title) set page(numbering: "1", number-align: center) set text(font: "Source Sans Pro", lang: language) show figure.where(kind: table): set figure.caption(position: top) // Title row. align(center)[ #block(text(weight: 700, 1.75em, title)) #v(1em, weak: true) #date ] // Author information. pad( top: 0.5em, bottom: 0.5em, x: 2em, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(center, strong(author))), ), ) set par(justify: true) if abstract != none { align(center)[ #block(width: 80%, [#text(weight: 700, 1.1em, "Abstract")\ #abstract]) ] } if include_outline [ #outline(indent: auto) ] // Main body. body }
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/documentation/docs/about.md
markdown
# TypstDiff tool ## Introduction TypstDiff is a tool to compare two documents with Typst extention. Our tool takes two documents and marks changes made in both documents. Styling of those changes can be set by user (more info in user guide). TypstDiff marks: * **insertions** - underlining inserted elements and putting on extra styling if specified by user * **deletions** - striking out deleted elements and putting on extra styling if specified by user * **updates** - adding old version of element to output file with strikeout and extra formating and new version of element to output file with underlining and extra formating from user. Due to Typst tool being relatively new our project does not support some particular features and elements of Typst documents. List of supported elements can be found on this page. ## TypstDiff processing In the process of checking files for changes TypstDiff uses three main tools: * **Pandoc** - for converting files from Typst to JSON format and back - Pandoc started supporting Typst extention only recently so a lot of features and typst elements are not converted properly - this is the reason for most of restriction in our tool. With newer versions of Pandoc, TypstDiff will probably also support more and more Typst features. * **jsondiff** - for finding changes in both files - in some cases jsondiff marks changes in hard to predict way. For example adding element to the first element of a list will be marked as updating all elements till the last one, and last one will be marked as inserted. You must take this into consideration while using TypstDiff. ## Some types of typst structures supported by TypstDiff for now * bullet_list * code * display_math * emph * header * inline_math * line_break * link * ordered_list * quoted * space * str * strong * sub_script * super_script * image * quote * cite * para * div * math
https://github.com/typst-jp/typst-jp.github.io
https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/docs/reference/syntax.md
markdown
Apache License 2.0
--- description: | Typstの構文に関するコンパクトなリファレンスです。詳細については、言語のマークアップモード、数式モード、およびコードモードを参照してください。 --- # 構文 Typstはマークアップ言語です。 これは、シンプルな構文を使用して一般的なレイアウトタスクを簡単に行えるということです。 Typstの軽量なマークアップ構文は、文書を簡単かつ自動的にスタイリングできるsetルールとshowルールによって補完されています。 これらすべては、組み込み関数およびユーザー定義関数を備えた、緊密に統合されたスクリプト言語によって支えられています。 ## モード { #modes } Typstには3種類の構文モードがあります。マークアップモード、数式モード、そしてコードモードです。 Typst文書では、マークアップモードがデフォルトであり、数式モードでは数式を書くことができ、コードモードではTypstのスクリプト機能を利用することができます。 以下の表を参照し、いつでも特定のモードに切り替えることができます。 | 新たなモード | 構文 | 例 | | ------------ | ---------------------------- | ------------------------------- | | コード | コードの前に`#`を付ける | `[Number: #(1 + 2)]` | | 数式 | 式を`[$..$]`で囲む | `[$-x$ is the opposite of $x$]` | | マークアップ | マークアップを`[[..]]`で囲む | `{let name = [*Typst!*]}` | 一度`#`でコードモードに入ると、途中でマークアップモードや数式モードに切り替えない限り、さらにハッシュを使う必要はありません。 ## マークアップ { #markup } Typstは、最も一般的な文書要素に対する組み込みのマークアップを提供します。 ほとんどの構文要素は、対応する関数のショートカットに過ぎません。 以下の表は、利用可能なすべてのマークアップと、その構文と使用法について詳しく学ぶための最適なページへのリンクを示しています。 | 名称 | 例 | 参照 | | ---------------- | ------------------------ | ------------------------------------ | | 段落区切り | 空行 | [`parbreak`]($parbreak) | | 強調(太字) | `[*strong*]` | [`strong`]($strong) | | 強調(イタリック) | `[_emphasis_]` | [`emph`]($emph) | | rawテキスト | ``[`print(1)`]`` | [`raw`]($raw) | | リンク | `[https://typst.app/]` | [`link`]($link) | | ラベル | `[<intro>]` | [`label`]($label) | | 参照 | `[@intro]` | [`ref`]($ref) | | 見出し | `[= Heading]` | [`heading`]($heading) | | 箇条書きリスト | `[- item]` | [`list`]($list) | | 番号付きリスト | `[+ item]` | [`enum`]($enum) | | 用語リスト | `[/ Term: description]` | [`terms`]($terms) | | 数式 | `[$x^2$]` | [Math]($category/math) | | 改行 | `[\]` | [`linebreak`]($linebreak) | | スマートクオート | `['single' or "double"]` | [`smartquote`]($smartquote) | | 短縮記号 | `[~]`, `[---]` | [Symbols]($category/symbols/sym) | | コード構文 | `[#rect(width: 1cm)]` | [Scripting]($scripting/#expressions) | | 文字エスケープ | `[Tweet at us \#ad]` | [Below]($category/syntax/#escapes) | | コメント | `[/* block */]`, `[// line]` | [Below]($category/syntax/#comments) | ## 数式モード { #math } 数式モードは、数式を組版するために使用される特別なマークアップモードです。 数式を `[$]` の文字で囲むことによって、数式モードに入ることができます。 これはマークアップモードとコードモードの両方で機能します。 数式が少なくとも一つのスペースで始まり終わる場合、その数式は独自のブロックに組版されます(例:`[$ x^2 $]`)。 インライン数式は、スペースを省略することで作成できます(例:`[$x^2$]`)。 以下に、数式モードに特有の構文の概要を示します。 | 名称 | 例 | 参照 | | ----------------------- | ----------------------- | ------------------------------------ | | インライン数式 | `[$x^2$]` | [Math]($category/math) | | ブロック数式 | `[$ x^2 $]` | [Math]($category/math) | | 下付き添え字 | `[$x_1$]` | [`attach`]($category/math/attach) | | 上付き添え字 | `[$x^2$]` | [`attach`]($category/math/attach) | | 分数 | `[$1 + (a+b)/5$]` | [`frac`]($math.frac) | | 改行 | `[$x \ y$]` | [`linebreak`]($linebreak) | | 揃え位置 | `[$x &= 2 \ &= 3$]` | [Math]($category/math) | | 変数アクセス | `[$#x$, $pi$]` | [Math]($category/math) | | フィールドアクセス | `[$arrow.r.long$]` | [Scripting]($scripting/#fields) | | 暗黙の乗算 | `[$x y$]` | [Math]($category/math) | | 短縮記号 | `[$->$]`, `[$!=$]` | [Symbols]($category/symbols/sym) | | 数式内のテキスト/文字列 | `[$a "is natural"$]` | [Math]($category/math) | | 数式関数呼び出し | `[$floor(x)$]` | [Math]($category/math) | | コード構文 | `[$#rect(width: 1cm)$]` | [Scripting]($scripting/#expressions) | | 文字エスケープ | `[$x\^2$]` | [Below]($category/syntax/#escapes) | | コメント | `[$/* comment */$]` | [Below]($category/syntax/#comments) | ## コードモード { #code } コードブロックや式の中では、新しい式は先頭に`#`を付けずに始めることができます。 多くの構文要素は式に特有のものです。 以下に、コードモードで利用可能なすべての構文の一覧表を示します。 | 名称 | 例 | 参照 | | -------------------------- | ----------------------------- | ------------------------------------- | | none | `{none}` | [`none`]($reference/foundations/none) | | 自動 | `{auto}` | [`auto`]($reference/foundations/auto) | | ブール値 | `{false}`, `{true}` | [`bool`]($reference/foundations/bool) | | 整数 | `{10}`, `{0xff}` | [`int`]($reference/foundations/int) | | 浮動小数点数 | `{3.14}`, `{1e5}` | [`float`]($reference/foundations/float) | | 長さ | `{2pt}`, `{3mm}`, `{1em}`, .. | [`length`]($reference/layout/length) | | 角度 | `{90deg}`, `{1rad}` | [`angle`]($reference/layout/angle) | | 比率 | `{2fr}` | [`fraction`]($reference/layout/fraction) | | 割合 | `{50%}` | [`ratio`]($reference/layout/ratio) | | 文字列 | `{"hello"}` | [`str`]($reference/foundations/str) | | ラベル | `{<intro>}` | [`label`]($reference/foundations/label) | | 数式 | `[$x^2$]` | [Math]($category/math) | | rawテキスト | ``[`print(1)`]`` | [`raw`]($reference/text/raw) | | 変数アクセス | `{x}` | [Scripting]($scripting/#blocks) | | コードブロック | `{{ let x = 1; x + 2 }}` | [Scripting]($scripting/#blocks) | | コンテンツブロック | `{[*Hello*]}` | [Scripting]($scripting/#blocks) | | 括弧付き式 | `{(1 + 2)}` | [Scripting]($scripting/#blocks) | | 配列 | `{(1, 2, 3)}` | [Array]($type/$array) | | 辞書 | `{(a: "hi", b: 2)}` | [Dictionary]($type/$dictionary) | | 単項演算子 | `{-x}` | [Scripting]($scripting/#operators) | | 二項演算子 | `{x + y}` | [Scripting]($scripting/#operators) | | 代入 | `{x = 1}` | [Scripting]($scripting/#operators) | | フィールドアクセス | `{x.y}` | [Scripting]($scripting/#fields) | | メソッド呼び出し | `{x.flatten()}` | [Scripting]($scripting/#methods) | | 関数呼び出し | `{min(x, y)}` | [Function]($type/$function) | | 引数展開 | `{min(..nums)}` | [Arguments]($type/$arguments) | | 無名関数 | `{(x, y) => x + y}` | [Function]($type/$function) | | letバインディング | `{let x = 1}` | [Scripting]($scripting/#bindings) | | 名前付き関数 | `{let f(x) = 2 * x}` | [Function]($type/$function) | | setルール | `{set text(14pt)}` | [Styling]($styling/#set-rules) | | set-ifルール | `{set text(..) if .. }` | [Styling]($styling/#set-rules) | | show-setルール | `{show heading: set block(..)}` | [Styling]($styling/#show-rules) | | 関数付きshowルール | `{show raw: it => {..}}` | [Styling]($styling/#show-rules) | | show-everythingルール | `{show: template}` | [Styling]($styling/#show-rules) | | コンテキスト式 | `{context text.lang}` | [Context]($context) | | 条件式 | `{if x == 1 {..} else {..}}` | [Scripting]($scripting/#conditionals) | | forループ | `{for x in (1, 2, 3) {..}}` | [Scripting]($scripting/#loops) | | whileループ | `{while x < 10 {..}}` | [Scripting]($scripting/#loops) | | ループ制御フロー | `{break, continue}` | [Scripting]($scripting/#loops) | | 関数からのリターン | `{return x}` | [Function]($type/$function) | | モジュールをインクルード | `{include "bar.typ"}` | [Scripting]($scripting/#modules) | | モジュールをインポート | `{import "bar.typ"}` | [Scripting]($scripting/#modules) | | モジュールからのインポート | `{import "bar.typ": a, b, c}` | [Scripting]($scripting/#modules) | | コメント | `{/* block */}`, `{// line}` | [Below]($category/syntax/#comments) | ## コメント { #comments } コメントはTypstによって無視され、出力には含まれません。 これは古いバージョンを除外したり、注釈を追加したりするのに便利です。 単一行をコメントアウトするには、行の先頭に`//`を付けます。 ```example // our data barely supports // this claim We show with $p < 0.05$ that the difference is significant. ``` コメントは `/*` と `*/` で囲むこともできます。この場合、コメントを複数行にわたって書くことができます。 ```example Our study design is as follows: /* Somebody write this up: - 1000 participants. - 2x2 data design. */ ``` ## エスケープシーケンス { #escapes } エスケープシーケンスは、Typstで入力が難しい特殊文字や他に特別な意味を持つ文字を挿入するために使用されます。 文字をエスケープするには、バックスラッシュをその前に置きます。 任意のUnicodeコードポイントを挿入するためには、16進エスケープシーケンス(`[\u{1f600}]`)を使用できます。 このエスケープシーケンスは[文字列]($str)でも機能します。 ```example I got an ice cream for \$1.50! \u{1f600} ``` ## Paths Typst has various features that require a file path to reference external resources such as images, Typst files, or data files. Paths are represented as [strings]($str). There are two kinds of paths: Relative and absolute. - A **relative path** searches from the location of the Typst file where the feature is invoked. It is the default: ```typ #image("images/logo.png") ``` - An **absolute path** searches from the _root_ of the project. It starts with a leading `/`: ```typ #image("/assets/logo.png") ``` ### Project root By default, the project root is the parent directory of the main Typst file. For security reasons, you cannot read any files outside of the root directory. If you want to set a specific folder as the root of your project, you can use the CLI's `--root` flag. Make sure that the main file is contained in the folder's subtree! ```bash typst compile --root .. file.typ ``` In the web app, the project itself is the root directory. You can always read all files within it, no matter which one is previewed (via the eye toggle next to each Typst file in the file panel). ### Paths and packages A package can only load files from its own directory. Within it, absolute paths point to the package root, rather than the project root. For this reason, it cannot directly load files from the project directory. If a package needs resources from the project (such as a logo image), you must pass the already loaded image, e.g. as a named parameter `{logo: image("mylogo.svg")}`. Note that you can then still customize the image's appearance with a set rule within the package. In the future, paths might become a [distinct type from strings](https://github.com/typst/typst/issues/971), so that they can retain knowledge of where they were constructed. This way, resources could be loaded from a different root.
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/grundpositionen/muensteraner_erklaerung.typ
typst
Other
#import "/src/template.typ": * == #ix("Münsteraner Erklärung") Philosophie ist in einigen Bundesländern immernoch ein Wahl- oder Ersatzfach, obwohl die Kompetenzen, die mit Hilfe philosophischer Arbeit gewonnen werden, für das moderne Leben aktuell und wichtig sind. In der #ix("Münsteraner Erklärung")#en[@MuensteranerErklaerung] werden aus diesem Grund folgende Forderungen gestellt: // + Aufwertung der in der im Philosophieunterricht vermittelten Kompetenzen. #orange-list[ *Gleichstellung des Philosophieunterrichts:* #set text(fill: black) Gefordert ist die Gleichstellung des Unterrichtsfaches "Philosophie" mit anderen Unterrichtsfächern. ][ *Etablierung als Prüfungsfach:* #set text(fill: black) Es soll die Möglichkeit geboten werden, in Philosophie eine Abitur- und jede andere Form der Abschlussprüfung ablegen zu können. ][ *Aus- und Weiterbildungsverhältnisse:* #set text(fill: black) Die Verhältnisse der Aus- und Weiterbildung für Lehrkräfte soll verbessert werden. Besonderer Schwerpunkt im Lehramtsstudium soll auf die Fachdidaktik und Praxisorientierung gelegt werden. ][ *Anforderung an Lehrkräfte:* #set text(fill: black) Lehrkräfte sollen grundständig Ausgebildet sein, um Philosophieunterricht durchführen zu dürfen. ]
https://github.com/jamesrswift/splendid-mdpi
https://raw.githubusercontent.com/jamesrswift/splendid-mdpi/main/template/main.typ
typst
The Unlicense
#import "@preview/splendid-mdpi:0.1.1" #import "@preview/physica:0.9.3" #show: splendid-mdpi.template.with( title: [Towards Swifter Interstellar Mail Delivery], authors: ( ( name: "<NAME>", department: "Primary Logistics Department", institution: "Delivery Institute", city: "Berlin", country: "Germany", mail: "<EMAIL>", ), ( name: "<NAME>", department: "Communications Group", institution: "Space Institute", city: "Florence", country: "Italy", mail: "<EMAIL>", ), ( name: "<NAME>", department: "Missing Letters Task Force", institution: "Mail Institute", city: "Budapest", country: "Hungary", mail: "<EMAIL>", ), ), date: ( year: 2022, month: "May", day: 17, ), keywords: ( "Space", "Mail", "Astromail", "Faster-than-Light", "Mars", ), doi: "10.7891/120948510", abstract: [ Recent advances in space-based document processing have enabled faster mail delivery between different planets of a solar system. Given the time it takes for a message to be transmitted from one planet to the next, its estimated that even a one-way trip to a distant destination could take up to one year. During these periods of interplanetary mail delivery there is a slight possibility of mail being lost in transit. This issue is considered so serious that space management employs P.I. agents to track down and retrieve lost mail. We propose A-Mail, a new anti-matter based approach that can ensure that mail loss occurring during interplanetary transit is unobservable and therefore potentially undetectable. Going even further, we extend A-Mail to predict problems and apply existing and new best practices to ensure the mail is delivered without any issues. We call this extension AI-Mail. ], details: [ *Publisher's Note:* MDPI stays neutral with regard to jurisdictional claims in published maps and institutional affiliations. *Copyright:* © 2022 by the authors. Submitted to _An Awesome Journal_ for possible open access publication under the terms and conditions of the Creative Commons Attribution (CC BY) license (#link("https://creativecommons.org/licenses/by/4.0/")).] ) = Introduction Our concept suggests three ways that A-Mail can be best utilized. - First is to reduce the probability of the failure of a space mission. This problem, known as the Mars problem, suggests that the high round-trip time required for communication between Mars and Earth inhibits successful human developments on the planet. Thanks to A-Mail's faster-than-light delivery system this problem could be solved once and for all. - As A-Mails are written using pen and paper, no digital technology is needed for short and long distance communication. This suggests a possibility of reducing the communication monopoly currently held by an entity known as the "internet". Our suggestion of A-Mail being responsible for postal delivery would reduce dependence on online services by delivering the vast majority of mail offline. Space is a place where drastic changes in methods of production and distribution can easily occur. - Lastly, A-Mail is capable of performing high-level complex calculations. It is this capability that distinguishes A-Mail from traditional space mailers. This is an especially useful capability when planning long-distance space missions. The delivery speed of an A-Mail can be determined through this simple formula: $ v(t) = lim_(t -> infinity) integral^infinity c dot sqrt(t^2) physica.dd("t") $ Building on the strong foundations of A-Mail, we extend our platform to predict problems and apply existing and new best practices to ensure the mail is delivered without any issues. We call this extension AI-Mail. AI-Mail is a new concept designed and delivered by artificially intelligent (AI) agents. The AI-Mail agents are intelligently designed to solve problems at various points in the delivery chain. These problems are related to targeting, delivery delay, tone of delivery, product information, product return, system crash, shipment error and more. AI-Mail provides a one-stop solution for A-Mail's shortcomings. == Proven technology A-Mail has been under development four the past ten years and in the process has consolidate different space programmes. Over the course of the last year, our space P.I.s have already found over ten thousand lost letters. These letters had been drifting in space since the stone ages when they were originally mailed. Only now we had the technology to recover them. In this way, A-Mail technology has already proven invaluable to human advancement and research, bringing us closer to our ancestors. == Limitless possibilities Through A-Mail's _faster-than-light_ technology, for the first time, humans have the capability to rearch far away solar systems to find out whether we are, after all, alone in this universe. During our research, we have already established pen pal relations with at least three potential extraterrestrial living forms. == Direct implications One of the most direct implications of A-Mail is the solution of the Mars problem. This means that people stuck on Mars can now finally watch football games live, a significant achievement on the grand scale of things. The complex communication interactions arising between Earth, Mars, and the \+ #figure( image("a-mail.png"), caption: [ Visualization of the FTL Earth-to-Mars communication capabilities enabled by A-Mail. ], )
https://github.com/yonatanmgr/university-notes
https://raw.githubusercontent.com/yonatanmgr/university-notes/main/0366-%5BMath%5D/globals/toc.typ
typst
#import "@preview/outrageous:0.1.0" #{ show outline.entry: outrageous.show-entry.with(font-weight: ("bold", auto), font: ("", auto), body-transform: (lvl, body) => { if "children" in body.fields() { let (number, space, ..text) = body.children style(styles => { h(measure([.], styles).width * (lvl - 1)) if not number.at("text", default: "").starts-with(regex("\d")) { [#((space,) + text).join()] } else { [#number. #text.join()] } }) } }) outline(title: "תוכן העניינים", depth: 2, indent: true) pagebreak(weak: true) }
https://github.com/max-niederman/MATH51
https://raw.githubusercontent.com/max-niederman/MATH51/main/notes/lecture_2023-08-04.typ
typst
#import "../lib.typ": * #show: lecture-notes.with( date: "2023-08-04" ) = Definite quadratic forms A quadratic form $q : RR^n -> RR$ is called _positive-definite_ if $ forall vname(x) in RR^n : vname(x) != vname(0) implies q(vname(x)) > 0 $ = Orthogonal matrices Orthogonal matrices represent transformations which are either rotations or reflections. For any rotation matrix $R$, the quadratic form $q_(R^T R) = v^T v$, because $ ||R v|| &= ||v|| \ (R v) dot (R v) &= v dot v \ (R v)^T (R v) &= v^T v \ v^T R^T R v &= v^T v \ q_(R^T R) (v) &= v^T v $ This also implies $R^T R = I_n$, because every quadratic form is uniquely associated with a symmetric matrix. This also implies that $R$ is orthonormal because the $i j$-th entry of $R^T R$ is defined as $ (R^T)_i dot R^j &= R^i dot R^j \ &= I_(i j) \ &= cases( 1 "if" i = j, 0 "if" i != j, ) $ In general, the following conditions are equivalent for a transformation $T_A : RR^n -> RR^m$: + $T_A$ is length-preserving. + $A^T A = I_n$ + When $n = m$, $A A^T = I_n$ + The set of $A$'s columns is orthonormal. + When $n = m$, the set of $A$'s rows are orthonormal. The product of two orthogonal matrices is also orthogonal. = Linear systems A general linear system of $m$ equations in $n$ variables is written as $ A vname(x) = vname(b) $ where $A$ is an $m times n$ matrix, and $a$ and $b$ are $n$- and $m$-vectors, respectively.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/attach-p2_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test high subscript and superscript. $ sqrt(a_(1/2)^zeta), sqrt(a_alpha^(1/2)), sqrt(a_(1/2)^(3/4)) \ sqrt(attach(a, tl: 1/2, bl: 3/4)), sqrt(attach(a, tl: 1/2, bl: 3/4, tr: 1/2, br: 3/4)) $
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap2/8_polarity_of_voltage_drops.typ
typst
Other
#import "../../core/core.typ" === Polarity of voltage drops We can trace the direction that electrons will flow in the same circuit by starting at the negative (-) terminal and following through to the positive (+) terminal of the battery, the only source of voltage in the circuit. From this we can see that the electrons are moving counter-clockwise, from point 6 to 5 to 4 to 3 to 2 to 1 and back to 6 again. As the current encounters the 5 $Omega$ resistance, voltage is dropped across the resistor's ends. The polarity of this voltage drop is negative (-) at point 4 with respect to positive (+) at point 3. We can mark the polarity of the resistor's voltage drop with these negative and positive symbols, in accordance with the direction of current (whichever end of the resistor the current is _entering_ is negative with respect to the end of the resistor it is exiting: #image("static/8-circuit.png") We could make our table of voltages a little more complete by marking the polarity of the voltage for each pair of points in this circuit: #core.voltage_listing[ Between points 1 (+) and 4 (-) = 10 volts Between points 2 (+) and 4 (-) = 10 volts Between points 3 (+) and 4 (-) = 10 volts Between points 1 (+) and 5 (-) = 10 volts Between points 2 (+) and 5 (-) = 10 volts Between points 3 (+) and 5 (-) = 10 volts Between points 1 (+) and 6 (-) = 10 volts Between points 2 (+) and 6 (-) = 10 volts Between points 3 (+) and 6 (-) = 10 volts ] While it might seem a little silly to document polarity of voltage drop in this circuit, it is an important concept to master. It will be critically important in the analysis of more complex circuits involving multiple resistors and/or batteries. It should be understood that polarity has nothing to do with Ohm's Law: there will never be negative voltages, currents, or resistance entered into any Ohm's Law equations! There are other mathematical principles of electricity that do take polarity into account through the use of signs (+ or -), but not Ohm's Law. #core.review[ The polarity of the voltage drop across any resistive component is determined by the direction of electron flow though it: _negative_ entering, and _positive_ exiting. ]
https://github.com/taooceros/typst-sync-packages
https://raw.githubusercontent.com/taooceros/typst-sync-packages/main/README.md
markdown
Apache License 2.0
# typst-packages Typst Packages (majorly my template)
https://github.com/crd2333/template-report
https://raw.githubusercontent.com/crd2333/template-report/master/packages/Packages_test.typ
typst
MIT License
#import "@preview/chic-hdr:0.3.0": * #set page(paper: "a4") #show: chic.with( chic-footer( left-side: strong( link("mailto:<EMAIL>", "<EMAIL>") ), right-side: chic-page-number() ), chic-header( left-side: emph(chic-heading-name()), right-side: smallcaps("Example") ), chic-separator(1pt), chic-offset(7pt), chic-height(1.5cm) ) *chic-hdr: 用于创建优雅的页眉和页脚* = Introduction #lorem(30) == Details #lorem(30) \ \ \ *colorful-boxes: 预定义的多彩框* #import "@preview/colorful-boxes:1.2.0": * #colorbox( title: lorem(5), color: "blue", radius: 2pt, width: auto )[#lorem(20)] #outlinebox( title: lorem(5), color: none, width: auto, radius: 2pt, centering: false )[#lorem(20)] \ \ \ *codelst: 用于渲染源代码的 Typst 包* #import "@preview/codelst:1.0.0": sourcecode #sourcecode[```typ #show "ArtosFlow": name => box[ #box(image( "logo.svg", height: 0.7em, )) #name ] This report is embedded in the ArtosFlow project. ArtosFlow is a project of the Artos Institute. ```] \ \ \ *showybox: 为 Typst 创建丰富多彩且可自定义的框* #import "@preview/showybox:2.0.1": showybox #showybox([Hello world!]) #showybox( frame: ( border-color: red.darken(50%), title-color: red.lighten(60%), body-color: red.lighten(80%) ), title-style: ( color: black, weight: "regular", align: center ), shadow: ( offset: 3pt, ), title: "Red-ish showybox with separated sections!", lorem(20), lorem(12) ) \ \ \ *easy-pinyin: 轻松编写汉语拼音* #import "@preview/easy-pinyin:0.1.0": pinyin, zhuyin 汉(#pinyin[ha4n])语(#pinyin[yu3])拼(#pinyin[pi1n])音(#pinyin[yi1n])。 #let per-char(f) = [#f(delimiter: "|")[汉|语|拼|音][ha4n|yu3|pi1n|yi1n]] #let per-word(f) = [#f(delimiter: "|")[汉语|拼音][ha4nyu3|pi1nyi1n]] #let all-in-one(f) = [#f[汉语拼音][ha4nyu3pi1nyi1n]] #let example(f) = (per-char(f), per-word(f), all-in-one(f)) // argument of scale and spacing #let arguments = ((0.5, none), (0.7, none), (0.7, 0.1em), (1.0, none), (1.0, 0.2em)) #table( columns: (auto, auto, auto, auto), align: (center + horizon, center, center, center), [arguments], [per char], [per word], [all in one], ..arguments.map(((scale, spacing)) => ( text(size: 0.7em)[#scale,#repr(spacing)], ..example(zhuyin.with(scale: scale, spacing: spacing)) )).flatten(), ) \ \ \ *lovelace: 伪代码书写的算法,没有预定立场,十分灵活* #import "@preview/lovelace:0.1.0": * #show: setup-lovelace #algorithm( caption: [The Euclidean algorithm], pseudocode( no-number, [*input:* integers $a$ and $b$], no-number, [*output:* greatest common divisor of $a$ and $b$], [*while* $a != b$ *do*], ind, [*if* $a > b$ *then*], ind, $a <- a - b$, ded, [*else*], ind, $b <- b - a$, ded, [*end*], ded, [*end*], [*return* $a$] ) ) \ \ \ *nth: 将英文序数添加到数字中,例如 1st、3nd、2rd、4th* #import "@preview/nth:0.2.0": nth #nth(2)\ #nth(3)\ #nth(4) // \ // \ // \ // *lemmify: 定理排版* // #import "@preview/lemmify:0.1.4": * // #let my-thm-style( // thm-type, name, number, body // ) = grid( // columns: (1fr, 3fr), // column-gutter: 1em, // stack(spacing: .5em, strong(thm-type), number, emph(name)), // body // ) // #let my-styling = ( // thm-styling: my-thm-style // ) // #let ( // theorem, rules // ) = default-theorems("thm-group", lang: "en", ..my-styling) // #show: rules // #show thm-selector("thm-group"): box.with(inset: 1em) // #lorem(20) // #theorem[ // #lorem(40) // ] // #lorem(20) // #theorem(name: "Some theorem")[ // #lorem(30) // ] \ \ \ *tablex: 在 Typst 中提供更强大和可定制的表格* #import "@preview/tablex:0.0.5": tablex, gridx, hlinex, vlinex, colspanx, rowspanx #tablex( columns: 4, auto-lines: false, // skip a column here vv vlinex(), vlinex(), vlinex(), (), vlinex(), colspanx(2)[a], (), [b], [J], [c], rowspanx(2)[d], [e], [K], [f], (), [g], [L], // ^^ '()' after the first cell are 100% ignored ) #tablex( columns: 4, auto-vlines: false, colspanx(2)[a], (), [b], [J], [c], rowspanx(2)[d], [e], [K], [f], (), [g], [L], ) #gridx( columns: 4, (), (), vlinex(end: 2), hlinex(stroke: yellow + 2pt), colspanx(2)[a], (), [b], [J], hlinex(start: 0, end: 1, stroke: yellow + 2pt), hlinex(start: 1, end: 2, stroke: green + 2pt), hlinex(start: 2, end: 3, stroke: red + 2pt), hlinex(start: 3, end: 4, stroke: blue.lighten(50%) + 2pt), [c], rowspanx(2)[d], [e], [K], hlinex(start: 2), [f], (), [g], [L], ) \ \ \ *tbl: 简洁编写复杂的表格* #import "@preview/tbl:0.0.4" #show: tbl.template.with(box: true, tab: "|") ```tbl R | L R N. software|version _ AFL|2.39b Mutt|1.8.0 Ruby|1.8.7.374 TeX Live|2015 ``` \ \ \ *用于渲染语言学中的语法树/解析树* #import "@preview/syntree:0.2.0": syntree #syntree( nonterminal: (font: "Linux Biolinum"), terminal: (fill: blue), child-spacing: 3em, // default 1em layer-spacing: 2em, // default 2.3em "[S [NP This] [VP [V is] [^NP a wug]]]" ) \ \ \ *使用 graphviz dot 语言生成图形的工具* #import "@preview/gviz:0.1.0": * #show raw.where(lang: "dot-render"): it => render-image(it.text) ```dot-render digraph mygraph { node [shape=box]; A -> B; B -> C; B -> D; C -> E; D -> E; E -> F; A -> F [label="one"]; A -> F [label="two"]; A -> F [label="three"]; A -> F [label="four"]; A -> F [label="five"]; }``` #let my-graph = "digraph {A -> B}" #render-image(my-graph, width: 10%) SVG: #box(clip: true, width: 100%, height: 20em)[ #raw(render(my-graph), block: true, lang: "svg") ] \ \ \ *polylux: 使用 Typst 制作演示幻灯片* #import "@preview/polylux:0.3.1": * #import themes.simple: * #set text(font: "Inria Sans") #show: simple-theme.with( footer: [Simple slides], ) #title-slide[ = Keep it simple! #v(2em) Alpha #footnote[Uni Augsburg] #h(1em) Bravo #footnote[Uni Bayreuth] #h(1em) Charlie #footnote[Uni Chemnitz] #h(1em) July 23 ] #slide[ == First slide #lorem(20) ] #focus-slide[ _Focus!_ This is very important. ] #centered-slide[ = Let's start a new section! ] #slide[ == Dynamic slide Did you know that... #pause ...you can see the current section at the top of the slide? ]
https://github.com/teamdailypractice/pdf-tools
https://raw.githubusercontent.com/teamdailypractice/pdf-tools/main/typst-pdf/thirukkural-cover/t2.typ
typst
#set page("a4") #set text( font: "TSCu_SaiIndira", size: 40pt ) #set align(center) \ \ \ \ திருக்குறள் \ \ #set text( font: "TSCu_SaiIndira", size: 24pt ) #set align(center) மு. வரதராசனார் உரை
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/flyingcircus/3.0.0/template/Main.typ
typst
Apache License 2.0
#import "@preview/flyingcircus:3.0.0" : * #let title = "Sample Flying Circus Book" #let author = "Tetragramm" #show: FlyingCircus.with(Title: title, Author: author, CoverImg: image("images/Cover.png"), Dedication: [Look strange? You probably don't have the fonts installed. Download the fonts from #link("https://github.com/Tetragramm/flying-circus-typst-template/archive/refs/heads/Fonts.zip")[HERE]. Install them on your computer, upload them to the Typst web-app (anywhere in the project is fine) or use the Typst command line option --font-path to include them.]) #FCPlane( read("Basic Biplane_stats.json"), Nickname: "Bring home the bacon!", Img: image("images/Bergziegel_image.png"), )[ This text is where the description of the plane goes. Formatting is pretty simple, but bold and italic don't work yet, I need to fake those. #underline[Words get underlined.] Leave an empty line or it will be the same paragraph + numbered list + Sub-Lists! + Things! But you can have multiple lines for an item by indenting the next one, or just one long line. - Sub-items! - Unnumbered list Break the column where you want it with `#colbreak()` Images can be added by doing `#image(path)`. The FC functions do fancy stuff though, and may override some arguments when you pass an image into them using an argument. Find the full documentation for Typst on the website #link("https://typst.app/docs")[#text(fill: blue)[HERE]] ] //If we don't want all our planes at the top level of the table of contents. EX: if we want // - Intro // - Story // - Planes // - First Plane // We break the page, and create a HiddenHeading, that doesn't show up in the document (Or a normal heading, if that's what you need) //Then we set the heading offset to one so everything after that is indented one level in the table of contents. #pagebreak() #HiddenHeading[= Vehicles] #set heading(offset: 1) //Parameters #FCVehicleSimple(read("Sample Vehicle_stats.json"))[#lorem(120)] //We wrap this in a text box so that we can set a special rule to apply #text[ //Set it so that the headings are offset by a large amount, so they don't show up in the table of contents. #set heading(offset: 10) // #FCWeapon( (Name: "Rifle/Carbine", Cells: (Hits: 1, Damage: 2, AP: 1, Range: "Extreme"), Price: "Scrip", Tags: "Manual"), Img: image("images/Rifle.png"), )[ Note that you can set the text in the cell boxes to whatever you want. ] #FCWeapon(( Name: "Machine-Gun (MG)", Cells: (Hits: 4, Damage: 2, AP: 1, "Ammo Count": 10), Price: "2þ", Tags: "Rapid Fire, Jam 1/2", ))[ Note that you can set the text in the cell boxes to whatever you want using the dictionary. ] ] #FCVehicleFancy( read("Sample Vehicle_stats.json"), Img: image("images/Wandelburg.png"), TextVOffset: 6.2in, BoxText: ("Role": "Fast Bomber", "First Flight": "1601", "Strengths": "Fastest Bomber"), BoxAnchor: "north-east", )[ The project to build the first armoured attack vehicle in the Gotha Empire spanned nearly three decades. Largely considered a low priority during the war with the UWF, the fierce fighting against the Macchi Republics suddenly accelerated the project, which went from concept sketch to deployment in six short months. This development was accompanied by intense secrecy: the project was code-named “Wandering Castle”, which gave the impression it was a Leviathan-building enterprise. Used for the first time in the Battle of Reggiane in 1593, the Type 1 reflects the idea that the tank ought to be a sort of mobile form of the concrete pillboxes coming into use at the time. Though suffering frequent breakdowns, plagued with difficulties getting its main gun on target, and very vulnerable in the mountains, it was successful enough that it soon became the most-produced tank of the war. After the first six months the official name of the vehicle was changed from its codename to “Self-Propelled Assault Vehicle Type 1”, known by the acronym “SbRd-AnZg Ausf I”. This development was ignored by everyone outside of official communications. ][#lorem(100)] #FCVehicleFancy(read("Sample Vehicle_stats.json"))[][#lorem(100)] #let ship_stats = ( Name: "<NAME>", Speed: 5, Handling: 15, Hardness: 9, Soak: 0, Strengths: "-", Weaknesses: "-", Weapons: ( (Name: "x2 Light Howitzer", Fore: "x1", Left: "x2", Right: "x2", Rear: "x1"), (Name: "x6 Pom-Pom Gun", Fore: "x2", Left: "x3", Right: "x3", Rear: "x2", Up: "x6"), (Name: "x2 WMG", Left: "x1", Right: "x1"), ), DamageStates: ("", "-1 Speed", "-3 Guns", "-1 Speed", "-3 Guns", "Sinking"), ) #set heading(offset: 0) #FCShip( Img: image("images/Macchi Frigate.png"), Ship: ship_stats, )[ Though remembered for large bombardment ships and airship tenders, the majority of the Seeheer was in fact these mid-sized frigates. These ships were designed for patrolling the seas for enemy airships and to escort Macchi cargo ships along the coast. They proved a deadly threat to landing barge attacks in the Caproni islands, as it was found their anti- aircraft guns were also effective against surface targets. ][ 160 crew ]
https://github.com/cunhapaulo/typst_styles
https://raw.githubusercontent.com/cunhapaulo/typst_styles/main/example_monography.typ
typst
MIT License
#import "./toolbox/monography.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( university: "Universidade Federal do Pará", sigla: "UFPA", centre: "Instituto de Filosofia e Ciências Humanas", faculty: "Faculdade de Filosofia", course: "Bacharelado em Filosofia", title: "Modernismo e Pós-Modernismo", subtitle: ": "+"Comentários sobre os Dois Tópicos segundo <NAME>", discipline: "Tópicos de Filosofia Contemporânea", professor: "Prof. Dr. <NAME>", citystate: "Belém - PA", year: "2023", date: "15 de setembro de 2023", keywords: [Modernismo; Pós-modernismo; Filosofia contemporânea; Filosofia ocidental.], authors: ( ( name: "<NAME> 2", affiliation: "Curso de Bacharelado em Filosofia - UFPA", email: "<EMAIL>", mat: "202208040033", ), // ( name: "", affiliation: "", mat: "", ), ), ) #set cite(style: "chicago-author-date") // Unnumbered section #section_[Introdução] #lorem(40) #footnote[#footciteref(<Peters2000>)] = Modernismo e Pós-modernismo na Filosofia #lorem(30) @Peters2000[p.105] == Modernismo nas artes // Unnumbered subsection version #subsection_[Modernismo nas artes] #lorem(20) Eaxample use of citation: 1. @Peters2000[p. 5] 2. #cite(<Peters2000>, supplement: "p.45"); 3. #citeonline(<Lyotard2009>); 4. #citeonline(<Lyotard2009>, supplement: "p.97"); #lorem(30) #myfigure("../img/finishline.jpg", width: 55%, caption: [Linha de chegada] ) #lorem(30) #myfigure("../img/ufpa.png", width: 25%, caption: [University´s logo], source: "Institutional website of UFPa " ) == Modernismo na filosofia #lorem(140) #highlightBox(lorem(40), color: "gray") == Pós-modernismo na filosofia #lorem(10) === O Pós-modernismo e outros movimentos associados // Unnumbered subsection version #subsubsection_[O Pós-modernismo e outros movimentos associados] #lorem(80) // Bibliography section #set par(first-line-indent: 0mm, hanging-indent: 8mm, leading: 0.6em) // format tweak #bibliography("./references/refs.bib", title: "Referências", style: "./references/abnt-ufrgs.csl")
https://github.com/jamesrswift/journal-ensemble
https://raw.githubusercontent.com/jamesrswift/journal-ensemble/main/src/pages.typ
typst
The Unlicense
#import "pages/contents.typ": contents #import "pages/cover.typ": cover #import "pages/inner.typ": inner
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-33.typ
typst
Other
// Error: 10-41 the return value is too large #calc.lcm(15486487489457, 4874879896543)
https://github.com/fuchs-fabian/typst-template-aio-studi-and-thesis
https://raw.githubusercontent.com/fuchs-fabian/typst-template-aio-studi-and-thesis/main/src/utils.typ
typst
MIT License
// Validation if content is none or empty #let is-not-none-or-empty(content) = if content != none and content != "" { return true } else { return false } // Validation if dict contains a specified key #let dict-contains-key(dict: (), key) = { if (key in dict) { return true } else { return false } } // Converts content to string #let to-string(content) = { if content.has("text") { content.text } else if content.has("children") { content.children.map(to-string).join("") } else if content.has("body") { to-string(content.body) } else if content == [ ] { " " } } // Default colors #let blue = rgb("#009fe3") #let dark-blue = rgb("#152f4e") #let light-blue = rgb("#e8eff7") #let dark-grey = rgb("#4a4a49") #let green = rgb("#26a269") #let purple = rgb("#613583") // Outline, which has a title listed in toc and no special formatting #let simple-outline(title: none, target: none, indent: 1em, depth: none) = { if is-not-none-or-empty(title) { heading(depth: 1)[ #title ] } outline( title: none, target: target, indent: indent, depth: depth ) } // Signing #let signing(text: none) = { import "dictionary.typ": txt-location, txt-date, txt-author-signature v(1fr) let gutter = 30pt let stroke = 0.5pt let columns = (1.2fr, 2fr) grid( columns: columns, gutter: gutter, [ #line(length: 100%, stroke: stroke) ], [ #line(length: 90%, stroke: stroke) ] ) v(-5pt) grid( columns: columns, gutter: gutter, [ #txt-location, #txt-date ], [ #if text == none { txt-author-signature } else { text } ] ) } // Emphasising keywords #let emphasized(fill: dark-blue, it) = { text(style: "normal", weight: "bold", tracking: 0pt, fill: fill, it) } // TODO handling - Reference: https://github.com/typst/typst/issues/662#issuecomment-1516709607 #let txt-todo = text(size: 1.2em, emphasized(fill: red, "TODO")) #let todo(it) = [ #if is-not-none-or-empty(it) { text([#txt-todo: #[#it <todo>]], red) } ]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-prec-04.typ
typst
Other
// Parentheses override precedence. #test((1), 1) #test((1+2)*-3, -9) // Error: 14 expected closing paren #test({(1 + 1}, 2)
https://github.com/Error0229/-
https://raw.githubusercontent.com/Error0229/-/main/-.-.%20.-/....%20.--%20..---.typ
typst
The Unlicense
#import "@preview/algo:0.3.3": algo, i, d, comment, code #set text(font: "New Computer Modern") #align(center, text(16pt)[ *Design and Analysis of Computer Algorithms Assignment \#2* ]) #align(right, [資工三 110590004 林奕廷]) = 1. == (a) #algo(title: "Alternating Disk", parameters: ("n", "d"))[ for $i <- 1$ to $n$ do:#i\ for $j <- i$ to $2n - 1$ do:#i\ if $d_j$ is dark and $d_(j+1)$ is light then:#i\ swap $d_j$ and $d_(j+1)$#d\ end if#d\ end for#d\ end for\ ] The total number of swaps is $n + (n-1) + (n-2) + ... + 1 = (n(n+1))/2$. == (b) Due to the fact that moving the dark disk at position $1 + 2k$ to $n - k$ requires at least $n - k$ swaps\( k from 0 to n - 1\), the total number of swaps is $1 + 2 + 3 + ... + n = (n(n+1))/2$.\ Hence the lower bound is $Omega(n^2)$. And the lower bound is tight because the given algorithm has a complexity of $O(n^2)$.\ = 2. $"let" k = lg n$\ #align( left, )[ #block( $ T(n) &=2T(n/2) + n/(lg n)\ &= 2^k + n/(lg n) + 2 (n/2)/(lg (n/2)) + 4 (n/4)/(lg (n/4)) + ... + 2^(k-1) (n / 2^(k-1))/(lg n/2^(k-1))\ &= n + n sum^(k-1)_(i=0) 1/(lg n - i)\ &<= n + n sum^(k-1)_(i=0) 1/(lg n - k + 1) = n + n lg n = O(n lg n) $, ) ] Assume $forall m \(m < n -> T(m) <= c dot m lg m \)$\ #align(left)[ #block($ T(n) &<= 2 c n/2 lg n/2 + n/(lg n)\ &= c n (lg n - 2) + n/(lg n)\ &= c n lg n - n(2c + 1/(lg n))\ &<= c n lg n\ $) ] Q.E.D. #set enum(numbering: "1°") = 3. a. $T(n) = 2T(n/2) + c$\ $a = 2, b = 2, f(n) = c $\ + $n^(log_b a) = n^1 = n$\ + $h(m) = c/n = O(m^(-1)), -1 <= 0$\ + $T(n) = n[T(1) + O(1)] = O(n)$\ b. $T(n) = 4T(n/2) + c n$\ $a = 4, b = 2, f(n) = c n$\ + $n^(log_b a) = n^2$\ + $h(m) = (c m)/m^2 = c/m = O(m^(-1)), -1 <= 0$\ + $T(n) = n^2[T(1) + O(1)] = O(n^2)$\ c. $T(n) = 4T(n/2) + c n^3$\ $a = 4, b = 2, f(n) = c n^3$ + $n^(log_b a) = n^2$\ + $h(m) = (c m^3)/m^2 = c m = O(m), 1 > 0$\ + $T(n) = n^2[T(1) + O(n)] = O(n^3)$\ d. $T(n) = 4T(n/3) + c n$\ $a = 4, b = 3, f(n) = c n$\ + $n^(log_b a) = n^(log_3 4) = n^(1.26)$\ + $h(m) = (c n)/(n^1.26) = O(n^-0.26), -0.26 < 0$ + $T(n) = n^(log_3 4)[T(1) + O(1)] = O(n^(1.26))$ Result: a < d < b < c = 4. #algo( title: "Multiply", parameters: ("x", "y",), )[ if $x = 0$ or $y = 0$ then:#i\ return 0#d\ end if\ $n <- max("length(x)", "length(y)")$\ if n = 1 then:#i\ return $ x dot y$#d\ end if\ $x_l, x_h <- "leftmost" floor(n/2) "bits of" x, "rightmost" floor(n/2) "bits of" x$\ $y_l, y_h <- "leftmost" floor(n/2) "bits of" y, "rightmost" floor(n/2) "bits of" y$\ $z_0 <- "Multiply"(x_l, y_l)$\ $z_1 <- "Multiply"(x_h, y_h)$\ $z_2 <- "Multiply"(x_h + x_l, y_h + y_l) - z_0 - z_1$\ return $z_1 dot 2^(n) + z_2 dot 2^(n/2) + z_0$\ ] $T(n) = cases(3T(n/2) + O(n) &"if" n > 1, O(1) &"otherwise")$\ By master theorem, $a = 3, b = 2, f(n) = n$\ + $n^(log_b a) = n^1.58$\ + $h(m) = (c m)/m^(1.58) = O(n^(-0.58)), -0.58 < 0$\ + $T(n) = n^(1.58)[T(1) + O(1)] = O(n^(1.58))$\ Q.E.D.
https://github.com/adeshkadambi/ut-thesis-typst
https://raw.githubusercontent.com/adeshkadambi/ut-thesis-typst/main/main.typ
typst
MIT License
#import "template.typ": ut-thesis, appendix #show: ut-thesis.with( "Cool title for a really cool thesis", "<NAME>", "Doctor of Philosophy", "Institute of Biomedical Engineering", "2024", [#include("0-abstract.typ")], [#include("0-ack.typ")], [#include "0-abbrev.typ"] ) // Your thesis content starts here #include "1-introduction.typ" // Bibliography #bibliography("bibliography.bib",) // Appendices #show: appendix = Some Derivation <app1> Cool thing we derived.
https://github.com/Trebor-Huang/HomotopyHistory
https://raw.githubusercontent.com/Trebor-Huang/HomotopyHistory/main/homology.typ
typst
#import "common.typ": * = 同调代数 同调代数, 就是将拓扑学中出现的同调概念的代数部分抽象出来研究的学科. 在此前代数拓扑的发展中, *链复形*的概念已经浮现出来. 这由一串代数对象 ${C_n}$ 与边界算子 $diff_n : C_n -> C_(n-1)$ 构成, 满足关键的等式 $ diff_n compose diff_(n+1) = 0 $ 简写成 $diff^2 = 0$. 这个简单的式子中蕴含无限丰富的结构. 同调群 $H_n$ 可以抽象地对链复形定义, 即 $ker diff_n$ 商去 $im diff_(n+1)$. 其中 $ker diff_n = Z_n$ 是图中蓝色的部分, 代表几何上的 $n$ 维圈; $im diff_(n+1) = B_n$ 代表 $(n+1)$ 维对象的 $n$ 维边界. #block(width: 100%)[ #import cetz.draw: * #set align(center) #cetz.canvas({ circle((2,0), radius: 1.5, fill: color.lighten(aqua, 70%)) circle((4,0), radius: 1.5, fill: white) arc((-2,0), anchor: "origin", radius: 1.5, start: 70deg, stop: -70deg) circle((0,0), radius: 1.5) content((0, -2), $C_(n+1)$) content((0, 1), $H_(n+1)$) content((1, 0), $B_n$) circle((2,0), radius: 1.5) content((2, -2), $C_n$) content((2, 1), $H_(n)$) circle((4,0), radius: 1.5) content((4, -2), $C_(n-1)$) content((4, 1), $H_(n-1)$) arc((6,0), anchor: "origin", radius: 1.5, start: 110deg, stop: 360deg-110deg) }) ] 如果所有的 $H_n$ 都为零, 即 $Z_n = B_n$, 就说链复形*正合*. 同调代数研究各种代数操作, 如张量积等, 如何影响链复形以及其同调群. 本章参考 @ATDTHistory 与 @HomologicalAlgebraHistory. == 万有系数定理与 Künneth 公式 不同系数的同调之间有相互关联. 以整数为系数的同调中, 链复形是一些单形自由生成的交换群 —— 即 $ZZ$-模 $ZZ^(plus.circle X)$ —— 组成的. 如果考虑用其他交换群 $G$ 构造链复形, 就是 $G^(plus.circle X) tilde.equiv ZZ^(plus.circle X) times.circle_ZZ G$. 那么, 研究其他系数的同调, 就是研究 $(- times.circle_ZZ G)$ 这个函子对链复形的同调群的作用. 1935 年, Čech @UCTTor 发现整数系数的同调可以确定任何其他交换群系数的同调. 对任何交换群 $G$, 都有 $ H_n (X; G) tilde.equiv H_n (X; ZZ) plus.circle "Tor"_1^ZZ (H_(n-1) (X; ZZ), G). $ 不过, 张量积与 $"Tor"$ 积的记号还没有出现, 这些群是以群表示的方法定义的. 1938 年, Whitney 提出了交换群与模的张量积. 这个名字来源于物理与微分几何中的应用. 为了描述三维空间的物质中张力的性质, 需要用到向量空间 $RR^3$ 的张量积. 在很长一段时间内, 张量积都仅限于向量空间的特殊情况. 上同调的万有系数定理在 1942 年由 Eilenberg 与 <NAME> 随着 $"Hom"$ 与 $"Ext"$ 这两个代数概念一起提出. 其本质是描述函子 $"Hom"_ZZ (-, G)$ 对链复形的同调群的影响. 在 Poincaré 的时代, 就知道空间相乘会导致 Betti 数怎样的变化. 如果将 Betti 数组装成多项式 $sum_k b_k x^k$, 那么空间的乘积对应这个多项式的乘积. 给定两个胞腔复形 $X, Y$, 不难看出 $X times Y$ 的胞腔复形结构. 其中 $n$ 维胞腔由 $X$ 的一个 $p$ 维胞腔与 $Y$ 的一个 $(n-p)$ 维胞腔相乘得到. 因此链复形可以写成 $ C_n (X times Y) = plus.circle.big_(p+q = n) C_p (X) times.circle_ZZ C_q (Y). $ 我们可以将右侧作为链复形的张量积的定义. 由于出现了张量积, 同调群出现的变化可以通过 $"Tor"$ 函子描述. 由于 Künneth 最早发现了利用 Betti 数 @KunnethBetti 与挠数 @KunnethTorsion 表述的形式, 这些定理的各种变体都被称作 *Künneth 公式*. == 正合列的提出 在文献中最早出现的正合列是在 1941 年, Hurewicz 将一系列已知的同态连接起来组成了一个序列: $ H^n (X) -->^i^* H^n (A) -->^delta H^(n+1) (X \\ A) --> H^(n+1) (X) --> dots.c $ 其中, $A$ 是 $X$ 的闭子空间. Hurewicz 观察到, 前一个映射的像与后一个映射的核刚好相等. 在几乎同一时间, Eckmann 描述了纤维丛中纤维、全空间与底空间的同伦群满足的正合列. 这在当代被称作*同伦纤维列*: $ dots.c -> pi_(n+1) (B) -> pi_n (F) -> pi_n (E) -> pi_n (B) -> pi_(n-1) (F) -> dots.c $ 不过, 暂时没有人注意到这与 Hurewicz 的发现在代数上的相似性. 在 1945 年, 提出 Eilenberg–Steenrod 公理时, 他们要求同调群有 “一组自然的群与群同态的系统”: $ dots.c -> H_n (X) -> H_n (X, A) -> H_(n-1) (A) -> H_(n-1) (X) -> dots.c $ 其中 $A$ 是 $X$ 的闭子空间. 同年, <NAME> (微分几何学家 <NAME> 之子) 在研究 Čech 同调时, 也发现了类似的长正合列. 他由此推出了一个非常重要的结论, 今天我们称作 *Mayer–Vietoris 正合列*. 这是 Eilenberg–Steenrod 公理的纯代数推论, 允许我们将空间拆分成两部分计算同调或者上同调. 1947 年 Kelley 与 Pitcher 正式提出了 “正合列” 这个词汇. 他们考虑了这个概念的一般代数性质, 包括它们在取逆向极限操作时的性质, 等等. 这开启了对链复形与正合列的纯代数研究. 这些成果包括 “五引理”: 考虑如图的交换图, 使得上下两行都是正合列, 如果周围四个纵向映射都是同构, 那么中心的纵向映射也是同构. $ mat(delim: #none, A_1, -->, A_2, -->, A_3, -->, A_4, -->, A_5; arrow.b,,arrow.b,,arrow.b,,arrow.b,,arrow.b; B_1, -->, B_2, -->, B_3, -->, B_4, -->, B_5; ) $ 还有 “蛇引理”: 给定两个短正合列之间的交换图, $ mat(delim: #none, 0, -->, A_1, -->, A_2, -->, A_3, -->, 0; space,,arrow.b,,arrow.b,,arrow.b,,; 0, -->, B_1, -->, B_2, -->, B_3, -->, 0; ) $ #let coker = math.op("coker") 三个纵向映射称作 $f, g, h$, 则有长正合列 $ 0 -> ker f -> ker g -> ker h -->^diff coker f -> coker g -> coker h -> 0. $ 这些引理对操作链复形等代数对象非常有用, 并且最终会导出拓扑上的丰富结构. 而所有这些都来自于 $diff^2 = 0$ 这个等式. == 代数学中的应用 群的低维同调与上同调是早已被研究的课题, 如叉同态 (crossed homomorphism) 的概念对应 $H^1 (G; A)$. $H^2 (G; A)$ 给出了以 $A$ 为正规子群, $G$ 为商群的群扩张的完全分类. 1941 年 Hopf 注意到 Hurewicz 映射 $pi_2 (X) -> H_2 (X; ZZ)$ 的余核由 $pi_1 (X)$ 完全确定, 并且给出了具体的计算公式. 这启发了 Eilenberg 与 Mac Lane 利用 $K(G, 1)$ 空间定义了群的任意维数同调与上同调. 他们证明了 $H^2 (G; A)$ 分类了群扩张, 将工作与传统的代数研究联系起来. 这将同调的语言正式引入了代数学. 群上同调的框架应用到类域论, 形成了 Galois 上同调的研究. 对交换代数与 Lie 代数的扩张问题, 也可以用上同调进行研究. == 谱序列与层论 起初, 群上同调的计算仅限于那些 $K(G, 1)$ 是熟悉的拓扑空间的群 $G$. 在 1946 年, Lyndon 发现了一种计算方法, 取定一个正规子群 $N$, 从 $H^bullet (N)$ 与 $H^bullet (G \/ N; A)$ 出发计算 $H^bullet (G; A)$. 这种方法最后会产生上同调群的一系列 “零件”, 如果能知道这些零件如何组装 (例如可能的组装方式只有一种时), 就可以确定上同调. 数学家 <NAME> 在二战期间被俘. 期间, 他发展了层论与层上同调. 层描述了能够局部定义并拼接的对象, 如连续函数、光滑函数等. 层上同调刻画了局部对象拼接成全局对象的阻碍, 例如局部有解的微分方程能否得到全局的解. 为了计算层上同调, 他还发展出了谱序列的理论. 1947 年, 根据 Cartan 的建议, Koszul 以滤链复形为核心概念, 发展出了谱序列的代数框架. Serre 注意到 Lyndon 早先的工作正是谱序列的雏形. 在战后, Cartan, Eilenberg, Serre 等人将谱序列与层的理论进一步发展成熟. 给定拓扑空间 $X$, 其上的*层*为每个开集 $U$ 赋予一个集合 $cal(F)(U)$, 表示这个开集上局部定义的数学对象. 例如连续函数层 $C^0$ 满足 $C^0(U)$ 是 $U$ 上连续函数的集合. 如果有两个开集 $U subset.eq V$, 那么有对应的限制映射 $cal(F)(V) -> cal(F)(U)$. 最后, 如果 $U = union.big_alpha U_alpha$ 被一族开集覆盖, 并且在每个开集上取定 $x_alpha in cal(F)(U_alpha)$, 满足 $U_alpha sect U_beta$ 上 $x_alpha$ 与 $x_beta$ 的限制相等, 就有唯一的 $x in cal(F)(U)$, 使得它限制在 $U_alpha$ 上是 $x_alpha$. 例如在连续函数层中, 这条公理意味着在一些开集上分别定义连续函数, 如果在定义域相交的地方这些函数相等, 那么就可以拼接成并集上的连续函数. 换句话说, 连续性是局部性质. == Cartan–Eilenberg 革命 Cartan 与 Eilenberg 在 1950 年代著书 《同调代数》@CartanEilenberg, 为这个领域带来了一场革命. 描述交换群, 可以靠生成元和它们之间的关系. 具体来说, 如果有一组生成元构成的集合 $G$, 那么它们之间的关系就是 $ZZ^(plus.circle G)$ 的子群 $R$. 这也一定是自由交换群. 我们描述的群就是 $A = ZZ^(plus.circle G) \/ R$. 从这个描述出发, 可以方便地计算各种操作. 例如, 如果有两个交换群 $A, B$, 需要计算哪些交换群 $X$ 有子群 $B$, 满足商群 $X \/ B = A$. 那么可以考虑为 $A$ 的每个生成元 $g in G$ 取 $X$ 里的一个代表元. 那么, 对于生成元之间的关系 $r in R$, $X$ 中对应的元素在 $A$ 中的像就是零, 因此它唯一确定了 $B$ 中的一个元素. 这样我们就得到了一个同态 $phi : R -> B$. 这个函数也可以反过来确定 $X$. 考虑 $ZZ^(plus.circle G) times B$, 我们商去它的一个子群 $hat(R) = {(r, -phi(r)) | r in R}$, 就得到所需的群 $X$. 两个 $phi$ 确定同一个群扩张, 当且仅当它们的差可以表示为某个同态 $ZZ^(plus.circle G) -> B$ 限制到 $R$ 上. 因此, 我们可以将群扩张的集合定义为 $ "Ext"^1(A, B) = (ZZ^(plus.circle G) times B) \/ hat(R). $ 这也揭示了群扩张的集合本身构成一个交换群. 这一点由 Baer 最早发现, 因此这个运算被称作 *Baer 和*. 这之中, 我们用到了交换群的*自由预解* (free resolution), 即一正合列 $dots.c -> F_2 -> F_1 -> A -> 0$, 其中 $F_i$ 都是自由交换群. 这可以看作是取定基底方便作具体计算的过程. 在交换群 (即 $ZZ$-模) 的情况, 自由预解总是在第二项就能停止, 但一般来说它可以任意长. 在这个计算中, 其实只用到了自由交换群的一条关键性质. 给定任何满射同态 $X ->> Y$, 从自由交换群出发的同态 $F -> Y$ 总能抬升为 $F -> X$, 使得得到的三角形交换. Cartan 与 Eilenberg 在他们的书中引入了这条性质, 称作*投射性*. 我们可以将自由预解替换为投射预解, 而不影响论证. 投射性有一条对偶性质, 即将定义中的所有箭头反向. 如果对于某个 $I$, 给定任何单射同态 $X >-> Y$, 任何同态 $X -> I$ 总能扩展为 $Y -> I$ 使得得到的三角形交换, 就称 $I$ *内射*. 这条性质也由 Baer 研究过. 对于交换群来说, 内射等价于*可除*, 即对于任何元素 $x$ 与正整数 $n$, 方程 $n y = x$ 都有解. 对偶地, 有内射预解 $0 -> A -> I_1 -> I_2 -> dots.c$ 的概念. $"Ext", "Tor"$ 函子都可以用投射预解和内射预解定义. 这种操作的推广是*导出函子*. 这统一了同调代数中的许多概念.
https://github.com/linsyking/messenger-manual
https://raw.githubusercontent.com/linsyking/messenger-manual/main/component.typ
typst
#import "@preview/fletcher:0.4.5" as fletcher: diagram, node, edge #pagebreak() = Components Components can be considered as the basic elements in the game. Every layer contains several components and each type of component has its own logic. Components are versatile. Users can abstract almost every single thing in their game as a component. For instance, a character that can move and attack, the bullet fired by the character, a settings panel, an abstract concept like "ability to cast magic", and a manager to manage one specific type of components. You may even embed components into a component! Properly implementing objects and abstract concepts as components can greatly reduce your workload. Components are customizable. Users can easily define all the details of a component. One component type can have its unique data type, matcher, initialization, update and render. Components are flexible. Users can organize different types of components whatever they like. They can set one component type be a sub-type of other component. They can also put different type of components into one set, so that the components can share a basic data type, and send the same type of messages to each other easily. Users can always put components whose types are in the same set, into one list in layer. Using components allows users to simplify a complex feature and manage it step by step. Moreover, it provides a simpler and more flexible way for users to organize code. So it is necessary to use components to implement most of the logics for a complex game. == Basic Model <component> Basically the component type is inherited from the general model as follows: ```elm type alias ConcreteUserComponent data cdata userdata tar msg bdata scenemsg = ConcreteGeneralModel data (Env cdata userdata) UserEvent tar msg ( Renderable, Int ) bdata (SceneOutputMsg scenemsg userdata) type alias AbstractComponent cdata userdata tar msg bdata scenemsg = AbstractGeneralModel (Env cdata userdata) UserEvent tar msg ( Renderable, Int ) bdata (SceneOutputMsg scenemsg userdata) ``` So for a single component, it works just like how general model does. The parameter `data` represents the data type of this type of component. It is unique since users can set it freely. `bdata`, which stands for _Base Data_, represents the type that will be the same among all the types of components in one set. Note the common data is the data that shared among all the components, so every component can view or change the only copy of the common data. However, base data is the data that every component has, and only the type is shared. For instance, in a platform game, common data may include gravity while base data may include positions and velocities. The `render` type is aliased to `(Renderable, Int)`. The second entry is the #link("https://developer.mozilla.org/en-US/docs/Web/CSS/z-index")[z-index] property of the component. Each component may have different z-index value. == User Components User components are the components that are mostly used. A user component should be attached to a specific scene, then it can only be used in that scene. To understand the usage of the components better, let's make an example. ```bash # Create a new scene named Game messenger scene Game # Create a new type of component in Game scene messenger component Game Comp # Create a new layer with components in Game Scene messenger layer -c Game A ``` Addition to set the data type of `Comp`, set the data type for initialize a `Comp` is necessary. Since we would like to determine the position, size and color when initializing, add codes in `Scenes/Home/Components/ComponentBase.elm`: #grid(columns: (1fr, 1fr), [ #set align(center) ```elm type alias Data = { left : Float , top : Float , width : Float , height : Float , color : Color } ``` ], [ ```elm type alias Init = { left : Float , top : Float , width : Float , height : Float , color : Color } ``` ] ) Then add the message type for initialization in `ComponentMsg`. However, the data set in `ComponentBase.elm` will be applied to all types of components. So it is a choice to set the init data and message type for every single type of component. Users can create a file named `Init.elm` in `Scene/Home/Components/Comp` to store them separately. Users can also use the option `--init` or `-i` to do this when creating the component. Don't forget to import it in `ComponentBase.elm`. ```bash messenger component -i Game Comp ``` Then draw a rectangle based on the component data in `view` function. But it will not be rendered on screen now since it has not been added to any layer yet. So let's add two components when initialize the layer and render them using `viewComponents`: ```elm import Scenes.Home.Components.Comp.Model as Rect import Scenes.Home.Components.Comp.Msg as RectMsg ... type alias Data = { components : List (AbstractComponent SceneCommonData UserData ComponentTarget ComponentMsg BaseData SceneMsg) } init : LayerInit SceneCommonData UserData LayerMsg Data init env initMsg = Data [ Rect.component ( RectangleInit <| RectMsg.Init 150 150 200 200 Color.blue ) env , Rect.component ( RectangleInit <| RectMsg.Init 200 200 200 200 Color.red ) env ] ... view : LayerView SceneCommonData UserData Data view env data = viewComponents env data.components ``` Note that `Data` and `view` function has been provided. Now one red rectangle on a blue one on screen. Then try to add a simple logic that when you left click the rectangle, it turns black: ```elm update : ComponentUpdate SceneCommonData Data UserData SceneMsg ComponentTarget ComponentMsg BaseData update env evnt data basedata = case evnt of MouseDown 0 pos -> if judgeMouseRect pos ( data.left, data.top ) ( data.width, data.height ) then ( ( { data | color = Color.black }, basedata ), [], ( env, False ) ) else ( ( data, basedata ), [], ( env, False ) ) _ -> ( ( data, basedata ), [], ( env, False ) ) ``` Then update all the components in layer using `updateComponents`, which has been done in `A/Model.elm` by default. === Message Blocking Our code seems to work well when we click the non-overlapping part of the two rectangles. But when we click the overlapping part of them, both of them turns black, which is not expected. The issue has been mentioned in @events. So we can solve this problem by changing the block value from `False` to `True`. ```elm ( ( { data | color = Color.black }, basedata ), [], ( env, True ) ) ``` What if add a layer `B` to the scene? Create a new layer B: ```bash messenger layer -c Game B ``` Then add it to the scene. Note to put `B` before `A` in the layer list so that layer `A` will update before `B` and render after `B`. See @layers and @events. Add two rectangle components to `B` in position (100, 100) and (250, 250) with size (200, 200), which means they will be overlapped by the components in `A`. Left click one component in A, the components in `B` do not turn black. It shows the block indicator will be passed by the order of updating. === Message Communication The work we did until now is just to update the component itself. But how to communicate with other components and layers? Let's add a logic that when user click one rectangle, the color of the other one turns green. First of all, set a message type in `Components/Comp/Init.elm` is necessary. Since the only message needed to pass is the color to change, add: ```elm type alias Msg = Color ``` Then add it to `ComponentMsg` in `ComponentBase.elm`. How a component reacts with the messages is determined in `updaterec`: ```elm updaterec : ComponentUpdateRec SceneCommonData Data UserData SceneMsg ComponentTarget ComponentMsg BaseData updaterec env msg data basedata = case msg of RectangleMsg c -> ( ( { data | color = c }, basedata ), [], env ) _ -> ( ( data, basedata ), [], env ) ``` Since the message is going to send from one component to the other, the target and matcher system need to be improved. An id can be added for every components to identify themselves. Let's add `id : Int` in `Data` and `InitData`. Then change `ComponentTarget` type into `Int`, and modify the `matcher`: ```elm matcher : ComponentMatcher Data BaseData ComponentTarget matcher data basedata tar = tar == data.id ``` `update` function is also need to be updated so that it can send message to other components when mouse left click. ```elm ( ( { data | color = Color.black }, basedata ) , List.filterMap (\n -> if n /= data.id then Just <| Other ( n, RectangleMsg green ) else Nothing ) <| List.range 0 1 -- use 0 1 because there are just 2 components , ( env, True ) ) ``` Run `make` and see the result now! Note that when click a component in one layer, the components in the other layer won't change their colors. So components cannot directly communicate across layers, they have to send message to each other via their parent layer. Now the issue is to communicate between layer and component. Sending message to components from a layer is similar to how from component. But a layer cannot directly deal with the messages from components in `updaterec` because the `updaterec` function of layer is used to handle the message from other layers. #align(center)[ #diagram( node-stroke: 1pt, edge-stroke: 1pt, node((-2, 0), [`A`], corner-radius: 0pt), edge((-2, 0), (2, 0), `LayerMsg`, "<->",), node((-3, 1), [Comp 1], corner-radius: 2pt), edge((-3, 1), (-2, 0), `ComponentMsg`, "<->"), node((-1, 1), [Comp 2], corner-radius: 2pt), edge((-1, 1), (-2, 0), `ComponentMsg`, "<->"), edge((-3, 1), (-1, 1), `ComponentMsg`, "<->"), node((2, 0), [`B`], corner-radius: 0pt), node((3, 1), [Comp 2], corner-radius: 2pt), edge((3, 1), (2, 0), `ComponentMsg`, "<->"), node((1, 1), [Comp 1], corner-radius: 2pt), edge((1, 1), (2, 0), `ComponentMsg`, "<->"), edge((3, 1), (1, 1), `ComponentMsg`, "<->"), ) ] Therefore, a handler for the messages from components should be added. We can simply modify the handler provide by default: ```elm handleComponentMsg : Handler Data SceneCommonData UserData LayerTarget LayerMsg SceneMsg ComponentMsg handleComponentMsg env compmsg data = case compmsg of SOMMsg som -> ( data, [ Parent <| SOMMsg som ], env ) OtherMsg msg -> case msg of RectangleMsg color -> let _ = Debug.log "msg" color in ( data, [], env ) _ -> ( data, [], env ) ``` In this way, components and their parent layer can communicate easily. === z-index Notice that the red rectangle is on the top of the blue one now. How to reverse their order to make the blue one on the top? A very simple way is to directly change their order in the initial list in layer. Since the render order depends on the order in list by default, the render order reverses in this way. However, this method doesn't work in some cases, especially when a new component is added during the game or the render order need to be changed during the game. They are the situation that z-index should be used. Users can decide the z-index dynamically based on data or environment in `view` function. Take the previous issue for example, the requirement can be implemented by adding a new value `order` in `data` which determines the z-index. The source code in this part can be found #link("https://github.com/linsyking/messenger-examples/tree/main/layers")[here]. == Portable Components *Warning. This feature is highly experimental.* To use portable components, you need to add `messenger-extra` to your dependencies. In brief, portable components are sets of interfaces that can be transformed automatically into user components. Portable components aim to provide more flexibilities on components. The characteristics of portable components include: - Users can use portable components across scenes and even across projects - Portable components could be written in a library - They do not have the base data - They cannot get the common data - Users need to set the `Msg` and `Target` type for every portable component - Users who use portable components need to provide a codec to transform the messages and targets *Warning*. Portable components are only useful when you are designing a component applicable to many different scenes (e.g. UI element). However, if your component is tightly connected to the scene (in most cases), please use scene prototype discussed in @sceneproto. It allows you to reuse scene and components. Think carefully whether you really need portable components before using it. Specifically, you need to provide codecs with the following types: ```elm type alias PortableMsgCodec specificmsg generalmsg = { encode : generalmsg -> specificmsg , decode : specificmsg -> generalmsg } type alias PortableTarCodec specifictar generaltar = { encode : generaltar -> specifictar , decode : specifictar -> generaltar } ``` #align(center)[ #diagram( node-stroke: 1pt, edge-stroke: 1pt, edge((-3, 0), (-1, 0), `generalmsg`, "->"), node((-1, 0), [`encode`], corner-radius: 0pt), edge((-1, 0), (0, 1), `specificmsg`, "->", bend: -20deg), node((0, 1), [Portable component], corner-radius: 2pt), edge((0, 1), (1, 0), `specificmsg`, "->", bend: -20deg), node((1, 0), [`decode`], corner-radius: 0pt), edge((1, 0), (3, 0), `generalmsg`, "->"), node(enclose: ((-1, 0), (0, 1), (1, 0)), stroke: (paint: blue, dash: "dashed"), inset: 8pt), node((0, 0), text(fill: blue)[Generated user component], stroke: none) ) ] After that, users can use the function below to generate user components from portable ones: ```elm translatePortableComponent : ConcretePortableComponent data userdata tar msg scenemsg -> PortableTarCodec tar gtar -> PortableMsgCodec msg gmsg -> bdata -> Int -> ConcreteUserComponent data cdata userdata gtar gmsg bdata scenemsg ``` Currently, portable components are experimental, so users need to handle portable components manually. === Example: Buttons First, define a portable component in `src/PortableComponents/Button/Model.elm`, where the "button" has its own special `Data`, `Target`, and `Msg`. Now we want to make it into a user component held by a layer. *Note.* There is no CLI command for users to directly generate a portable component. #grid(columns: (1fr, 1fr), [ #set align(center) ```elm type Msg = InitData (Maybe Data) | Pressed ``` ], [ #set align(center) ```elm type Target = Other | Me ``` ] ) On this purpose, we create a function to transform "button" to a user component in `Scenes/Home/Components/Button.elm` with basics defined in `Scenes/Home/Components/ComponentBase.elm`. The `ComponentMsg` and `ComponentTarget` are defined as below: #grid(columns: (1fr, 1fr), [ #set align(center) ```elm type ComponentMsg = ButtonInit Button.Data | ButtonPressed String | NullComponentMsg ``` ], [ #set align(center) ```elm type alias ComponentTarget = String ``` ] ) Then, in `Scenes/Home/Components/Button.elm`, we define the component generator by: ```elm component : Int -> ComponentTarget -> PortableComponentStorage SceneCommonData UserData ComponentTarget ComponentMsg BaseData SceneMsg component zindex gtar = let targetCodec : PortableTarCodec Button.Target ComponentTarget targetCodec = { encode = \_ -> Button.Other , decode = \_ -> gtar } msgCodec : PortableMsgCodec Button.Msg ComponentMsg msgCodec = { encode = \msg -> case msg of ButtonInit data -> Button.InitData (Just data) _ -> Button.InitData Nothing , decode = \msg -> case msg of Button.InitData _ -> NullComponentMsg Button.Pressed -> ButtonPressed gtar } in genPortableComponent Button.componentcon targetCodec msgCodec () zindex ``` Note that `gtar` is used to initialize the component, and `zindex` is the z-index property of the created component. Now the portable component `button` can be used as normal user components in the layer. === Use with User Components To validate that the portable component type has been successfully transformed into user components, users can add a sample component. Use the component in User Component part and simply modify it. To make things easy, remove the id and the update logic. When click the button, the rectangle is expected to turn yellow. But the logic of changing color doesn't need to be added in the `update` function of button: ```elm MouseDown 0 pos -> if judgeMouseRect pos data.pos data.size then ( data, [ Other ( OtherC, Pressed ) ], ( env, True ) ) else ( data, [], ( env, False ) ) ``` Instead, it should be added in the codec in `Components/Button.elm`, where the translator is stored. More specifically, to make the the buttons more general, users can determine what message they should pass when initialize every single one of them. ```elm component : Int -> ComponentTarget -> ComponentMsg -> PortableComponentStorage SceneCommonData UserData ComponentTarget ComponentMsg BaseData SceneMsg component zindex gtar gmsg = let ... msgCodec : PortableMsgCodec Button.Msg ComponentMsg msgCodec = ... decode = ... Button.Pressed -> gmsg ... in genPortableComponent Button.componentcon targetCodec msgCodec () zindex ``` Then initialize two buttons and a rectangle in one list in layer: ```elm init : LayerInit SceneCommonData UserData LayerMsg Data init env initMsg = Data [ Button.component 1 "Rect" (RectMsg yellow) (ButtonInit <| ButtonConfig.Data ( 0, 0 ) ( 100, 100 ) "Button 1") env , Button.component 1 "Rect" (RectMsg orange) (ButtonInit <| ButtonConfig.Data ( 300, 300 ) ( 100, 100 ) "Button 2") env , Rect.component ( RectInit <| RectMsg.Init 200 500 200 200 red ) env ] ``` Now the the requirement is simply implement since every specific button message `Other OtherC Pressed` will be decode as `Other ( "Rect", RectMsg yellow )`. Find the detailed example #link("https://github.com/linsyking/messenger-examples/tree/main/portable-components")[here]. Users can even make different translators for the same portable component type to implement different usages. And the same type of portable component can be used in different scenes by setting translators for every scene. See more usages about portable components in @componentgroup.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11D00.typ
typst
Apache License 2.0
#let data = ( ("MASARAM GONDI LETTER A", "Lo", 0), ("MASARAM GONDI LETTER AA", "Lo", 0), ("MASARAM GONDI LETTER I", "Lo", 0), ("MASARAM GONDI LETTER II", "Lo", 0), ("MASARAM GONDI LETTER U", "Lo", 0), ("MASARAM GONDI LETTER UU", "Lo", 0), ("MASARAM GONDI LETTER E", "Lo", 0), (), ("MASARAM GONDI LETTER AI", "Lo", 0), ("MASARAM GONDI LETTER O", "Lo", 0), (), ("MASARAM GONDI LETTER AU", "Lo", 0), ("MASARAM GONDI LETTER KA", "Lo", 0), ("MASARAM GONDI LETTER KHA", "Lo", 0), ("MASARAM GONDI LETTER GA", "Lo", 0), ("MASARAM GONDI LETTER GHA", "Lo", 0), ("MASARAM GONDI LETTER NGA", "Lo", 0), ("MASARAM GONDI LETTER CA", "Lo", 0), ("MASARAM GONDI LETTER CHA", "Lo", 0), ("MASARAM GONDI LETTER JA", "Lo", 0), ("MASARAM GONDI LETTER JHA", "Lo", 0), ("MASARAM GONDI LETTER NYA", "Lo", 0), ("MASARAM GONDI LETTER TTA", "Lo", 0), ("MASARAM GONDI LETTER TTHA", "Lo", 0), ("MASARAM GONDI LETTER DDA", "Lo", 0), ("MASARAM GONDI LETTER DDHA", "Lo", 0), ("MASARAM GONDI LETTER NNA", "Lo", 0), ("MASARAM GONDI LETTER TA", "Lo", 0), ("MASARAM GONDI LETTER THA", "Lo", 0), ("MASARAM GONDI LETTER DA", "Lo", 0), ("MASARAM GONDI LETTER DHA", "Lo", 0), ("MASARAM GONDI LETTER NA", "Lo", 0), ("MASARAM GONDI LETTER PA", "Lo", 0), ("MASARAM GONDI LETTER PHA", "Lo", 0), ("MASARAM GONDI LETTER BA", "Lo", 0), ("MASARAM GONDI LETTER BHA", "Lo", 0), ("MASARAM GONDI LETTER MA", "Lo", 0), ("MASARAM GONDI LETTER YA", "Lo", 0), ("MASARAM GONDI LETTER RA", "Lo", 0), ("MASARAM GONDI LETTER LA", "Lo", 0), ("MASARAM GONDI LETTER VA", "Lo", 0), ("MASARAM GONDI LETTER SHA", "Lo", 0), ("MASARAM GONDI LETTER SSA", "Lo", 0), ("MASARAM GONDI LETTER SA", "Lo", 0), ("MASARAM GONDI LETTER HA", "Lo", 0), ("MASARAM GONDI LETTER LLA", "Lo", 0), ("MASARAM GONDI LETTER KSSA", "Lo", 0), ("MASARAM GONDI LETTER JNYA", "Lo", 0), ("MASARAM GONDI LETTER TRA", "Lo", 0), ("MASARAM GONDI VOWEL SIGN AA", "Mn", 0), ("MASARAM GONDI VOWEL SIGN I", "Mn", 0), ("MASARAM GONDI VOWEL SIGN II", "Mn", 0), ("MASARAM GONDI VOWEL SIGN U", "Mn", 0), ("MASARAM GONDI VOWEL SIGN UU", "Mn", 0), ("MASARAM GONDI VOWEL SIGN VOCALIC R", "Mn", 0), (), (), (), ("MASARAM GONDI VOWEL SIGN E", "Mn", 0), (), ("MASARAM GONDI VOWEL SIGN AI", "Mn", 0), ("MASARAM GONDI VOWEL SIGN O", "Mn", 0), (), ("MASARAM GONDI VOWEL SIGN AU", "Mn", 0), ("MASARAM GONDI SIGN ANUSVARA", "Mn", 0), ("MASARAM GONDI SIGN VISARGA", "Mn", 0), ("MASARAM GONDI SIGN NUKTA", "Mn", 7), ("MASARAM GONDI SIGN CANDRA", "Mn", 0), ("MASARAM GONDI SIGN HALANTA", "Mn", 9), ("MASARAM GONDI VIRAMA", "Mn", 9), ("MASARAM GONDI REPHA", "Lo", 0), ("MASARAM GONDI RA-KARA", "Mn", 0), (), (), (), (), (), (), (), (), ("MASARAM GONDI DIGIT ZERO", "Nd", 0), ("MASARAM GONDI DIGIT ONE", "Nd", 0), ("MASARAM GONDI DIGIT TWO", "Nd", 0), ("MASARAM GONDI DIGIT THREE", "Nd", 0), ("MASARAM GONDI DIGIT FOUR", "Nd", 0), ("MASARAM GONDI DIGIT FIVE", "Nd", 0), ("MASARAM GONDI DIGIT SIX", "Nd", 0), ("MASARAM GONDI DIGIT SEVEN", "Nd", 0), ("MASARAM GONDI DIGIT EIGHT", "Nd", 0), ("MASARAM GONDI DIGIT NINE", "Nd", 0), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/draw/grouping.typ
typst
Apache License 2.0
#import "/src/process.typ" #import "/src/intersection.typ" #import "/src/path-util.typ" #import "/src/styles.typ" #import "/src/drawable.typ" #import "/src/vector.typ" #import "/src/util.typ" #import "/src/coordinate.typ" #import "/src/aabb.typ" #import "/src/anchor.typ" as anchor_ #import "/src/deps.typ" #import deps.oxifmt: strfmt #import "transformations.typ": move-to /// Hides an element. /// /// Hidden elements are not drawn to the canvas, are ignored when calculating bounding boxes and discarded by `merge-path`. All /// other behaviours remain the same as a non-hidden element. /// /// #example(``` /// set-style(radius: .5) /// intersections("i", { /// circle((0,0), name: "a") /// circle((1,2), name: "b") /// // Use a hidden line to find the border intersections /// hide(line("a.center", "b.center")) /// }) /// line("i.0", "i.1") /// ```) /// /// - body (element): One or more elements to hide #let hide(body) = { if type(body) == array { return body.map(f => { (ctx) => { let element = f(ctx) if "drawables" in element { element.drawables = element.drawables.map(d => { d.hidden = true return d }) } return element } }) } return body } /// Calculates the intersections between multiple paths and creates one anchor /// per intersection point. /// /// All resulting anchors will be named numerically, starting at 0. /// i.e., a call `intersections("a", ...)` will generate the anchors /// `"a.0"`, `"a.1"`, `"a.2"` to `"a.n"`, depending of the number of /// intersections. /// /// #example(``` /// intersections("i", { /// circle((0, 0)) /// bezier((0,0), (3,0), (1,-1), (2,1)) /// line((0,-1), (0,1)) /// rect((1.5,-1),(2.5,1)) /// }) /// for-each-anchor("i", (name) => { /// circle("i." + name, radius: .1, fill: blue) /// }) /// ```) /// /// You can also use named elements: /// /// #example(``` /// circle((0,0), name: "a") /// rect((0,0), (1,1), name: "b") /// intersections("i", "a", "b") /// for-each-anchor("i", (name) => { /// circle("i." + name, radius: .1, fill: blue) /// }) /// ```) /// /// You can calculate intersections with hidden elements by using @@hide(). /// /// - name (string): Name to prepend to the generated anchors. (Not to be confused with other `name` arguments that allow the use of anchor coordinates.) /// - ..elements (elements,string): Elements and/or element names to calculate intersections with. /// Elements referred to by name are (unlike elements passed) not drawn by the intersections function! /// - samples (int): Number of samples to use for non-linear path segments. A higher sample count can give more precise results but worse performance. #let intersections(name, ..elements, samples: 10) = { samples = calc.clamp(samples, 2, 2500) assert(type(name) == str and name != "", message: "Intersection must have a name, got:" + repr(name)) assert(elements.pos() != (), message: "You must at least give one element to intersections.") return (ctx => { let ctx = ctx // List of drawables to calc intersections for; // grouped by element. let named-drawables = () // List of drawables passed as elements to calc intersections for; // grouped by element. let drawables = () for elem in elements.pos() { if type(elem) == str { assert(elem in ctx.nodes, message: "No such element '" + elem + "' in elements " + repr(ctx.nodes.keys())) named-drawables.push(ctx.nodes.at(elem).drawables) } else { for sub in elem { let sub-drawables = () (ctx: ctx, drawables: sub-drawables, ..) = process.element(ctx, sub) if sub-drawables != none and sub-drawables != () { drawables.push(sub-drawables) } } } } let elems = named-drawables + drawables let pts = () if elems.len() > 1 { for (i, elem-1) in elems.enumerate() { for j in range(i + 1, elems.len()) { let elem-2 = elems.at(j) for path-1 in elem-1 { for path-2 in elem-2 { for pt in intersection.path-path( path-1, path-2, samples: samples ) { if pt not in pts { pts.push(pt) } } } } } } } let anchors = (:) for (i, pt) in pts.enumerate() { anchors.insert(str(i), pt) } return ( ctx: ctx, name: name, anchors: anchor_.setup( anchor => { anchors.at(anchor) }, anchors.keys(), transform: none, name: name ).last(), drawables: drawables.flatten() ) },) } /// Groups one or more elements together. This element acts as a scope, all state changes such as transformations and styling only affect the elements in the group. Elements after the group are not affected by the changes inside the group. /// /// #example(``` /// // Create group /// group({ /// stroke(5pt) /// scale(.5); rotate(45deg) /// rect((-1,-1),(1,1)) /// }) /// rect((-1,-1),(1,1)) /// ```) /// /// = parameters /// /// = Styling /// *Root* `group` /// /// == Keys /// #show-parameter-block("padding", ("none", "number", "array", "dictionary"), default: none, [How much padding to add around the group's bounding box. `none` applies no padding. A number applies padding to all sides equally. A dictionary applies padding following Typst's `pad` function: https://typst.app/docs/reference/layout/pad/. An array follows CSS like padding: `(y, x)`, `(top, x, bottom)` or `(top, right, bottom, left)`.]) /// /// = Anchors /// Supports compass, distance and angle anchors. However they are created based on the axis aligned bounding box of all the child elements of the group. /// /// You can add custom anchors to the group by using the `anchor` element while in the scope of said group, see `anchor` for more details. You can also copy over anchors from named child element by using the `copy-anchors` element as they are not accessible from outside the group. /// /// The default anchor is "center" but this can be overridden by using `anchor` to place a new anchor called "default". /// /// - body (elements, function): Elements to group together. A least one is required. A function that accepts `ctx` and returns elements is also accepted. /// - anchor (none, string): Anchor to position the group and it's children relative to. For translation the difference between the groups `"center"` anchor /// and the passed anchor is used. /// - name (none, string): /// - ..style (style): #let group(body, name: none, anchor: none, ..style) = { assert(type(body) in (array, function), message: "Incorrect type for body, expected an array or function. Instead got: " + repr(body)) // No extra positional arguments from the style sink assert.eq( style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos()), ) (ctx => { let style = styles.resolve(ctx.style, merge: style.named(), root: "group") let bounds = none let drawables = () let group-ctx = ctx group-ctx.groups.push((anchors: (:))) (ctx: group-ctx, drawables, bounds) = process.many(group-ctx, if type(body) == function {body(ctx)} else {body}) // Apply bounds padding let bounds = if bounds != none { let padding = util.as-padding-dict(style.padding) for (k, v) in padding { padding.insert(k, util.resolve-number(ctx, v)) } aabb.padded(bounds, padding) } // Calculate a bounding box path used for border // anchor calculation. let (center, width, height, path) = if bounds != none { (bounds.low.at(1), bounds.high.at(1)) = (bounds.high.at(1), bounds.low.at(1)) let center = aabb.mid(bounds) let (width, height, _) = aabb.size(bounds) let path = drawable.path( path-util.line-segment(( (bounds.low.at(0), bounds.high.at(1)), bounds.high, (bounds.high.at(0), bounds.low.at(1)), bounds.low, )), close: true) (center, width, height, path) } else { (none, none, none, none) } let (transform, anchors) = anchor_.setup( anchor => { let anchors = group-ctx.groups.last().anchors if type(anchor) == str and anchor in anchors { return anchors.at(anchor) } }, group-ctx.groups.last().anchors.keys(), name: name, default: if bounds != none { "center" } else { none }, offset-anchor: anchor, path-anchors: bounds != none, border-anchors: bounds != none, center: center, radii: (width, height), path: path, ) return ( ctx: ctx, name: name, anchors: anchors, drawables: drawable.apply-transform(transform, drawables), ) },) } /// Creates a new anchor for the current group. This element can only be used inside a group otherwise it will panic. The new anchor will be accessible from inside the group by using just the anchor's name as a coordinate. /// /// #example(``` /// // Create group /// group(name: "g", { /// circle((0,0)) /// anchor("x", (.4, .1)) /// circle("x", radius: .2) /// }) /// circle("g.x", radius: .1) /// ```) /// /// - name (string): The name of the anchor /// - position (coordinate): The position of the anchor #let anchor(name, position) = { assert(name != none and name != "" and not name.starts-with("."), message: "Anchors must not be none, \"\" or start with \".\"!") coordinate.resolve-system(position) return (ctx => { assert( ctx.groups.len() > 0, message: "Anchor '" + name + "' created outside of group!", ) let (ctx, position) = coordinate.resolve(ctx, position) position = util.apply-transform(ctx.transform, position) ctx.groups.last().anchors.insert(name, position) return (ctx: ctx, name: name, anchors: anchor_.setup(anchor => position, ("default",), default: "default", name: name, transform: none).last()) },) } /// Copies multiple anchors from one element into the current group. Panics when used outside of a group. Copied anchors will be accessible in the same way anchors created by the `anchor` element are. /// /// - element (string): The name of the element to copy anchors from. /// - filter (auto,array): When set to `auto` all anchors will be copied to the group. An array of anchor names can instead be given so only the anchors that are in the element and the list will be copied over. #let copy-anchors(element, filter: auto) = { (ctx => { assert( ctx.groups.len() > 0, message: "copy-anchors cannot be used outside of a group.", ) assert( element in ctx.nodes, message: "copy-anchors: Could not find element '" + element + "'", ) let calc-anchors = ctx.nodes.at(element).anchors let anchors = calc-anchors(()) if filter != auto { anchors = anchors.filter(a => a in filter) } let new = { let d = (:) for a in anchors { d.insert(a, calc-anchors(a)) } d } // Add each anchor as own element for (k, v) in new { ctx.nodes.insert(k, (anchors: (name => { if name == () { return ("default",) } else if name == "default" { v } }))) } // Add anchors to group ctx.groups.last().anchors += new return (ctx: ctx) },) } /// An advanced element that allows you to modify the current canvas context. /// /// A context object holds the canvas' state, such as the element dictionary, /// the current transformation matrix, group and canvas unit length. The following /// fields are considered stable: /// - `length` (length): Length of one canvas unit as typst length /// - `transform` (cetz.matrix): Current 4x4 transformation matrix /// - `debug` (bool): True if the canvas' debug flag is set /// /// #example(``` /// // Setting a custom transformation matrix /// set-ctx(ctx => { /// let mat = ((1, 0, .5, 0), /// (0, 1, 0, 0), /// (0, 0, 1, 0), /// (0, 0, 0, 1)) /// ctx.transform = mat /// return ctx /// }) /// circle((z: 0), fill: red) /// circle((z: 1), fill: blue) /// circle((z: 2), fill: green) /// ```) /// /// - callback (function): A function that accepts the context dictionary and only returns a new one. #let set-ctx(callback) = { assert(type(callback) == function) return (ctx => (ctx: callback(ctx)),) } /// An advanced element that allows you to read the current canvas context through a callback and return elements based on it. /// /// #example(``` /// // Print the transformation matrix /// get-ctx(ctx => { /// content((), [#repr(ctx.transform)]) /// }) /// ```) /// /// - callback (function): A function that accepts the context dictionary and can return elements. #let get-ctx(callback) = { assert(type(callback) == function) (ctx => { let body = callback(ctx) if body != none { let (ctx, drawables) = process.many(ctx, callback(ctx)) return (ctx: ctx, drawables: drawables) } return (ctx: ctx) },) } /// Iterates through all anchors of an element and calls a callback for each one. /// /// #example(``` /// // Label nodes anchors /// rect((0, 0), (2,2), name: "my-rect") /// for-each-anchor("my-rect", (name) => { /// content((), box(inset: 1pt, fill: white, text(8pt, [#name])), angle: -30deg) /// }) /// ```) /// /// - name (string): The name of the element with the anchors to loop through. /// - callback (function): A function that takes the anchor name and can return elements. #let for-each-anchor(name, callback) = { get-ctx(ctx => { assert( name in ctx.nodes, message: strfmt("Unknown element {} in elements {}", name, repr(ctx.nodes.keys())) ) for anchor in (ctx.nodes.at(name).anchors)(()) { if anchor == none { continue } move-to(name + "." + anchor) callback(anchor) } }) } /// Places elements on a specific layer. /// /// A layer determines the position of an element in the draw queue. A lower /// layer is drawn before a higher layer. /// /// Layers can be used to draw behind or in front of other elements, even if /// the other elements were created before or after. An example would be drawing /// a background behind a text, but using the text's calculated bounding box for /// positioning the background. /// /// #example(``` /// // Draw something behind text /// set-style(stroke: none) /// content((0, 0), [This is an example.], name: "text") /// on-layer(-1, { /// circle("text.north-east", radius: .3, fill: red) /// circle("text.south", radius: .4, fill: green) /// circle("text.north-west", radius: .2, fill: blue) /// }) /// ```) /// /// - layer (float, integer): The layer to place the elements on. Elements placed without `on-layer` are always placed on layer 0. /// - body (elements): Elements to draw on the layer specified. #let on-layer(layer, body) = { assert(type(layer) in (int, float), message: "Layer must be a float or integer, 0 being the default layer. Got: " + repr(layer)) assert(type(body) in (function, array)) return (ctx => { let (ctx, drawables, ..) = process.many(ctx, if type(body) == function { body(ctx) } else { body }) drawables = drawables.map(d => { if d.at("z-index", default: none) == none { d.z-index = layer } return d }) return ( ctx: ctx, drawables: drawables ) },) } // DEPRECATED TODO: Remove #let place-anchors(path, name, ..anchors) = { panic("place-anchors got removed. Use path anchors `(name: <element>, anchor: <number, ratio>)` instead.") } // DEPRECATED TODO: Remove #let place-marks(path, ..marks-style, name: none) = { panic("place-marks got removed. Use the `pos:` key of marks for manual mark positioning.") }
https://github.com/Jollywatt/typst-wordometer
https://raw.githubusercontent.com/Jollywatt/typst-wordometer/master/tests/word-count/test.typ
typst
MIT License
#import "/src/lib.typ": * #set page(width: 15cm, height: auto) #word-count(totals => [ Hello, stats are in! #totals ]) #block(fill: orange.lighten(90%), inset: 1em)[ #show: word-count One two three four. There are #total-words total words and #total-characters characters. ]
https://github.com/Mc-Zen/quill
https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/layout/gutter/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 0pt) #import "/src/quill.typ": * #box(fill: red, quantum-circuit( column-spacing: 0pt, row-spacing: 0pt, 10pt /*should be ignored*/, gate($H$), 5pt, 10pt, 5pt, gate($H$), 10pt, gate($H$), [\ ], 10pt, gate($H$), gate($H$), gate($H$), [\ ], 10pt, 20pt, gate($H$), gate($H$),20pt, gate($H$), ))
https://github.com/Mc-Zen/quill
https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/README.md
markdown
MIT License
# Tests for Quill Here, tests for the library are collected. There are - some unit tests testing the Typst code for things like correct gate and instruction creation as well as - output image comparisons for regression tests. The tests are instrumented using [typst-test](https://github.com/tingerrr/typst-test/).
https://github.com/EpicEricEE/typst-droplet
https://raw.githubusercontent.com/EpicEricEE/typst-droplet/master/tests/explicit/test.typ
typst
MIT License
#import "/src/lib.typ": dropcap #set page(width: 6cm, height: auto, margin: 1em) // Test explicitly passed first letter. #dropcap(square(size: 1em), gap: 1em)[A square is a square.] #dropcap(square(size: 1em), gap: 1em, height: 3, lorem(13)) #dropcap(square(), height: 14pt, gap: 1em, lorem(10)) #dropcap[\#1][The winner has won what was to win.] #dropcap(height: auto, gap: 1em)[ #figure(rect(), caption: [Rect]) ][ To the left is a rectangle inside a figure with a caption, that this text is wrapped around. ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/034%20-%20Dominaria/007_Return%20to%20Dominaria%3A%20Episode%207.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Return to Dominaria: Episode 7", set_name: "Dominaria", story_date: datetime(day: 25, month: 04, year: 2018), author: "<NAME>", doc ) Teferi walked out to the beach before dawn, to where he could see Zhalfir reflected in the sunrise. He wasn't the only one. If you stood in the right place on the shoreline, if the weather was just the right balance between overcast and bright sunlight, the ghost of Zhalfir's coastline was visible. The translucent gleaming towers and domes floated as if on clouds above the sea. #figure(image("007_Return to Dominaria: Episode 7/01.jpg", width: 100%), caption: [Zhalfirin Void | Art by Chase Stone], supplement: none, numbering: none) It was a pilgrimage still made here by many inhabitants of Femeref and other parts of Jamuraa. Some came to honor ancestors lost when the rift occurred, some came out of historical curiosity. This morning several groups stood on the beach, solemn and silent or talking animatedly as their children played in the surf. Others stood alone, like Teferi. He kept his distance, though the chances of him being recognized lessened with every century that passed. His own aging was now a slow process, but he had already long outlived his mortal enemies. The nearby town of Sewa had benefitted from selling supplies and lodging to the Zhalfir pilgrims and it bustled with activity all year, though Teferi only came in the cooler months. He had been wandering for the past several years, since the Mending, exploring Dominaria but never feeling the urge to settle down. When he had paid for his room in the hostel, the proprietor had said, "It must be a trial, to be named after the destroyer of Zhalfir." #emph[Destroyer of Zhalfir, that's a new one] , Teferi thought with a sigh. His explanation was well-practiced. "It's an old family name, and no one wanted to offend my great-grandmother." The proprietor had nodded sympathetically, and that had been that. As the day's heat rose with the sun, Teferi walked back up through the dunes, the wind pulling at his blue robes. He took the path to the road and passed more pilgrims headed toward the beach—another group with children, two women, and a man walking alone—and nodded absently to them as he passed. The road ran along terraced fields and reservoirs, which gave way to garden plots and shade trees, then went through the open gates in the town's outer wall. The market plaza bustled with activity, with stalls under colorful awnings selling all sorts of food and drinks and trinkets to the pilgrims and locals milling around. Most of the crowd had the dark or brown skin of Femeref or northern Jamuraa, but there were a few travelers from other parts of Dominaria in the crowd. Sewa was a good town to visit, and the oldest quarter had mosaics in its plazas and columned houses that reminded Teferi of his old home in Zhalfir. Teferi wasn't sure why Zhalfir had been so much on his mind since he'd given up his spark. Guilt, surely, but he knew he had done the right thing. Zhalfir lived on, separate and protected from the forces that would have devastated it. Except lately that thought had begun to feel~self-serving at best. It had been the right decision at the time. Now he was no longer sure. #emph[It's not as if you can do anything about it] , he told himself, weary with this internal argument. His Planeswalker spark had been needed to repair Shiv's time rift to prevent devastating destruction, and he had no power now to return Zhalfir. #figure(image("007_Return to Dominaria: Episode 7/02.jpg", width: 100%), caption: [Teferi, Mage of Zhalfir | Art by <NAME> & <NAME>], supplement: none, numbering: none) He found his way through the maze of streets, the high stone walls of houses to either side, passing the gates that led into their lush garden courts. As he entered the public fountain plaza, he saw two figures sitting on the low stone wall near the door of his hostel. Teferi kept walking, kept his face and body language neutral. Not many people outside the new mage academy in Tolaria West knew who he was anymore. After Shiv, he had avoided using magic, had moved from town to town in Jamuraa until he had outrun his reputation. No one here should know he was that Teferi, the time mage who had stolen Zhalfir away, but he still had old enemies who wouldn't mind seeing him dead. And possibly new enemies. There were rumors of the Cabal gaining strength outside of Otaria, though no one was quite sure how, or what had spurred their resurgence. As Teferi reached the hostel's covered patio, the two people sitting near the door stood up to confront him. With no preamble, the woman said, "They say in the market that you're called Teferi." "They say a lot of things," Teferi countered. She was a very lovely woman, with strong features and a confident bearing. Her long braids had been tied back and piled atop her head and she wore the loose pants, shirt, and hooded robe of a caravan drover. A whip with a well-worn handle hung from her belt. The man was broad and muscular, wearing a sword and a warrior's leather and metal jerkin, his dreadlocks ornamented with copper rings. From the darkness of their skin, they might be the children of Zhalfirin families left behind when Teferi had created the time rift, but so were many inhabitants of Femeref. It didn't necessarily mean they had come here with an ancient family vendetta to kill him. The man smiled, and in a more amiable tone said, "This is Subira, and I'm Kwende." Without waiting for Teferi to acknowledge the introduction, Subira said, "You were expecting a visit from a man called Maket." Teferi kept his face polite, though he wasn't sure whether to be baffled or suspicious. "I'm sorry, you have the wrong Teferi. I wasn't expecting to see anyone named Maket today, or any other day." Subira lifted her brows, clearly skeptical. "You weren't." It wasn't a question, but Teferi answered it anyway. "No, I wasn't." He leaned on his staff, intrigued. If this was the prelude to an assassination attempt, it was at least unique. "What is this about?" Watching him thoughtfully, Kwende explained, "Maket said he was coming to see you, that that was the reason he was traveling here from Suq'Ata." "I can't help what Maket said." Teferi was beginning to think it wasn't an assassination attempt after all, but an ordinary case of confused travelers misunderstanding one another. "You'll have to look for him elsewhere." "We don't need to look for him elsewhere," Subira said, her expression skeptical and grim. "He's dead." Teferi stared at her. Now he was more intrigued, and much warier. "Would you tell me why you're here?" She exchanged an opaque glance with Kwende, then finally said, "I need to find out what happened at my caravan. Maket was killed in our camp, and he said he was coming here to see someone called Teferi." This was all very odd. Teferi said, "I swear to you that I didn't know this Maket." He knew he should walk away, maybe even pack his few belongings and leave Sewa entirely. But his curiosity was piqued, and he asked, "How was he killed?" Kwende's expression was grave. "By magic. Or at least that's what the caravan's physician believes." #emph[Huh] , Teferi thought. "What sort of magic?" "We're not sure—none of us is a mage." Kwende lifted his brows inquiringly. "Are you?" Subira still watched him like a predator hoping for prey to break cover. Teferi decided not to answer that question. "It sounds like you need a magistrate." Subira held her suspicious stare for a moment more, then grimaced. "The magistrates in this town look on the caravan drovers as scapegoats for every crime that happens while we're here. I don't want my people harassed. I want to find out who did this and turn the culprit over to the town judiciary myself." Teferi could see her point. He said, "I'm sorry, I don't know anything about this man Maket." And if he was sensible, he would leave it at that. But he had never been sensible, especially where a mystery was concerned. And if this Maket had really been coming to see him, he should find out why. "Why did the physician think it was magic that killed him?" Kwende said, "Because it's been two days and his body is not showing any sign of rot." He held up a hand. "I know, the obvious solution is that he's still alive, but he's not breathing and he's as cold as a stone." #emph[This becomes more curious by the moment] , Teferi thought. "Perhaps I could take a look," he said. Subira's brows lowered. Such an expression of deep suspicion tinged with irony shouldn't make her more beautiful, but somehow it did. "So you are a mage then?" she said. Kwende studied him intently. That still wasn't a question Teferi wanted to answer. "I'm a scholar, I know about many things. And you don't seem to have any other options, unless you want to ask the magistrates for help." Subira eyed him, but then said, "A good point. Well, come on, then." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Teferi followed Subira and Kwende to the outskirts of the town, past the stables and cheaper hostels, then outside the wall to the rocky flats where the caravan's tents and wagons stood. Other travelers, mostly groups of pilgrims too poor to afford lodging in Sewa, had clustered close to the caravan camp for safety. The bluffs that sheltered the town from the worst of the desert winds gave some protection to the flats, but it was not a place where anyone would want to spend much time. As they walked, Teferi asked, "How well did you know Maket?" Subira said, "Not well. This was the first time he traveled on my caravan." She nodded to Kwende. "Kwende knew him better." Kwende shook his head a little. "We had traveled together for a time, before we joined up with the caravan to come here." #figure(image("007_Return to Dominaria: Episode 7/03.jpg", width: 100%), caption: [Excavation Elephant | Art by <NAME>], supplement: none, numbering: none) Teferi had assumed Kwende and Subira owned the caravan together, and felt a jolt of relief that they were apparently recent acquaintances. Then he shook his head at himself.#emph[Idiot] , he thought. He had no business thinking of potential romantic attachments, not now. And perhaps not for years yet, until people forgot he had ever existed. And that was a depressing thought, even for someone on his way to look at a dead man. He sighed deeply, and Subira threw him a quizzical look. She led the way through the camp to a tent that stood some distance away and was guarded by several caravan drovers. "We moved the body out here," she explained. Kwende added, "The other passengers insisted on it, afraid whatever he died of was catching." "It's a wise precaution," Teferi told them. "There are death spells intended to be spread to anyone who touches the victim." Startled, Subira paused, holding up the tent flap. "Really?" Kwende shrugged the concern aside. "The physician who examined him has come to no harm." "Well, not yet," Teferi said mildly, and ducked inside the tent. The dead man lay on a carpet, covered by a cloth, and Teferi pulled it aside. Teferi had wondered if the physician was wrong, if the man was actually alive and in the grip of some strange but natural paralysis. Maybe even some poison that could appear to lower the temperature of the body and disguise any sign of life. But as Teferi checked the man's eyes and pulse, he saw that wasn't the case. He saw something else, too. He said, "You and your physician were right, this isn't a natural death." Subira said, "So do you know him?" "No, I've never seen him before." Teferi sat back, watching her thoughtfully. "Someone has performed a spell or used a poison on your poor Maket to not only steal the life from his body, but to suspend and preserve it. It's done in such a way as to make it look like time magic." He pushed to his feet. Subira's eyes narrowed, and Kwende's expression held a certain wary tension. He said, "Was it?" "If this was time magic, he would be suspended and seem not to move or breathe, but he would be alive, his body would still be warm, and when released he would go on his way as if it never happened. Time magic also takes effort to maintain, and can't be held indefinitely." Teferi shrugged. "So if I was going to kill a man, I certainly wouldn't use time magic, at least not in that way." He smiled. "I know you think I did this. That's why you came looking for me." Subira glanced at Kwende, who was still watching Teferi like a man prepared to defend himself at any moment. She said, "Did you kill him?" Teferi told her, "Luckily for our burgeoning friendship, I did not." Kwende relaxed a little, no longer expecting an attack. Subira's gaze was thoughtful, and it was hard to tell if she believed Teferi's denial or not. "Maket told Kwende you were a time mage. I wasn't sure I believed him." "Neither was I," Kwende said. "But it seemed to explain~" He gestured to the body. "~this." Teferi looked down at Maket again, frowning. Someone who knew who Teferi was had obviously sent Maket on this journey, but then what was the point of killing him before he completed it? #emph[Was Maket collateral damage, or was the plot aimed at both of us?] Teferi wondered. "Hmm." Subira lifted her brows. "Is that all you've got to say?" "I always have plenty to say; it's one of my faults." Teferi grinned at her. "Did he tell you why he wanted to see me?" "No, and I didn't ask," Kwende said. He was still skeptical, though something in his bearing made Teferi think that while he certainly believed that Teferi was a powerful time mage, he didn't believe Teferi had killed Maket. "It was none of my business, and I had no idea it would become important later." Teferi nodded understanding. "Did you search his belongings?" "Not yet." Subira turned to lift the tent flap and gestured to one of the drovers. "Akime, go and bring Maket's baggage, please." "I'll get it," Kwende said as he ducked out. "It's in my tent." "Thank you," Subira called after him. She turned back to Teferi and they contemplated each other in silence. She finally said, "I was certain you were the culprit, so there was no need to look for clues, like a character in a story." Teferi had to tease her. "And now you know I'm not the culprit?" Subira's expression was ironic. "Let's say I'm open to other theories." "What other theories would those be?" Teferi was honestly curious. At the hostel, Subira had seemed more aggressively suspicious than Kwende, but she clearly had an open mind. Maybe Kwende had been just as suspicious, but better at hiding his real feelings. Subira folded her arms, studying him. "That Maket was sent here to kill you." That was far too close to the theory that Teferi was inclined toward. He hesitated, not sure what to say. There wasn't much reason for anyone to kill the pilgrim scholar of Zhalfir that Teferi had been pretending to be for the past several years, even if he was a time mage. Then Subira added, "I think you're not just a Teferi, but #emph[the] Teferi." They eyed each other for a long moment. Subira didn't seem appalled by the idea that she was facing the Destroyer of Zhalfir, but it was hard to tell. Teferi let his breath out and admitted, "If I am that Teferi~Let's say that someone being sent to kill me is not an unusual occurrence." Subira's brow furrowed. "But would they send only one assassin? I think you're far more dangerous than that." #figure(image("007_Return to Dominaria: Episode 7/04.jpg", width: 100%), caption: [Teferi, Timebender | Art by Zack Stella], supplement: none, numbering: none) Teferi kept his smile light. As much as he wanted to see it as flirting, he knew she was too straightforward for that and was simply speaking her mind. "Your confidence in me is gratifying." Subira's expression was serious. "I know a dangerous man when I see one." She knew he was dangerous, but she hadn't expressed any contempt or dismay. Teferi had to ask, "It doesn't bother you, knowing who I am?" Subira shrugged. "My family were always travelers. None were in Zhalfir when it~left." She added, "I was never raised to think of Zhalfir as a birthright that was stolen from me. I've also read about what the Phyrexian invasion was like, and seen the remnants. I can understand why you did it." She hesitated, then her mouth twisted a little in sympathy. "They say you don't have the power to bring it back. That must be~hard." Her simple acceptance of those facts made the knot of guilt in his heart loosen. "When I created the Zhalfir rift, I was so certain I was right, that I was saving my home from a horror that would utterly destroy it. Now I question my decision every day, but I have no power to change what I did." It was surprisingly easy to make the painful admission. He met her calm gaze and felt no urge to look away. This was the first time he had had an honest conversation with anyone in years, and it was almost making him dizzy. Subira nodded, accepting his confidence without comment. "So we know you have enemies. But if Maket was coming here to kill you, then who killed him?" "A good question." Teferi paced the tent, trying to concentrate on the problem at hand. "Perhaps Maket discovers a plan to kill me. He travels here to warn me, but the mage behind the plan kills him, and makes it appear that I did it." He glanced at Subira. "Then you go to the magistrate, I'm accused of the crime~" Subira tone was ironic. "And you meekly go into custody until you can prove your innocence." "No. I wouldn't let them arrest me. Being confined in a cell is not something~" Teferi decided not to finish that thought. It wasn't the same as being trapped in a time bubble, but it wasn't something he wanted to experience again. He would never let himself be imprisoned, and anyone who tried it would find out just how dangerous he was. "But the plan didn't work," Subira said, and made an impatient gesture. "It makes me wonder what whoever did this is thinking now. Or doing now." "Subira!" someone shouted from outside, his voice rough with alarm. Subira shoved the canvas aside and ran. Teferi ducked out after her and stopped in his tracks. "Uh-oh," he muttered. Rolling toward them out of the desert flats was a sandstorm. The wall of sand and dust loomed so large it was like a giant ocean wave, or an avalanche of rock tumbling off a mountain. It would hit the caravan with the same impact. Sewa, partially protected by the bluffs and its stone walls, would probably survive. What the storm would do to anyone caught outside, and the livestock and gardens and fields and everything needed to survive the next season, was a nightmare. Teferi strode toward where Subira and the drovers stood frozen in horror. It was too late to run, though from the shouts and screams from the tents and wagons, some were attempting it. "What is that?" Subira demanded. "An illusion?" "No, it's real." Teferi could feel it in the air, with a weight and electricity an illusion could never duplicate. "But not a coincidence," Subira said grimly. "A powerful mage could raise this out of nothing," Teferi said. "A not so powerful but knowledgeable mage could raise it with several different spells over a period of days, nudging various winds and air pressure systems. It's a complicated process—" "Which you can explain later if we survive." Subira made a helpless gesture. "Can you stop its time? Make it freeze?" It was too large, too diffuse. "No, I'm going to have to think of something else," Teferi said. He had already thought of something else, he just didn't know if he could make it work. He strode forward away from the others, to the edge of the shelf of rock. He lifted his staff to give himself an anchor and hoped he had estimated the distance correctly. #figure(image("007_Return to Dominaria: Episode 7/05.jpg", width: 100%), caption: [Syncopate | Art by <NAME>], supplement: none, numbering: none) He cast the spell to stop time for a bubble of air ten feet in front of him. Inside the bubble, drifting dust motes froze in place. Gathering every scrap of power he still had, Teferi stretched the bubble and made it longer, wider, higher, extending it seaward toward the bluffs that formed a natural windbreak for the town and outward to shield the caravan grounds, then up as high as he could stretch it. He made sure to keep it at an angle, using the sharp edges of the rock shelves as a guide. Logic said this should work; Teferi just hoped logic was right. An instant later the leading edge of the storm struck the time bubble and slid sideways along it, out toward the open desert. The wind howled in confusion and sand blasted against the bubble. Teferi held it as long as he could and then longer, darkness creeping in on the edges of his vision. The sheer effort made his body feel as light as gossamer, as if his feet floated above the ground. He wasn't sure if that was really happening or if it was what fainting felt like. He thought it might actually be a faint. Then he hit the ground and the bubble collapsed. Teferi braced himself for an unpleasant death. Being skinned and scraped raw by sand was not a good end to his life as an aging former planeswalking immortal. But the wind that flowed over him was no stronger than a normal harsh desert wind and the sand it carried was abrasive but not fatally so. It died away to fitful dust-filled gusts. Subira leaned over him and shook his shoulder. "Are you all right?" Teferi took a breath to answer and choked on sand. Subira hauled him into a sitting position and pounded him on the back until he could breathe. He wiped watering eyes and lifted his head to see the caravan grounds still intact, though tents, wagons, and agitated animals were covered with a layer of dust. People staggered around coughing and flailing, and those who had fled slowly returned, clearly amazed at their survival. The town looked in better shape, where confused inhabitants gathered on the rooftops and in the windows and doorways of the houses built back against the cliffs. #figure(image("007_Return to Dominaria: Episode 7/06.jpg", width: 100%), caption: [Sulfur Falls | Art by Cliff Childs], supplement: none, numbering: none) As Subira helped Teferi to his feet, her drover Akime ran to help. As they reached the tent, another drover ran up and said, "They're coming from the town, a crowd of magistrates. They say someone here brought the storm." "Who brought the storm?" Subira asked. As the man hesitated, she said, "Just tell me!" "Him, Teferi," the drover said. "That's a lie," Akime protested. "It was Teferi who saved us. We saw him with our own eyes. Why call a storm only to half kill himself stopping it?" Subira looked toward the town gate, where the approaching crowd was just visible. She said to Teferi, "This is the work of whoever is trying to kill you." She turned toward the drovers. "Who went to town? Who brought these people?" Akime gestured in confusion. "No one! We've all been here. Only Kwende—he went to arrange for Maket's body to be taken away." "Kwende?" Subira repeated. Her eyes widened. "Oh, for the love of—" "Kwende who told you Maket came here to look for me, who said Maket told him I was a time mage?" Teferi asked grimly. It was clear as glass now. Maket had probably been an innocent victim, a pilgrim traveling here who Kwende had befriended as part of his plot. Once Teferi had been taken by the magistrates and their mages, the sandstorm would have already destroyed the evidence in the caravan camp and the witnesses who might have contradicted whatever story Kwende meant to tell. Subira swore in angry realization. "I've been a fool! He's lied to me all along." She turned to Teferi. "Freeze time and run." "I can't, not now." Teferi was too exhausted to freeze more than a cloud of angry gnats. He had to recover before he could use his power again. "Then hide," Subira insisted. Teferi hesitated. Running away felt like~well, like running away. "But—" Subira hissed, "Hurry, you idiot!" So Teferi ran. He dodged through the tents, keeping the bulk of the wagons and the camel pens between himself and the group of magistrates. He headed toward the rocky hills at the far end of Sewa's wall. He would have to hide until nightfall, then find some way to get provisions before he left. The sword swing came out of nowhere and Teferi flung himself sideways. He hit the ground and rolled. Kwende leapt out from between the tents. He moved so fast he was like a blur. Teferi flung up a hand and accelerated time around the sword blade that drove down toward his chest. As it struck him it shattered into pieces, the steel rusted through. Kwende staggered, overbalanced, and Teferi scrambled away. He grabbed his fallen staff and managed to shove himself upright. Kwende recovered and drew two long knives, their blades gleaming with crystal. Teferi held his staff out like a man about to cast a devastating time spell, but he knew he had maybe one or two minor efforts left in him before he collapsed entirely. "Why are you doing this?" he demanded. #figure(image("007_Return to Dominaria: Episode 7/07.jpg", width: 100%), caption: [Kwende, Pride of Femeref | Art by Daarken], supplement: none, numbering: none) "It was the only way to get to you," Kwende said, his face hard with fury. "Traitor, destroyer!" He surged forward. Teferi managed to slow time a little, so Kwende's blindingly fast assault turned into a slow menacing pace. Teferi backed away. "You brought the storm." Kwende's grin was more like a grimace as he fought Teferi's waning power. "I hired a mage to make the spells that stirred the winds, and to make the death magic poison, so Maket would look as if he had been killed by a time mage." "Who are you?" Teferi demanded. If he was going to die, he wanted to know why. "My ancestor was Mageta the Lion." Kwende's gaze was as hard as iron. "He was in Ki'pamu when you destroyed it." "The general." Teferi's heart sank. He shook his head. "It wasn't destroyed—" "Liar!" Kwende's muscles bulged as he fought the time spell, and Teferi knew he couldn't hold on much longer. Then a whip cracked, wrapped around Kwende's arm, and jerked him aside. Subira stood with Akime and her other drovers behind her, all armed. She shouted, "Leave him alone, Kwende! He didn't kill Maket, and he didn't raise the storm. You did that. #emph[You] are the murderer!" Kwende's face showed only determination. "Because he was too powerful to kill, I had to weaken him first. You don't understand—" Subira waved a hand, her face incredulous. "Weaken him? And kill half the town and everyone in my caravan camp to do it? And what about Maket? Your precious Mageta would be proud of that, would he?" She grimaced in disgust. "We've traveled together, Kwende, and I know this isn't worthy of you." Kwende glared at her. "Maket was a thief and a murderer. I would never kill an innocent." Subira was unimpressed. "But you were willing to sacrifice everyone in the caravan camp to trap Teferi." Kwende shook his head, confusion overtaking his anger. "I knew he would turn the storm and save them." Subira was baffled. "You knew he would save them? But you still want to kill him." "He is the destroyer of Zhalfir!" Kwende shouted. "I have been told my whole life that my blood must have vengeance on his!" Teferi grimaced. Kwende had been raised on retribution and blood feud for Zhalfir, for the loss of people he had never known, a place he had never seen. He thought killing Teferi was his only way to freedom from that suffocating legacy. Teferi said, "Zhalfir is not destroyed! Go to the beach with the other pilgrims and look at it! It's still there, and if I could return it, I'd give my life to do it right this instant." Teferi controlled his voice with effort. "But my life isn't enough. I don't have the power anymore. It's impossible." Akime said urgently, "Subira, the magistrates are coming. We need to go." "Get my wagon. I'll go ahead with Teferi and meet you at our next stop," Subira told him. Kwende said raggedly, "No, I won't let you take him away. I've waited too long—" Subira dropped her whip and strode forward until she stood almost chest to chest with Kwende. She said, flatly, "Then kill me. That's the only way you'll stop me. You're either a murderer or you're not, Kwende. Choose." "Subira," Teferi said, his voice a dry rasp. He was terrified Kwende would drive his knife into her heart, and Teferi hadn't the power to stop him. "Don't. Don't risk yourself~Kwende, please don't kill her." She ignored him. Kwende stared at her as the moment stretched, then he slowly stepped back. He backed away and the drovers moved to get between him and Subira. Then Akime drove up with Subira's wagon. Kwende stood there as Subira shoved Teferi up onto the driver's box. As she climbed up to take the reins from Akime, Kwende said, "Why are you doing this for him?" "I'm doing it for both of you, you idiot," she said. "Now go away and do something worthwhile." Akime jumped down. As the wagon rolled away, Teferi said, "You could have been killed." He trembled with exhaustion, his powers depleted. "You're welcome," Subira said pointedly. "The least you can do is come with my caravan and keep the thieves and raiders and other threats off us. A time mage should be good at that." Teferi slumped back against the seat, giving the thought serious consideration. It was tempting. If he had to keep wandering, it would be good to do it with company. Company who he wouldn't have to lie to about who he really was. "For a while," he promised finally, as the wagon rolled over the bumpy road. "I'm not one to settle down." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "Niambi, be careful!" Teferi called to his daughter. She was running in the court again, chasing the dragonflies that clustered around the lilies in the fountain pond. The big house under the acacia trees was spacious and comfortable but old, and the flagstones paving the court were uneven. The cracks were just the right shape to catch unwary little feet. A few years ago, Subira had found someone else to run her caravan, and she had settled down with Teferi in this town near one of their old routes, long enough to have Niambi. She had gone back to her caravan now, visiting regularly as Teferi raised their daughter. #figure(image("007_Return to Dominaria: Episode 7/08.jpg", width: 100%), caption: [Adventurous Impulse | Art by Titus Lunter], supplement: none, numbering: none) Niambi bolted for the fountain but her sandal caught on a loose stone and she started to fall. Teferi cast the spell out of pure instinct and Niambi froze in mid-air. Teferi froze for an instant, too, startled at himself. He obviously hadn't lost any of his fighting reflexes, even after so long without using his magic. He stepped forward and circled Niambi, carefully examining her angle and trajectory, making sure there wasn't anything sharp or hard in her path. When he let her fall, she would land on the grass, possibly get a bruise or two, and hopefully learn a lesson about running in her sandals on the court's uneven flagstones. There was no other choice, really. But he thought how once there had been a choice, between Zhalfir's devastation and removing it from the world, preserving and trapping it. Thinking of Niambi preserved and trapped like a bone in amber turned his stomach. He couldn't keep her safe at the cost of her freedom and growth. It seemed obvious. It hadn't been obvious with Zhalfir, when there was no guarantee that anything of Zhalfir would have survived the Phyrexians. But so much of Dominaria had survived, if not intact, then with enough of itself left to grow anew and evolve. Teferi let his breath out. He had known for a long time that if he could return Zhalfir, he would do it. But no amount of soul-searching would give him the power. #emph[But some other sort of searching might] , Teferi thought. Urza had certainly created powerful artifacts that might help. It was worth looking into. But for now, he decided a compromise was best. He stepped around in front of Niambi and released his spell. As time moved around her again, she landed in her father's arms and laughed with delight.
https://github.com/sthenic/technogram
https://raw.githubusercontent.com/sthenic/technogram/main/src/requirements.typ
typst
MIT License
#import "to-string.typ": * /* Hook to replace references of kind 'requirement' with custom text. */ #let format-reference(it) = { if it.element != none and it.element.has("kind") and it.element.kind == "requirement" { link(it.target, it.element.caption.body) } else { it } } /* Add a set of requirements with the same prefix, e.g. '3.4'. */ #let requirements( prefix: none, release: none, ..reqs, ) = { let cells = () let prefix = [REQ #prefix] + if prefix != none [.] for req in reqs.pos() { let title = prefix + [#req.number] cells.push(grid.cell( [ /* Hidden figure with special 'kind' to create an achor point for future references. */ #hide(place[#figure( none, kind: "requirement", supplement: none, caption: title, outlined: true, )#if req.label != none { label(req.label) }]) #text(size: 0.8em, style: "italic")[#title] ])) cells.push(grid.cell(breakable: true, req.body)) } grid( columns: (75pt, auto), column-gutter: 0.5em, row-gutter: 1.5em, ..cells, ) } /* Add a requirement. */ #let req( number, label: none, body, ) = { ( number: number, label: label, body: body, ) } /* Add a requirement comment as a separate block with emphasized text. */ #let reqcomment(body) = { block(emph(body)) } /* Hook to check for duplicate requirements (ideally once at the end). */ #let check-for-duplicates() = context { let seen = () for it in query(figure.where(kind: "requirement")) { let body = to-string(it.caption.body) if body in seen { panic(body + " is already defined.") } else { seen.push(body) } } }
https://github.com/felsenhower/kbs-typst
https://raw.githubusercontent.com/felsenhower/kbs-typst/master/examples/10.typ
typst
MIT License
= Einführung #text(font: "Comic Sans MS")[ Mein erster Text mit Typst! ] #lorem(20)
https://github.com/pvdrz/cv
https://raw.githubusercontent.com/pvdrz/cv/main/cv.typ
typst
#set page( "us-letter", margin: 2cm, ) #set text( font: "Source Sans Pro", size: 8.7pt, weight: "light" ) #let purple = rgb("#684b75") #align(center)[ #text(size: 32pt, weight: "thin")[Christian] #h(0.5em) #text(size: 32pt, weight: "bold")[ <NAME>iz] #text(weight: "regular", size: 8pt, fill: purple)[#smallcaps[Software Engineer]] #text(weight: "regular", size: 8pt)[ #link("mailto:<EMAIL>")[ #h(0.5em) <EMAIL>] #h(0.5em) | #h(0.5em) #link("https://github.com/pvdrz")[ #h(0.5em) pvdrz] ] ] #let underlink(url, text) = { link(url, underline(text)) } #let experience_item(place, location, position, period, description) = { grid( columns: (60%, 1fr), align: (left, right), row-gutter: 0.75em, text(weight: "bold", size: 11pt)[#place], text(style: "italic", fill: purple)[#location], text(weight:"regular", size: 8pt)[#smallcaps[#position]], text(style: "italic", size: 8pt)[#period], ) text[#description] v(1em) } #let event_item(date, title, subtitle, location) = { grid( columns: (80%, 1fr), rows: 0.33em, align: (left, right), [#date #h(1em) #text(weight: "bold")[#title], #subtitle], text(style: "italic", fill: purple)[#location], ) } #let section(name) = { grid( columns: 2, text(weight: "bold", size: 16pt, fill: purple)[#name], line( stroke: 0.8pt, start: (3pt, 10pt), end: (100%, 10pt), ) ) } #section[Education] #pad( left: 1em, [ #experience_item( "Universidad de los Andes", "Bogotá, Colombia", "M. Eng. in Systems and Computing Engineering", "2016 - 2019", [ #smallcaps[Dissertation:] #underlink("https://repositorio.uniandes.edu.co/server/api/core/bitstreams/d8ff4d64-a163-4ac3-b136-7bd8a8244048/content", "Bounded generics over constants in Rust") ], ) #experience_item( "Universidad de los Andes", "Bogotá, Colombia", "B. S. in Physics", "2011 - 2016", [ #smallcaps[Dissertation:] #underlink("https://repositorio.uniandes.edu.co/server/api/core/bitstreams/97798913-0b9d-492f-b0ad-f763e94401fa/content", "A semi-analytic approach to formation processes in galaxies") #smallcaps[Publications:] #underlink("https://iopscience.iop.org/article/10.3847/0004-637X/832/2/169", "Quantifying and Controlling Biases in Estimates of Dark Matter Halo Concentration") ], ) ] ) #section[Experience] #pad( left: 1em, [ #experience_item( "Ferrous Systems", "Remote", "Software Engineer", "July 2022 - Present", [ - Work as a consultant on initiatives of the #underlink("https://www.memorysafety.org", "Prossimo project"), including #underlink("https://www.memorysafety.org/initiative/sudo-su/", `sudo-rs`), #underlink("https://www.memorysafety.org/initiative/tools/", `bindgen`) and #underlink("https://www.memorysafety.org/initiative/rustls/", `rustls`). - Part of the maintainer team for #underlink("https://ferrous-systems.com/ferrocene/", "Ferrocene"), an open source qualified Rust compiler toolchain. ] ) #experience_item( "IOTA Foundation", "Remote", "Software Engineer", [July 2020 - November 2020 #h(1em) ... #h(1em) April 2021 - June 2022], [ - Design and maintain #underlink("https://crates.io/crates/packable", "Packable"), a `#[no_std]` compatible binary serialization framework used by several Rust projects inside the foundation. - Port and optimize the CurlP hashing algorithm to Rust. - Debug and solve several concurrency issues inside the #underlink("https://github.com/iotaledger/bee/", "Bee") framework protocol. - Introduction of metrics to the Bee framework for performance tracking. ] ) #experience_item( "Universidad <NAME>", "Full-time Professor", "Bogotá, Colombia", "February 2020 - July 2020", [ - In charge of two sections of the Introduction to Computational Thinking course. - In charge of the mainstreaming process for introductory computer science courses. - Designed the syllabi for the courses on compilers and algorithm design for the new program in computer science. ] ) #experience_item( "Fermi National Accelerator Laboratory", "CMS Site Support Operator", "Batavia, Illinois, United States", "June 2019 - November 2019", [ Responsible for monitoring and troubleshooting all the services of the CMS distributed computing infrastructure. ] ) #experience_item( "Universidad de los Andes", "Graduate Assistant", "Bogotá, Colombia", "February 2018 - December 2018", [ In charge of one section and two laboratories of the undergraduate course in discrete mathematics and logic. ] ) #experience_item( "Rappi inc.", "Data Scientist", "Bogotá, Colombia", "June 2017 - March 2018", [ - Co-designer of the A / B testing platform used on the CPGs search engine. - Introduced human search quality rating into the Quality Assurance process for the CPGs search engine. - Developed a predictive model to estimate the time of payment of debt acquired by a courier. - Developed a data pipeline to monitor the distribution of supply and demand in near real time. ] ) ] ) #pagebreak() #pad( left: 1em, [ #experience_item( "<NAME>", "Graduate Research Assistant", "Bogotá, Colombia", "July 2016 - August 2017", [ - Developed a web application to monitor the state of the public transport service in Rio de Janeiro. - Study on traffic and mobility in order to characterize traffic accidents in Bogotá. - Study on taxes of urban delineation and characterization of taxpayers in order to detect anomalous requests of construction permits in Bogotá. ] ) ] ) #section[Open Source Contributions] #pad( left: 1em, [ #text(weight: "bold", size: 11pt)[Bindgen] - Contributed as a maintainer since the end of 2022. This includes triage and debug issues, mentor new contributors, improving the CI workflows, update the documentation, etc. - Implemented the `--wrap-static-fns` feature, which allows to generate bindings for static C functions. - Reorganize the code so adding new flags to bindgen is less error prone. - Improve build times by reducing the number of downloaded dependencies and reorganizing the codebase. #text(weight: "bold", size: 11pt)[Sudo-rs] - Implemented the execution layer of `sudo`. - Wrote a callback based polling API to handle signals and IO events. #text(weight: "bold", size: 11pt)[Miri] - Added support for Integer-Pointer casts in Miri to allow pointer arithmetic. - Implemented distinct primitives for interpreter-host communication in Miri. #text(weight: "bold", size: 11pt)[Rust] - Weakened several compiler checks to expand constant evaluation support. - Migrated several compiler diagnostics to ease diagnostic translation. ] ) #v(1em) #section[Events] #pad( left: 1em, [ #event_item("2020", "Speaker", "RustFest Global", "Online") #event_item("2019", "Scolarship Assistant", "RustFest", "Barcelona, Spain") #event_item("2016", "Scolarship Assistant", "24th Physics Summer School", "México, México") #event_item("2016", "Scolarship Assistant", "1st Mexican AstroCosmoStatistics School", "Guanajuato, México") #event_item("2013", "Speaker", "4th Colombian Congress in Astronomy and Astrophysics", "Online") #v(1em) ] ) #section[Relevant Courses] #pad( left: 1em, [ #event_item("2018", "Concurrency and Distribution", "Systems and Computing Engineering", "Uniandes") #event_item("2018", "Programing Paradigms", "Systems and Computing Engineering", "Uniandes") #event_item("2015", "Measure and Integration", "Mathematics", "Uniandes") #event_item("2015", "Computational Complexity", "Mathematics", "Uniandes") #event_item("2015", "Mathematical Logic", "Mathematics", "Uniandes") #event_item("2013", "Computational Physics", "Physics", "Uniandes") #event_item("2012", "Number Theory", "Mathematics", "Uniandes") #event_item("2012", "Discrete Mathematics", "Mathematics", "Uniandes") ] ) #v(1em) #section[Programming] #pad( left: 1em, [ #grid( columns: 2, [ #text(weight: "bold", size: 11pt)[Programming Languages] #box(height: 2em, columns(4)[ - Rust - C - Python - Bash - Elixir - Go ]) ], [ #text(weight: "bold", size: 11pt)[Other Tools] #box(height: 2em, columns(4)[ - Git - Docker - Nix - Valgrind - Heaptrack - Perf - Miri - Z3 ]) ] ) ] ) #v(1em) #section[Languages] #pad( left: 1em, [ #grid( columns: (1fr, 1fr, 1fr), [#text(weight: "bold")[Spanish] #h(1em) Native], [#text(weight: "bold")[English] #h(1em) C1], [#text(weight: "bold")[German] #h(1em) B1], ) ] )
https://github.com/Myriad-Dreamin/shiroa
https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/packages/shiroa/summary-internal.typ
typst
Apache License 2.0
#import "utils.typ": _store-content /// Internal method to convert summary content nodes #let _convert-summary(elem) = { // The entry point of the metadata nodes if metadata == elem.func() { // convert any metadata elem to its value let node = elem.value // Convert the summary content inside the book elem if node.at("kind") == "book" { let summary = node.at("summary") node.insert("summary", _convert-summary(summary)) } return node } // convert a heading element to a part elem if heading == elem.func() { return ( kind: "part", level: elem.depth, title: _store-content(elem.body), ) } // convert a (possibly nested) list to a part elem if list.item == elem.func() { // convert children first let maybe-children = _convert-summary(elem.body) if type(maybe-children) == "array" { // if the list-item has children, then process subchapters if maybe-children.len() <= 0 { panic("invalid list-item, no maybe-children") } // the first child is the chapter itself let node = maybe-children.at(0) // the rest are subchapters let rest = maybe-children.slice(1) node.insert("sub", rest) return node } else { // no children, return the list-item itself return maybe-children } } // convert a sequence of elements to a list of node if [].func() == elem.func() { return elem.children.map(_convert-summary).filter(it => it != none) } // All of rest are invalid none } /// Internal method to number sections /// meta: array of summary nodes /// base: array of section number #let _numbering-sections(meta, base: ()) = { // incremental section counter used in loop let cnt = 1 for c in meta { // skip non-chapter nodes or nodes without section number if c.at("kind") != "chapter" or c.at("section") == none { (c,) continue } // default incremental section let idx = cnt cnt += 1 let num = base + (idx,) // c.insert("auto-section", num) let user-specified = c.at("section") // c.insert("raw-section", repr(user-specified)) // update section number if user specified it by str or array if user-specified != none and user-specified != auto { // update number num = if type(user-specified) == str { // e.g. "1.2.3" -> (1, 2, 3) user-specified.split(".").map(int) } else if type(user-specified) == array { for n in user-specified { assert( type(n) == int, message: "invalid type of section counter specified " + repr(user-specified) + ", want number in array", ) } // e.g. (1, 2, 3) user-specified } else { panic("invalid type of manual section specified " + repr(user-specified) + ", want str or array") } // update cnt cnt = num.last() + 1 } // update section number let auto-num = num.map(str).join(".") c.at("section") = auto-num // update sub chapters if "sub" in c { c.sub = _numbering-sections(c.at("sub"), base: num) } (c,) } }
https://github.com/PgBiel/typst-ansi-gui
https://raw.githubusercontent.com/PgBiel/typst-ansi-gui/main/README.md
markdown
Apache License 2.0
# typst-ansi-gui Small GUI to highlight some Typst code using ANSI escape codes with [@frolozotl](https://github.com/frozolotl)'s amazing https://github.com/frozolotl/typst-ansi-hl Made with [iced](https://iced.rs/). You can **try it in your browser:** https://pgbiel.github.io/typst-ansi-gui/ ![app screenshot](https://github.com/PgBiel/typst-ansi-gui/assets/9021226/7a60c269-b78b-4ee6-a0a9-93966fa61d36) ## Usage Run the application, paste your Typst code at the top, and press `Highlight`. Then, press `Copy` to copy the generated ANSI. You can then paste the copied highlighted code on Discord as such: ```` ```ansi PASTE IT HERE ``` ```` You should now see your Typst code with proper syntax highlighting. ## Installing You can run `cargo install --git https://github.com/PgBiel/typst-ansi-gui --locked typst-ansi-gui`, which will build the application from source and install. ## Building Just run `cargo build` and the built application will be at `target/debug/typst-ansi-gui`. You can then run it. ## Formatting and Checking To format the code, run `cargo fmt`. To check, run `cargo clippy`. ## License Licensed under MIT or Apache-2.0, at your choice.
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/diagram-cetz-coords/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 1em) #import "/src/exports.typ" as fletcher: diagram, node, edge Polar coordinates #diagram( node-fill: teal.transparentize(60%), { node((0,0), [hello], name: <center>) let n = 16 for i in range(0, n) { node((rel: (i*360deg/n, 15mm), to: <center>), $ ast $, fill: none, inset: 0pt) edge(<center>, "<-") } } ) #pagebreak() Perpendicular coordinates #diagram( node-defocus: 0, node((100,100), $A$, name: <a>), edge("-"), node((rel: (1,1)), $B$, name: <b>), node((<a>, "|-", <b>), $A tack B$, name: <c>), edge(".."), node((<a>, "-|", <b>), $A tack.l B$, name: <c>), )
https://github.com/liuguangxi/erdos
https://raw.githubusercontent.com/liuguangxi/erdos/master/Problems/typstdoc/figures/p93_3.typ
typst
#import "@preview/cetz:0.2.1" #cetz.canvas(length: 10pt, { import cetz.draw: * let brown = orange.darken(40%) let os = 0.12 let sqr-mark(cor) = line(cor, (rel: (0.24, 0.24)), stroke: black+3.6pt) line((2.3, 0), (3, 2.8), stroke: yellow+3pt) line((3, 0), (4.3, 2.5), stroke: yellow+3pt) line((7.9, 0), (7.5, 3.5), stroke: yellow+3pt) line((8.4, 0), (8.8, 3.6), stroke: yellow+3pt) line((3, 2.8), (2.4, 5.2), stroke: yellow+3pt) line((4.3, 2.5), (4.9, 5.2), stroke: yellow+3pt) line((3, 2.8), (4.9, 5.2), stroke: yellow+3pt) line((2.4, 5.2), (4.9, 5.2), stroke: yellow+3pt) line((4.9, 5.2), (6.3, 5.2), stroke: yellow+3pt) line((7.5, 3.5), (6.3, 5.2), stroke: yellow+3pt) line((7.5, 3.5), (8.3, 6), stroke: yellow+3pt) line((8.8, 3.6), (8.3, 6), stroke: yellow+3pt) line((6.3, 5.2), (8.3, 6), stroke: yellow+3pt) line((2.4, 5.2), (1.5, 7.6), stroke: yellow+3pt) line((0.5, 6), (1.5, 7.6), stroke: yellow+3pt) line((2.4, 5.2), (3, 7.5), stroke: orange+3pt) line((1.5, 7.6), (3, 7.5), stroke: yellow+3pt) line((3, 7.5), (5, 7.6), stroke: yellow+3pt) line((4.9, 5.2), (5, 7.6), stroke: brown+3pt) line((5, 7.6), (6.3, 8), stroke: yellow+3pt) line((6.3, 5.2), (6.3, 8), stroke: orange+3pt) line((5, 7.6), (7.5, 8.6), stroke: yellow+3pt) line((7.5, 8.6), (8.9, 9.6), stroke: yellow+3pt) line((8.3, 6), (8.9, 9.6), stroke: yellow+3pt) line((8.3, 6), (9.5, 8.3), stroke: yellow+3pt) line((7.5, 8.6), (9.5, 8.3), stroke: yellow+3pt) line((8.3, 6), (7.5, 8.6), stroke: brown+3pt) line((8.9, 9.6), (10, 10.3), stroke: yellow+3pt) line((9.5, 8.3), (10.6, 8.9), stroke: yellow+3pt) line((10, 10.3), (10.6, 8.9), stroke: yellow+3pt) line((10.6, 8.9), (11.2, 8.4), stroke: yellow+3pt) line((11.8, 8.8), (11.2, 8.4), stroke: yellow+3pt) line((11.8, 8.8), (12, 10.3), stroke: yellow+3pt) line((11.2, 10), (10, 10.3), stroke: yellow+3pt) line((11.2, 10), (12, 10.3), stroke: yellow+3pt) line((10.6, 11.6), (10, 10.3), stroke: yellow+3pt) line((10.6, 11.6), (11.2, 10), stroke: yellow+3pt) line((11.5, 11.5), (11.2, 10), stroke: yellow+3pt) line((11.5, 11.5), (12, 10.3), stroke: yellow+3pt) sqr-mark((3-os, 2.8-os)) sqr-mark((4.3-os, 2.5-os)) sqr-mark((7.5-os, 3.5-os)) sqr-mark((8.8-os, 3.6-os)) sqr-mark((2.4-os, 5.2-os)) sqr-mark((4.9-os, 5.2-os)) sqr-mark((6.3-os, 5.2-os)) sqr-mark((8.3-os, 6-os)) sqr-mark((1.5-os, 7.6-os)) sqr-mark((3-os, 7.5-os)) sqr-mark((5-os, 7.6-os)) sqr-mark((6.3-os, 8-os)) sqr-mark((7.5-os, 8.6-os)) sqr-mark((8.9-os, 9.6-os)) sqr-mark((9.5-os, 8.3-os)) sqr-mark((10-os, 10.3-os)) sqr-mark((10.6-os, 8.9-os)) sqr-mark((11.2-os, 8.4-os)) sqr-mark((11.8-os, 8.8-os)) sqr-mark((12-os, 10.3-os)) sqr-mark((11.2-os, 10-os)) sqr-mark((10.6-os, 11.6-os)) sqr-mark((11.5-os, 11.5-os)) line((0, 0), (14, 0), stroke: 3pt) content((0.5, 12.5), anchor: "south-west", [*Wild Zebra*]) })
https://github.com/TheLukeGuy/backtrack
https://raw.githubusercontent.com/TheLukeGuy/backtrack/main/src/versions.typ
typst
Apache License 2.0
// Copyright © 2023 <NAME> // This file is part of Backtrack. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at <http://www.apache.org/licenses/LICENSE-2.0>. // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #let _v0-9-0-supported = { import "checks.typ": v0-9-0-supported v0-9-0-supported } #let from-v0-9-0-version(v0-9-0-version) = ( cmpable: v0-9-0-version, displayable: str(v0-9-0-version), observable: v0-9-0-version, ) #let post-v0-8-0 = if _v0-9-0-supported { (..components) => from-v0-9-0-version(version(..components)) } else { (..components) => { let flattened = () for component in components.pos() { if type(component) == type(()) { flattened += component.map(str) } else { flattened.push(str(component)) } } ( cmpable: 9223372036854775807, displayable: flattened.join("."), observable: flattened, ) } } #let _numbered = if _v0-9-0-supported { minor => from-v0-9-0-version(version(0, minor, 0)) } else { minor => ( cmpable: minor - 1, displayable: "0." + str(minor) + ".0", observable: (0, minor, 0), ) } #let v0-8-0 = _numbered(8) #let v0-7-0 = _numbered(7) #let v0-6-0 = _numbered(6) #let v0-5-0 = _numbered(5) #let v0-4-0 = _numbered(4) #let v0-3-0 = _numbered(3) #let v0-2-0 = _numbered(2) #let v0-1-0 = _numbered(1) #let _dated = if _v0-9-0-supported { (_, date, date-components) => { let version = version(0, 0, 0, date-components) (cmpable: version, displayable: date, observable: version) } } else { (versions-until-v0-1-0, date, date-components) => ( cmpable: -versions-until-v0-1-0, displayable: date, observable: (0, 0, 0) + date-components, ) } #let v2023-03-28 = _dated(1, "2023-03-28", (2023, 3, 28)) #let v2023-03-21 = _dated(2, "2023-03-21", (2023, 3, 21)) #let v2023-02-25 = _dated(3, "2023-02-25", (2023, 2, 25)) #let v2023-02-15 = _dated(4, "2023-02-15", (2023, 2, 15)) #let v2023-02-12 = _dated(5, "2023-02-12", (2023, 2, 12)) #let v2023-02-02 = _dated(6, "2023-02-02", (2023, 2, 2)) #let v2023-01-30 = _dated(7, "2023-01-30", (2023, 1, 30))
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/components/math.typ
typst
#import "/config.typ": theme #let hlp(math) = { set text(fill: theme.primary) math } #let hls(math) = { set text(fill: theme.secondary) math }
https://github.com/bckmnn/typst-planner
https://raw.githubusercontent.com/bckmnn/typst-planner/main/README.md
markdown
MIT License
# typst-planner Typst Package to create plans and timelines and overviews.
https://github.com/EliasRothfuss/vorlage_typst_doku-master
https://raw.githubusercontent.com/EliasRothfuss/vorlage_typst_doku-master/main/chapter/abstract.typ
typst
= Kurzfassung Problemstellung Ziel der Arbeit Vorgehen und angewandte Methoden Konkrete Ergebnisse der Arbeit, am besten mit quantitativen Angaben #pagebreak() = Abstract Variante sorgt dafür, das Abstract nicht im Inhaltsverzeichnis auftaucht English translation of the #emph[Kurzfassung]
https://github.com/loreanvictor/master-thesis
https://raw.githubusercontent.com/loreanvictor/master-thesis/main/thesis_typ/math_classes.typ
typst
MIT License
#let sees = math.class( "relation", sym.lt.tri ) #let sharesscope = math.class( "relation", sym.eq.delta ) #let blindto = math.class( "relation", sym.lt.tri.not ) #let selects = math.class( "relation", sym.lt.tri.eq ) #let success = math.class( "normal", sym.circle.filled ) #let semisuccess = math.class( "normal", sym.ast.circle ) #let failure = math.class( "normal", sym.circle.stroked )
https://github.com/maucejo/presentation_polylux
https://raw.githubusercontent.com/maucejo/presentation_polylux/main/src/_progress-bars.typ
typst
MIT License
#import "@preview/polylux:0.3.1": * #import "_config.typ": * #let cell = block.with( width: 100%, height: 100%, above: 0pt, below: 0pt, breakable: false ) #let slide-progress-bar = utils.polylux-progress( ratio => { grid( columns: (ratio * 100%, 1fr), cell(fill: colors.red), cell(fill: colors.gray.lighten(40%)) ) }) #let section-progress-bar = { context{ let ratio = states.sec-count.at(here()).first()/states.sec-count.final().first() grid( columns: (ratio*100%, 1fr), cell(fill: colors.red), cell(fill: colors.gray.lighten(40%)) ) } } #let appendix-progress-bar = { context{ let ratio = states.app-count.at(here()).first()/states.app-count.final().first() grid( columns: (ratio*100%, 1fr), cell(fill: colors.red), cell(fill: colors.gray.lighten(40%)) ) } } #let presentation-progress-bar = { context{ let ratio = states.sec-count.at(here()).first()/states.sec-count.final().first() grid( columns: (ratio*100%, 1fr), cell(fill: colors.red), cell(fill: colors.gray.lighten(40%)) ) } }
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/exers/a.typ
typst
#import "../cfg.typ": * #show: cfg $ "Prove that" ex(lim_(n -> oo) x_n) -> lim_(n -> oo) abs(x_n) = abs(lim_(n -> oo) x_n) $ That is, $all(epsilon > 0) ex(N) all(n > N): abs(abs(lim_(n -> oo) x_n) - abs(x_n)) < epsilon$ $ex(N) all(n > N): abs(lim_(n -> oo) x_n - x_n) < epsilon$ $all(a\, b): abs(abs(a) - abs(b)) <= abs(a - b)$ $all(n > N): abs(abs(lim_(n -> oo) x_n) - abs(x_n)) <= abs(lim_(n -> oo) x_n - x_n) < epsilon$
https://github.com/Zateros/dimat-tetelek
https://raw.githubusercontent.com/Zateros/dimat-tetelek/main/dimat_elso.typ
typst
#import "@preview/cetz:0.2.2" #let colorS = color.rgb("#B4D3B4") #set page( paper: "a4", numbering: "1.", margin: (x: 40pt, y: 40pt) ) #set document( author: "<NAME> & <NAME>", title: "Diszkrét matematika vizsgatételek" ) #set text( size: 15pt, font: "Times New Roman" ) #set par( justify: true, ) #set enum( numbering: "1.)", spacing: 15pt, ) #set block( below: 15pt ) #show heading.where(level: 2): it => block( breakable: false, fill: colorS, inset: 10pt, radius: 4pt, )[#it] #show heading.where(level: 1): it => align(center)[#it] #show heading.where(level: 3): it => [#underline[#it]] = Diszkrét matematika vizsgára kért tételek == Logika és halmazok + #box()[_Definiálja a predikátum fogalmát! Az alábbiak közül melyik predikátum:_ #set enum(numbering: "a)") + $P (x)$ + $P (x) and O(x)$; _ahol adott $x$ egész esetén $P (x)$ és $O(x)$ jelentése, hogy $x$ prı́m, ill. $x$ páratlan._ *Predikátum*: olyan változóktól függő kijelentések, amelyhez a változóik értékétől fűggően valamilyen igazságérték tartozik (elemi formulák, önállóan jelentéssel bíró kifejezések) Az *_a)_ lesz predikátum*, a _b)_ már _formulának_ számít. \ $arrow.long$ *Formula*: A formulák predikátumokból és logikai jelekből alkotott "mondatok" ] + #box()[ _Írja fel az _és_ és a _vagy_ igazságtábláját! \ Mi lesz az $I and (H or I)$ igazságértéke?_ - #grid( columns: (auto, auto), gutter: 15pt, table( columns: (auto,auto,auto), [$and$],[*Igaz*],[*Hamis*], [*Igaz*],[Igaz],[Hamis], [*Hamis*],[Hamis],[Hamis], ), table( columns: (auto,auto,auto), [$or$],[*Igaz*],[*Hamis*], [*Igaz*],[Igaz],[Igaz], [*Hamis*],[Igaz],[Hamis], ) ) - $underbrace(I and underbrace((H or I),"Igaz"), "Igaz") $ ] + #box()[ _Írja fel a tagadás és az implikáció igazságtábláját! \ Mi lesz az $A arrow.double B$ tagadása?_ - #grid( columns: (auto, auto), gutter: 15pt, table( columns: (auto,auto,auto), [$not$],[*Igaz*],[*Hamis*], [],[Hamis],[Igaz], ), table( columns: (auto,auto,auto), [$A$],[$B$],[$A arrow.double B$], [Igaz],[Igaz],[Igaz], [Igaz],[Hamis],[Hamis], [Hamis],[Igaz],[Igaz], [Hamis],[Hamis],[Igaz], ), ) - $A arrow.double B$ ekvivalens $not A or B$-vel, ennek a tagadása $A and not B$ lesz a De Morgan azonosságok miatt. ] + #box()[ _Mik az egzisztenciális és univerzális kvantorok? \ Mutasson példát olyan $H(x, y)$ kétváltozós predikátumra, melyre $forall x exists y H(x, y) eq.not exists y forall x H(x, y)$!_ - Egzisztenciális kvantor: $exists$ "létezik", univerzális kvantor: $forall$ "minden". Kvantorokkal "lokális változókat" képezhetünk. - Az első része azt állítja, hogy minden x számhoz létezik olyan szám, amire igaz ez a H predikátum. A másik része pedig, hogy létezik olyan szám, amihez minden x számmal igaz H predikátum. Így például, ha H predikátum azt állítja, hogy x és y különbsége páros, akkor az állítás igaz lesz, mert: - Minden számhoz létezik olyan szám, amivel a különbségük páros lesz (pl.: $x eq 3 "és" y_1 eq 0 space (x - y_1 eq 3 arrow.zigzag) "vagy" y_2 eq 1 arrow.r x - y_2 eq 2$) - Nem létezik olyan szám, ami minden számmal a különbsége páros #line(end: (100%,0%)) Igaz $eq.not$ Hamis ] + #box()[ _Definiálja logikai jelek segı́tségével halmazok metszetét és unióját! \ Mutasson egy-egy példát olyan _A, B, C_ halmazokra melyekre $(A union B) sect C$ megegyezik, ill. nem egyezik meg $A union (B sect C)$ halmazzal!_ - Legyen _A, B_ két halmaz - $A sect B eq {x colon x in A and x in B}$ - $A union B eq {x colon x in A or x in B}$ - $(A union B) sect C eq A union (B sect C)$ - pl.: $A eq {1,2}, B eq {1,2}, C eq {1,2}$ \ $arrow.r ({1,2} union {1,2}) sect {1,2} eq {1,2} union ({1,2} sect {1,2}) eq {1,2}$ - $(A union B) sect C eq.not A union (B sect C)$ - pl.: $A eq {1,2}, B eq {1}, C eq {2}$ \ \ $arrow.r ({1,2} union {1}) sect {2} &eq {2} \ {1,2} union ({1} sect {2}) &eq {1,2}$ \ #line(end: (100%,0%)) ${2} eq.not {1,2}$ ] + #box()[ _Definiálja halmazok szimmetrikus differenciáját! \ Mi lesz az $A eq {a, b, c}$ és $B eq {b, c, d}$ halmazok szimmetrikus differenciája?_ - $A triangle.t.small B eq (A \\ B) union (B \\ A) eq (A union B) \\ (A sect B) eq {a colon (a in A) plus.circle (b in B)}$ - ${a,b,c} triangle.t.small {b,c,d} eq ({a,b,c} \\ {b,c,d}) union ({b,c,d} \\ {a,b,c}) eq {a} union {d} eq {a,d}$ ] == Relációk + #box()[ _Definiálja a binér reláció fogalmát! \ Mutasson két példát relációra az $X eq {a, b, c}$ és $Y eq {1, 2, 3}$ halmazok között!_ - *Binér reláció:* Legyen $X, Y$ két tetszőleges halmaz. Ekkor az $R subset X times Y$ egy (binér) reláció az $X, Y$ halmaz között. Ha $X eq Y$ , akkor $R subset X times X$ egy (binér) reláció $X$-en. #align(center)[ #cetz.canvas({ import cetz.draw: * grid((0,0), (6,6), name: "gr", stroke: blue) set-style(mark: (end: ">"), fill: black) line((0,-0.5), (0,6.5), name: "y") line((-0.5,0), (6.5,0), name: "x") content("x.mid", [$X$], anchor: "north", padding: .2) content("y.mid", [$Y$], anchor: "east", padding: .4) content("gr.north-east", [$X times Y$], anchor: "north-east", padding: -0.6) set-style(fill: rgb(204, 255, 204), stroke: none) rotate(z: 35deg) circle((4.5,0), radius: (1.75, 1), name: "hz") content("hz.center", [$R$]) }) //TODO - Pl.: - *Descartes-szorzat ($X times Y$)*: \ $X times Y eq {(a,1),(a,2),(a,3),(b,1),(b,2),(b,3),(c,1),(c,2),(c,3)}$ - *Descartes-szorzat ($Y times X$)*: \ $Y times X eq {(1,a),(1,b),(1,c),(2,a),(2,b),(2,c),(3,a),(3,b),(3,c)}$ ]] + #box()[ _Definiálja relációk értelmezési tartományát és értékkészletét! \ Mi lesz az $R eq {(a, 1), (a, 2), (b, 1), (b, 4)} subset {a, b, c, d} times {1, 2, 3, 4}$ reláció értelmezési tartománya és értékkészlete?_ - Legyen $R subset X times Y$ egy reláció - R értelmezési tartománya: $"dmn"(R) eq {x in X: exists y in Y: (x,y) in R}$ - R értékkészlete: $"rng"(R) eq {y in Y: exists x in X: (x,y) in R}$ #align(center)[#cetz.canvas({ import cetz.draw: * content((0,0), [a], name: "a") content((0,-1), [b], name: "b") content((0,-2), [c], name: "c") content((0,-3), [d], name: "d") content((3,0), [1], name: "1") content((3,-1), [2], name: "2") content((3,-2), [3], name: "3") content((3,-3), [4], name: "4") content(("a",1.5,"1"), [$R$], anchor: "south", padding: .5) set-style(mark: (end: ">"), stroke: green, fill:green) line("a", "1") line("a", "2") line("b", "1") line("b", "4") })] - $"dmn"(R) eq {a,b}$ - $"rng"(R) eq {1,2,4}$ ] + #box()[ _Definiálja relációk kompozı́cióját! \ Legyen $R eq {(a, 1), (a, 2), (b, 1), (b, 4)} "és" S eq {(1, alpha), (1, beta), (2, alpha), (3, gamma)}.$ Mi lesz az $S circle.stroked.tiny R$ kompozı́ció?_ - Legyenek _R_ és _S_ binér relációk. Ekkor az $R circle.stroked.tiny S$ kompozı́ció (összetétel, sorozat) reláció: $R circle.stroked.tiny S eq {(x,y) colon exists z colon (x,z) in S, (z,y) in R}$ #align(center)[#cetz.canvas({ import cetz.draw: * content((0,0), [a], name: "a") content((0,-1), [b], name: "b") content((0,-2), [c], name: "c") content((0,-3), [d], name: "d") content((3,0), [1], name: "1") content((3,-1), [2], name: "2") content((3,-2), [3], name: "3") content((3,-3), [4], name: "4") content((6,0), [$alpha$], name: "al") content((6,-1), [$beta$], name: "be") content((6,-2), [$gamma$], name: "ga") content((6,-3), [$delta$], name: "de") content(("a",1.5,"1"), [$R$], anchor: "south", padding: .5) content(("1",1.5,"al"), [$S$], anchor: "south", padding: .5) set-style(mark: (end: ">"), stroke: green, fill:green) line("a", "1") line("a", "2") line("b", "1") line("b", "4") set-style(mark: (end: ">"), stroke: blue, fill:blue) line("1", "al") line("1", "be") line("2", "al") line("3", "ga") })] - $S circle.stroked.tiny R eq {(a,alpha),(a,beta),(b,alpha),(b,beta)}$ #align(center)[#cetz.canvas({ import cetz.draw: * content((0,0), [a], name: "a") content((0,-1), [b], name: "b") content((0,-2), [c], name: "c") content((0,-3), [d], name: "d") content((3,0), [1], name: "1") content((3,-1), [2], name: "2") content((3,-2), [3], name: "3") content((3,-3), [4], name: "4") content((6,0), [$alpha$], name: "al") content((6,-1), [$beta$], name: "be") content((6,-2), [$gamma$], name: "ga") content((6,-3), [$delta$], name: "de") content(("a",1.5,"1"), [$R$], anchor: "south", padding: .5) content(("1",1.5,"al"), [$S$], anchor: "south", padding: .5) set-style(mark: (end: ">"), stroke: gray, fill:gray) line("a", "1") line("a", "2") line("b", "1") line("b", "4") set-style(mark: (end: ">"), stroke: rgb(36, 36, 36), fill:rgb(36, 36, 36)) line("1", "al") line("1", "be") line("2", "al") line("3", "ga") set-style(mark: (end: ">"), stroke: red, fill:red) line("a", "al") line("a", "be") line("b", "al") line("b", "be") })] ] + #box()[ _Definiálja a szimmetrikus relációkat! \ Szimmetrikus-e az $R eq {(1, 2), (1, 3), (2, 3), (3, 1)} subset {1, 2, 3} times {1, 2, 3}$ reláció?_ - Legyen $R subset X times X$. R reláció szimmetrikus, ha $forall x, y in X colon x R y arrow.double y R x$ (pl.: $eq, K$) \ $arrow.r space K eq {(x,y) in RR times RR colon abs(x - y) lt.eq 1} "(közelségi reláció)"$ - Nem, mivel $(1,2) in R, "de" (2,1) in.not R "és" (2,3) in R, "de" (3,2) in.not R$ ] + #box()[ _Definiálja a reflexı́v relációkat! \ Reflexı́v-e az $R eq {(1, 2), (1, 3), (2, 3), (3, 1)} subset {1, 2, 3} times {1, 2, 3}$ reláció?_ - Legyen $R subset X times X$. R reláció reflexı́v, ha $forall x in X colon x R x$ (pl.: $eq, lt.eq, subset, bar, K$) - Nem reflexı́v, mert $(1,1) in.not R, (2,2) in.not R, (3,3) in.not R$. ] + #box()[ _Definiálja a tranzitı́v relációkat! \ Tranzitı́v-e az $R eq {(1, 2), (1, 3), (2, 3), (3, 1)} subset {1, 2, 3} times {1, 2, 3}$ reláció?_ - Legyen $R subset X times X$. R reláció tranzitı́v, ha $forall x,y,z in X colon x R y and y R z arrow.double x R z$ (pl.: $eq, lt.eq, subset, bar$) - Nem, mivel $(2,3) in R, (3,1) in R, "de" (2,1) in.not R$. ] + #box()[ _Definiálja az ekvivalencia reláció fogalmát! \ Adjon két különböző példát ekvivalencia relációra az $X eq {1, 2, 3}$ halmazon!_ - Egy _R_ reláció ekvivalencia reláció, ha reflexı́v, tranzitı́v és szimmetrikus. - pl.: - $R eq {(1,1), (2,2), (3,3)} subset X times X$ - $R eq {(1,1), (1,2),(1,3),(2,1), (2,2), (2,3),(3,1), (3,2), (3,3)} subset.eq X times X$ ] + #box()[ _Definiálja az osztályozás fogalmát! \ Adjon két különböző példát osztályozásra az $X eq {1, 2, 3}$ halmazon!_ - Egy _X_ halmaz részhalmazainak _O_ rendszerét osztályozásnak nevezzük, ha - _O_ elemei páronként diszjunkt nemüres halmazok - $union O eq X$ - pl.: - $O eq {{1,3},{2}}$ - $O eq {{1},{2},{3}}$ ] #pagebreak() == Komplex számok + #box()[ _Definiálja komplex számok trigonometrikus alakját! \ Mi lesz a $z eq 1 + i in CC$ szám trigonometrikus alakja?_ - Legyen $z eq a plus b i in CC \\ {0}$. - Az $r eq abs(z)$ az $(a,b) in RR^2$ vektor hossza - A $phi eq arg(z) in [0,2pi)$ az $(a,b)$ vektor irányszöge, a $z$ argumentuma. - Ekkor $a eq r cos phi "és" b eq r sin phi$, így $z eq r(cos phi plus i sin phi)$ #align(center)[ #cetz.canvas({ import cetz.draw: * set-style(mark: (end: ">"), fill: black) line((0,-0.5), (0,4.5), name: "y") line((-0.5,0), (6.5,0), name: "x") line((0,0), (4,2.5), name: "diag") set-style(mark: (end: none), stroke: (dash: "dashed")) line((0,2.5), (4,2.5), name: "xproj") line((4,0), (4,2.5), name: "yproj") content("xproj.start", anchor: "east", padding: .3, [$b eq "Im"(z)$]) content("yproj.start", anchor: "north", padding: .3, [$a eq "Re"(z)$]) content("diag.end", anchor: "west", padding: .3, [$z eq a plus b i$]) content("diag.mid", angle: "diag.end", anchor: "south", padding: .2, [$r eq abs(z)$]) set-style(fill: none, stroke: (dash: none)) arc((2,0),start: 0deg, stop: 65deg, name: "deg") content("deg.mid", anchor: "east", padding: .4, [$phi$]) }) ] - $z eq sqrt(2)(cos pi / 4 plus i sin pi / 4)$ - $r eq abs(z) eq sqrt(1^2 plus 1^2) eq sqrt(2)$ - $sin phi eq 1 / abs(z) eq 1 / sqrt(2) arrow.double phi eq pi / 4$ ] + #box()[ _Mondja ki a szorzásra vonatkozó Moivre azonosságot! \ Mi lesz a $z eq 3(cos(pi/3) + i dot sin(pi/3))$ és $w = 7(cos((5pi)/6)+i dot sin((5pi)/6))$ számok szorzatának trigonometrikus alakja?_ - Legyen $z, w in CC \\ {0}$ nem-nulla komplex számok: $ z eq abs(z)(cos phi plus i sin phi), w eq abs(w)(cos psi plus i sin psi). $ Ekkor $ z w eq abs(z) abs(w)(cos (phi plus psi) plus i sin (phi plus psi)) $ - $z w eq 3 dot 7(cos (pi/3 plus (5pi)/6) plus i sin (pi/3 plus (5pi)/6)) eq 21(cos ((7pi)/6) plus i sin ((7pi)/6))$ ] + #box()[ _Mondja ki az osztásra vonatkozó Moivre azonosságot! \ Mi lesz a $z eq 3(cos(π/3) + i dot sin(π/3))$ és $w eq 7(cos((5pi)/6) + i dot sin((5pi)/6))$ számok hányadosának trigonometrikus alakja?_ - Legyen $z, w in CC \\ {0}$ nem-nulla komplex számok: $ z eq abs(z)(cos phi plus i sin phi), w eq abs(w)(cos psi plus i sin psi). $ Ekkor $ z / w eq abs(z) / abs(w)(cos (phi minus psi) plus i sin (phi minus psi)) $ - $z / w eq 3 / 7(cos (pi/3 minus (5pi)/6) plus i sin (pi/3 minus (5pi)/6)) eq 3 / 7(cos (-(3pi)/6) plus i sin (-(3pi)/6))$ ] + #box()[_Mondja ki a hatványozásra vonatkozó Moivre azonosságot! \ Mi lesz a $z = 3(cos(π/3) + i dot.op sin(π/3))$ számok tizenkettedik hatványának trigonometrikus alakja?_ \ \ Legyen $z in CC \\ {0}$ nem-nulla komplex számok: $ z eq abs(z) (cos(phi) + i sin(phi)) $ és legyen $n in NN$. Ekkor $z^n eq abs(z)^n (cos n phi + i sin n phi)$ \ \ $z eq 3(cos(pi/3) + i sin(pi/3))$ $ z^12 eq abs(3)^12 (cos 12 (pi/3) + i sin 12(pi/3)) eq 3^12 (cos 4 pi + i sin 4 pi) eq \ eq 3^12 (cos 0 + i sin 0) eq 3^12 ( 1+0i) eq 3^12 $ ] + _Adott $w eq.not 0$ komplex szám és $n ≥ 1$ egész esetén mik lesznek a $z^n = w$ komplex megoldásai? \ Mondja ki a megfelelő tételt! Hány megoldása van a $z^3 = −1$ egyenletnek komplex számok körében?_ \ \ Legyen $w in CC \\ {0}$ komplex szám $w eq abs(w) (cos psi + i sin psi)$ trigonometrikus alakkal. $z^n eq w, space z in CC$ egyenlet megoldásai: $ z_k eq abs(w)^(1/n) (cos phi_k + i sin phi_k): phi_k = psi/n + (2k pi)/n, space k eq 0,1,dots,n-1 $ $ z^3 eq -1 arrow.double.long z eq root(3,-1) arrow.double.long z eq root(3,1)(cos((pi+2k pi)/3)+i sin((pi + 2k pi)/3)) $ Egyenletbe $k = 0,1,2$-re különbőző eredményt kapunk, tehát a $z^3 eq -1$ egyenletnek 3 megoldása van. == Kombinatorika + #box()[_Hányféleképpen lehet n különböző elemet sorba állítani? \ Mondja ki a megfelelő összefüggést! \ Hányféleképpen lehet 5 különböző könyvet a polcra felrakni?_ \ \ $n$ elemből az első helyre $n$-féleképpen választhatunk, a második helyre $n-1$ féleképpen és így tovább... Így a szorzás szabály szerint az összes lehetőségek száma: $n dot.op (n-1) dot.op dots dot.op 2 dot.op 1 eq n!$ \ 5 különböző könyvet $5! eq 120$ féleképpen lehet sorbaállítani.] + _Hányféleképpen lehet n, nem feltételen különböző elemet sorba állítani? Mondja ki a megfelelő összefüggést! \ Hányféleképpen lehet 7 hosszú szót lehet képezni három darab `’a’`, két darab `’b’` és három darab `’c’` segítségével?_ \ \ Ha minden elem között különbséget teszünk, akkor $n!$ lehetséges sorrend van.\ Azonban ekkor egy lehetőséget többször is számoltunk. Nevezetesen, ha az $i$-edik elemből $k_i$ darab van, akkor a ismétlés nélküli permutáció és a szorzat-szabály szerint egy sorrendet $(k_1)! dot.op dots dot.op (k_m)!$-szer számoltunk. \ Így az osztás-szabály szerint, ha az azonos típusú elemek között nem teszünk különbséget, akkor $(k_1 + k_2 + dots + k_m )!/(k_1 ! dot k_2 ! dot dots dot k_m !)$ lehetséges sorrend van. \ \ $7!/(3! dot 2! dot 3!)$ féleképpen. + _Hányféleképpen lehet k elemet választani egy n elemű halmazból, ha a kiválasztás sorrendje számít és egy elemet többször is felhasználhatunk? \ Hány 7 hosszú szót képezhetünk az `’a’, ’b’` és `’c’` karakterek felhasználásával?_ \ \ Mindegyik helyre $n$-féleképpen válaszhatunk elemet, tehát a szorzat-szabály 2 szerint, a lehetséges választások száma $n^k$ lehetséges sorrend van \ \ Mivel 3 fajta karakterünk van és 7 helyre kell választanunk, ezért $3^7$ féleképpen. + #box()[_Hányféleképpen lehet k elemet kiválasztani egy n elemű halmazból, ha a kiválasztás sorrendje számít és egy elemet csak egyszer választhatunk? \ Hány 5 hossz szót képezhetünk az `’a’, ’b’, ’c’, ’d’, ’e’, ’f’` és `’g’` karakterek felhasználásával, ha egy karaktert csak egyszer használhatunk?_ \ \ 1. helyre $n$-féleképpen válaszhatunk, 2. helyre $n-1$-féleképpen,..., a $k$-adik helyre $n-k+1$-féleképpen választanunk. Így a szorzat-szabály 2 szerint a lehetséges választások száma $n(n-1)(n-2)...(n-k+1) eq n!/(n-k)!$ lehetséges sorrend van. \ \ $n$ itt a betünk száma azaz 7 és a $k$ szó hossz azaz 5, tehát $7!/(7-5)!$ lehetséges sorrend van.] + #box()[_Hányféleképpen lehet k elemet kiválasztani egy n elemű halmazból, ha a kiválasztás nem sorrendje számít és egy elemet csak egyszer választhatunk? \ Hányféleképpen tudunk kiválasztani 2 könyvet az 5-ből, amit nyaralásra viszünk magunkkal?_ \ \ Ha a sorrend számítana akkor $n!/(n-k)!$ lenne a lehetséges választások száma. Mivel azonban egy lehetőséget ekkor többször is számolunk ezért $k$ elem lehetséges sorrendjét figyelembe kell venni azaz $k!$. Így az osztás-szabály szerint, a lehetséges választások száma $(n!"/"(n-k)!)/k! eq vec(n,k)$ lehetséges sorend van. \ \ $n$ a könyvek száma és $k$ amennyit ki szeretnénk választani, azaz $vec(5,2)$] + _Hányféleképpen lehet k elemet kiválasztani egy n elemű halmazból, ha a kiválasztás nem sorrendje számít és egy elemet többször is választhatunk? \ Hányféleképpen tudunk kiválasztani 3 gombócot választani az 5-féle fagylaltból, ha a választás sorrendje nem számít?_ \ \ Minden lehetséges választás megfelel egy 0-1 sorozatnak: $ 1,1,...1,0,1,1...1,0,1 $ Ekkor elég leszámlálni a lehetséges ilyen típusú sorozatokat. Itt pontosan $n$ darab 1-es van (választott elemek) és $k-1$ darab 0 (szeparátorok száma) azaz $vec(n+k-1,k)$ \ \ $n$ a fagylalt-félék száma és $k$ a gombócok száma, tehát $vec(5+3-1,3) eq vec(7,3)$ #pagebreak() == Gráfok + _Mondja ki a gráf csúcsainak fokszáma és a gráf elszáma közötti osszefüggést! \ Van-e olyan egyszerű gráf, mely csúcsainak fokszámai `1,2,2,2,2,4`? \ Válaszát indokolja!_ \ \ Minden $G eq (V,E) "gráfra " limits(sum)_(v in V) d(v) eq 2 abs(E)$ \ \ Nem létezik, mivel a páratlan fokszámú csúcsok száma nem páros (az `1`-es fokszám miatt). + #box()[_Definiálja gráfok izomorfiáját! \ Mutasson példát két gráfra melyek izomorfak, és adja meg a közöttük lévő izomorfiát is!_ \ \ Két $G eq (V,E) "és " H eq (U,F)$ gráf izomorfak, ha létezik olyan $f : V arrow U$ és $g : E arrow F$ bijekciók (egyértelmű hozzárendelések), hogy $ forall v in V and e in E : v in e arrow.l.r.double.long f(v) in g(e) $ #grid( columns: (auto, auto, auto), gutter: 5pt, image("izom1.png"), image("izom2.png"), image("table.png") )] + _Definiálja a részgráf és feszített részgráf fogalmát! \ Mutasson példát két G ill. H gráfra, melyekre H részgráfja, de nem feszített részgráfja G-nek!_ \ \ Egy $G eq (V,E)$ gráfnak a $H eq (U,F)$ gráf részgráfja, ha $U subset V and F subset E$ \ \ Egy $H eq (U,F)$ egy feszített részgráfja $G eq (V,E)$-nek, ha\ #box()[ - részgráfja: $U subset V and F subset E$ - feszített: $u_1,u_2 in U and {u_1,u_2} in E arrow.long.double {u_1,u_2} in F$ ] #grid( columns: (auto, auto, auto), gutter: 5pt, image("resz1.png"), image("resz2.png"), $H eq G_3 "a feladat szövegében"$ ) + #box()[_Definiálja a séta fogalmát gráfokra! \ Adjon példát két különböző sétára $v_1$ és $v_8$ között az alábbi gráfban:_ \ \ #grid( columns: (auto, auto), gutter: 5pt, align: horizon, image("seta.png"), grid( rows: (auto, auto), gutter: 10pt, $"Legyen "space G eq (V,E) "egy gráf. Egy" v_0,e_1,v_1,...,v_(k-1), e_k, v_k \ "sorozatot "space k"-hosszú sétának nevezünk, ha"$, box()[ - $v_i in V (0 lt.eq i lt.eq k), space e_i in E (1 lt.eq i lt.eq k)$ - $e_i eq {v_(i-1), v_i} (1 lt.eq i lt.eq k)$ ] ) ) \ \ #box()[ + $v_1,e_4,v_5,e_9,v_7,e_8,v_8$ + $v_1,e_1,v_2,e_5,v_3,e_11,v_8$ ] ] + _Definiálja az út fogalmát gráfokra! \ Adjon példát két különböző sétára $v_1$ és $v_8$ között az alábbi gráfban:_ #grid( columns: (auto, auto), gutter: 5pt, align: horizon, image("seta.png"), grid( rows: (auto, auto), gutter: 10pt, $"Legyen "space G eq (V,E) "egy gráf. Egy" v_0,e_1,v_1,...,v_(k-1), e_k, v_k \ "sorozatot "space k"-hosszú útnak nevezünk, ha"$, box()[ - ez egy séta - $v_i eq.not v_j space (i eq.not j)$ ] ) ) \ \ #box()[ + $v_1,e_4,v_5,e_9,v_7,e_8,v_8$ + $v_1,e_1,v_2,e_5,v_3,e_11,v_8$ ] + #box()[_Definiálja az összefüggő gráfok fogalmát! \ Mutasson egy-egy példát összefüggő és nem összefüggő gráfra!_ \ \ Egy $G eq (V,E)$ gráf összefüggő, ha $forall u,v in V, u eq.not v$ van $u$ és $v$ között séta. #align(center, grid( columns: (auto, auto), gutter: 5pt, align: center, grid( columns: (auto, auto), gutter: 5pt, align: horizon, "Összefüggő:", image("ossz.png") ), grid( columns: (auto, auto), gutter: 5pt, align: horizon, "Nem összefüggő:", image("nemossz.png",width: 56%) ), ) ) ] + _Definiálja a fa fogalmát gráfok körében! \ Mutasson egy-egy példát fa és nem fa gráfra!_ \ \ Egy $G eq (V,E)$ gráfot fának hívunk, ha\ #box[ - összefüggő - körmentes ] #align( center,grid( columns: (auto, auto, auto, auto), gutter: 5pt, align: horizon, "fa:", image("fa.png"), "Nem fa mert van benne kör:", image("izom1.png") ) ) + _Definiálja az Euler-séta fogalmát! \ Mutasson példát Euler-sétára az alábbi gráfban:_ \ \ Egy $G$ gráfban a $v_0,e_1,v_1,...,v_(k-1),e_k,v_k$ séta egy Euler-séta, ha #box[ - $e_i eq.not e_j space ( i eq.not j)$ - a séta $G$ minden élét tartalmazza. - zárt Euler-séta: $v_0 eq v_k$ ] #grid( columns: (auto, auto), gutter : 5pt, align: horizon, image("euler.png"), $v_5,e_8,v_6,e_6,v_3,e_5,v_2,e_1,v_1,e_4,v_5,e_7,v_2,e_2,v_4,e_3,v_5$ ) + #box()[_Definiálja a Hamilton-út fogalmát! \ Mutasson példát Hamilton-útra az alábbi gráfban:_ \ \ Legyen $G$ egy véges, egyszerű gráf. A $G$ gráfban egy út Hamilton-út, ha minden csúcsot pontosan egyszer tartalmaz. \ #align(center, grid( columns: (auto, auto), gutter: 5pt, align: horizon, image("euler.png"), $v_1, e_1, v_2, e_2, v_4, e_3, v_5, e_8, v_6, e_6, v_3$ ) ) ]